omaha_client/
state_machine.rs

1// Copyright 2019 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9use crate::{
10    app_set::{AppSet, AppSetExt as _},
11    async_generator,
12    common::{App, CheckOptions, CheckTiming},
13    configuration::Config,
14    cup_ecdsa::{CupDecorationError, CupVerificationError, Cupv2Handler, RequestMetadata},
15    http_request::{self, HttpRequest},
16    installer::{AppInstallResult, Installer, Plan},
17    metrics::{ClockType, Metrics, MetricsReporter, UpdateCheckFailureReason},
18    policy::{CheckDecision, PolicyEngine, UpdateDecision},
19    protocol::{
20        self,
21        request::{Event, EventErrorCode, EventResult, EventType, InstallSource, GUID},
22        response::{parse_json_response, OmahaStatus, Response, UpdateCheck},
23    },
24    request_builder::{self, RequestBuilder, RequestParams},
25    storage::{Storage, StorageExt},
26    time::{ComplexTime, PartialComplexTime, TimeSource, Timer},
27};
28
29use anyhow::anyhow;
30use futures::{
31    channel::{mpsc, oneshot},
32    future::{self, BoxFuture, Fuse},
33    lock::Mutex,
34    prelude::*,
35    select,
36};
37use http::{response::Parts, Response as HttpResponse};
38use log::{error, info, warn};
39use p256::ecdsa::DerSignature;
40use std::{
41    cmp::min,
42    collections::HashMap,
43    convert::TryInto,
44    rc::Rc,
45    str::Utf8Error,
46    time::{Duration, Instant, SystemTime},
47};
48use thiserror::Error;
49
50pub mod update_check;
51
52mod builder;
53pub use builder::StateMachineBuilder;
54
55mod observer;
56use observer::StateMachineProgressObserver;
57pub use observer::{InstallProgress, StateMachineEvent};
58
59const INSTALL_PLAN_ID: &str = "install_plan_id";
60const UPDATE_FIRST_SEEN_TIME: &str = "update_first_seen_time";
61const UPDATE_FINISH_TIME: &str = "update_finish_time";
62const TARGET_VERSION: &str = "target_version";
63const CONSECUTIVE_FAILED_INSTALL_ATTEMPTS: &str = "consecutive_failed_install_attempts";
64// How long do we wait after not allowed to reboot to check again.
65const CHECK_REBOOT_ALLOWED_INTERVAL: Duration = Duration::from_secs(30 * 60);
66// This header contains the number of seconds client must not contact server again.
67const X_RETRY_AFTER: &str = "X-Retry-After";
68// How many requests we will make to Omaha before giving up.
69const MAX_OMAHA_REQUEST_ATTEMPTS: u64 = 3;
70
71/// This is the core state machine for a client's update check.  It is instantiated and used to
72/// perform update checks over time or to perform a single update check process.
73#[derive(Debug)]
74pub struct StateMachine<PE, HR, IN, TM, MR, ST, AS, CH>
75where
76    PE: PolicyEngine,
77    HR: HttpRequest,
78    IN: Installer,
79    TM: Timer,
80    MR: MetricsReporter,
81    ST: Storage,
82    AS: AppSet,
83{
84    /// The immutable configuration of the client itself.
85    config: Config,
86
87    policy_engine: PE,
88
89    http: HR,
90
91    installer: IN,
92
93    timer: TM,
94
95    time_source: PE::TimeSource,
96
97    metrics_reporter: MR,
98
99    storage_ref: Rc<Mutex<ST>>,
100
101    /// Context for update check.
102    context: update_check::Context,
103
104    /// The list of apps used for update check.
105    /// When locking both storage and app_set, make sure to always lock storage first.
106    app_set: Rc<Mutex<AS>>,
107
108    cup_handler: Option<CH>,
109}
110
111#[derive(Copy, Clone, Debug, Eq, PartialEq)]
112pub enum State {
113    Idle,
114    CheckingForUpdates(InstallSource),
115    ErrorCheckingForUpdate,
116    NoUpdateAvailable,
117    InstallationDeferredByPolicy,
118    InstallingUpdate,
119    WaitingForReboot,
120    InstallationError,
121}
122
123/// This is the set of errors that can occur when making a request to Omaha.  This is an internal
124/// collection of error types.
125#[derive(Error, Debug)]
126pub enum OmahaRequestError {
127    #[error("Unexpected JSON error constructing update check")]
128    Json(#[from] serde_json::Error),
129
130    #[error("Error building update check HTTP request")]
131    HttpBuilder(#[from] http::Error),
132
133    #[error("Error decorating outgoing request with CUPv2 parameters")]
134    CupDecoration(#[from] CupDecorationError),
135
136    #[error("Error validating incoming response with CUPv2 protocol")]
137    CupValidation(#[from] CupVerificationError),
138
139    // TODO: This still contains hyper user error which should be split out.
140    #[error("HTTP transport error performing update check")]
141    HttpTransport(#[from] http_request::Error),
142
143    #[error("HTTP error performing update check: {0}")]
144    HttpStatus(hyper::StatusCode),
145}
146
147impl From<request_builder::Error> for OmahaRequestError {
148    fn from(err: request_builder::Error) -> Self {
149        match err {
150            request_builder::Error::Json(e) => OmahaRequestError::Json(e),
151            request_builder::Error::Http(e) => OmahaRequestError::HttpBuilder(e),
152            request_builder::Error::Cup(e) => OmahaRequestError::CupDecoration(e),
153        }
154    }
155}
156
157impl From<http::StatusCode> for OmahaRequestError {
158    fn from(sc: http::StatusCode) -> Self {
159        OmahaRequestError::HttpStatus(sc)
160    }
161}
162
163/// This is the set of errors that can occur when parsing the response body from Omaha.  This is an
164/// internal collection of error types.
165#[derive(Error, Debug)]
166pub enum ResponseParseError {
167    #[error("Response was not valid UTF-8")]
168    Utf8(#[from] Utf8Error),
169
170    #[error("Unexpected JSON error parsing update check response")]
171    Json(#[from] serde_json::Error),
172}
173
174#[derive(Error, Debug)]
175pub enum UpdateCheckError {
176    #[error("Error checking with Omaha")]
177    OmahaRequest(#[from] OmahaRequestError),
178
179    #[error("Error parsing Omaha response")]
180    ResponseParser(#[from] ResponseParseError),
181
182    #[error("Unable to create an install plan")]
183    InstallPlan(#[source] anyhow::Error),
184}
185
186/// A handle to interact with the state machine running in another task.
187#[derive(Clone)]
188pub struct ControlHandle(mpsc::Sender<ControlRequest>);
189
190/// Error indicating that the state machine task no longer exists.
191#[derive(Debug, Clone, Error, PartialEq, Eq)]
192#[error("state machine dropped before all its control handles")]
193pub struct StateMachineGone;
194
195impl From<mpsc::SendError> for StateMachineGone {
196    fn from(_: mpsc::SendError) -> Self {
197        StateMachineGone
198    }
199}
200
201impl From<oneshot::Canceled> for StateMachineGone {
202    fn from(_: oneshot::Canceled) -> Self {
203        StateMachineGone
204    }
205}
206
207enum ControlRequest {
208    StartUpdateCheck {
209        options: CheckOptions,
210        responder: oneshot::Sender<StartUpdateCheckResponse>,
211    },
212}
213
214/// Responses to a request to start an update check now.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub enum StartUpdateCheckResponse {
217    /// The state machine was idle and the request triggered an update check.
218    Started,
219
220    /// The state machine was already processing an update check and ignored this request and
221    /// options.
222    AlreadyRunning,
223
224    /// The update check was throttled by policy.
225    Throttled,
226}
227
228impl ControlHandle {
229    /// Ask the state machine to start an update check with the provided options, returning whether
230    /// or not the state machine started a check or was already running one.
231    pub async fn start_update_check(
232        &mut self,
233        options: CheckOptions,
234    ) -> Result<StartUpdateCheckResponse, StateMachineGone> {
235        let (responder, receive_response) = oneshot::channel();
236        self.0
237            .send(ControlRequest::StartUpdateCheck { options, responder })
238            .await?;
239        Ok(receive_response.await?)
240    }
241}
242
243#[derive(Debug)]
244enum RebootAfterUpdate<T> {
245    Needed(T),
246    NotNeeded,
247}
248
249impl<PE, HR, IN, TM, MR, ST, AS, IR, PL, CH> StateMachine<PE, HR, IN, TM, MR, ST, AS, CH>
250where
251    PE: PolicyEngine<InstallResult = IR, InstallPlan = PL>,
252    HR: HttpRequest,
253    IN: Installer<InstallResult = IR, InstallPlan = PL>,
254    TM: Timer,
255    MR: MetricsReporter,
256    ST: Storage,
257    AS: AppSet,
258    CH: Cupv2Handler,
259    IR: 'static + Send,
260    PL: Plan,
261{
262    /// Ask policy engine for the next update check time and update the context and yield event.
263    async fn update_next_update_time(
264        &mut self,
265        co: &mut async_generator::Yield<StateMachineEvent>,
266    ) -> CheckTiming {
267        let apps = self.app_set.lock().await.get_apps();
268        let timing = self
269            .policy_engine
270            .compute_next_update_time(&apps, &self.context.schedule, &self.context.state)
271            .await;
272        self.context.schedule.next_update_time = Some(timing);
273
274        co.yield_(StateMachineEvent::ScheduleChange(self.context.schedule))
275            .await;
276        info!("Calculated check timing: {}", timing);
277        timing
278    }
279
280    /// Return a future that will wait until the given check timing.
281    async fn make_wait_to_next_check(
282        &mut self,
283        check_timing: CheckTiming,
284    ) -> Fuse<BoxFuture<'static, ()>> {
285        if let Some(minimum_wait) = check_timing.minimum_wait {
286            // If there's a minimum wait, also wait at least that long, by joining the two
287            // timers so that both need to be true (in case `next_update_time` turns out to be
288            // very close to now)
289            future::join(
290                self.timer.wait_for(minimum_wait),
291                self.timer.wait_until(check_timing.time),
292            )
293            .map(|_| ())
294            .boxed()
295            .fuse()
296        } else {
297            // Otherwise just setup the timer for the waiting until the next time.  This is a
298            // wait until either the monotonic or wall times have passed.
299            self.timer.wait_until(check_timing.time).fuse()
300        }
301    }
302
303    async fn run(
304        mut self,
305        mut control: mpsc::Receiver<ControlRequest>,
306        mut co: async_generator::Yield<StateMachineEvent>,
307    ) {
308        {
309            let app_set = self.app_set.lock().await;
310            if !app_set.all_valid() {
311                error!(
312                    "App set not valid, not starting state machine: {:#?}",
313                    app_set.get_apps()
314                );
315                return;
316            }
317        }
318
319        let state_machine_start_monotonic_time = self.time_source.now_in_monotonic();
320
321        let mut should_report_waited_for_reboot_duration = false;
322
323        let update_finish_time = {
324            let storage = self.storage_ref.lock().await;
325            let update_finish_time = storage.get_time(UPDATE_FINISH_TIME).await;
326            if update_finish_time.is_some() {
327                if let Some(target_version) = storage.get_string(TARGET_VERSION).await {
328                    if target_version == self.config.os.version {
329                        should_report_waited_for_reboot_duration = true;
330                    }
331                }
332            }
333            update_finish_time
334        };
335
336        loop {
337            info!("Initial context: {:?}", self.context);
338
339            if should_report_waited_for_reboot_duration {
340                match self.report_waited_for_reboot_duration(
341                    update_finish_time.unwrap(),
342                    state_machine_start_monotonic_time,
343                    self.time_source.now(),
344                ) {
345                    Ok(()) => {
346                        // If the report was successful, don't try again on the next loop.
347                        should_report_waited_for_reboot_duration = false;
348
349                        let mut storage = self.storage_ref.lock().await;
350                        storage.remove_or_log(UPDATE_FINISH_TIME).await;
351                        storage.remove_or_log(TARGET_VERSION).await;
352                        storage.commit_or_log().await;
353                    }
354                    Err(e) => {
355                        warn!(
356                            "Couldn't report wait for reboot duration: {:#}, will try again",
357                            e
358                        );
359                    }
360                }
361            }
362
363            let (mut options, responder) = {
364                let check_timing = self.update_next_update_time(&mut co).await;
365                let mut wait_to_next_check = self.make_wait_to_next_check(check_timing).await;
366
367                // Wait for either the next check time or a request to start an update check.  Use
368                // the default check options with the timed check, or those sent with a request.
369                select! {
370                    () = wait_to_next_check => (CheckOptions::default(), None),
371                    ControlRequest::StartUpdateCheck{options, responder} = control.select_next_some() => {
372                        (options, Some(responder))
373                    }
374                }
375            };
376
377            let reboot_after_update = {
378                let apps = self.app_set.lock().await.get_apps();
379                info!(
380                    "Checking to see if an update check is allowed at this time for {:?}",
381                    apps
382                );
383                let decision = self
384                    .policy_engine
385                    .update_check_allowed(
386                        &apps,
387                        &self.context.schedule,
388                        &self.context.state,
389                        &options,
390                    )
391                    .await;
392
393                info!("The update check decision is: {:?}", decision);
394
395                let request_params = match decision {
396                    // Positive results, will continue with the update check process
397                    CheckDecision::Ok(rp) | CheckDecision::OkUpdateDeferred(rp) => rp,
398
399                    // Negative results, exit early
400                    CheckDecision::TooSoon
401                    | CheckDecision::ThrottledByPolicy
402                    | CheckDecision::DeniedByPolicy => {
403                        info!("The update check is not allowed at this time.");
404                        if let Some(responder) = responder {
405                            let _ = responder.send(StartUpdateCheckResponse::Throttled);
406                        }
407                        continue;
408                    }
409                };
410                if let Some(responder) = responder {
411                    let _ = responder.send(StartUpdateCheckResponse::Started);
412                }
413
414                // "start" the update check itself (well, create the future that is the update check)
415                let update_check = self.start_update_check(request_params, &mut co).fuse();
416                futures::pin_mut!(update_check);
417
418                // Wait for the update check to complete, handling any control requests that come in
419                // during the check.
420                loop {
421                    select! {
422                        update_check_result = update_check => break update_check_result,
423                        ControlRequest::StartUpdateCheck{
424                            options: new_options,
425                            responder
426                        } = control.select_next_some() => {
427                            if new_options.source == InstallSource::OnDemand {
428                                info!("Got on demand update check request, ensuring ongoing check is on demand");
429                                // TODO(63180): merge CheckOptions in Policy, not here.
430                                options.source = InstallSource::OnDemand;
431                            }
432
433                            let _ = responder.send(StartUpdateCheckResponse::AlreadyRunning);
434                        }
435                    }
436                }
437            };
438
439            if let RebootAfterUpdate::Needed(install_result) = reboot_after_update {
440                Self::yield_state(State::WaitingForReboot, &mut co).await;
441                self.wait_for_reboot(options, &mut control, install_result, &mut co)
442                    .await;
443            }
444
445            Self::yield_state(State::Idle, &mut co).await;
446        }
447    }
448
449    async fn wait_for_reboot(
450        &mut self,
451        mut options: CheckOptions,
452        control: &mut mpsc::Receiver<ControlRequest>,
453        install_result: IN::InstallResult,
454        co: &mut async_generator::Yield<StateMachineEvent>,
455    ) {
456        if !self
457            .policy_engine
458            .reboot_allowed(&options, &install_result)
459            .await
460        {
461            let wait_to_see_if_reboot_allowed =
462                self.timer.wait_for(CHECK_REBOOT_ALLOWED_INTERVAL).fuse();
463            futures::pin_mut!(wait_to_see_if_reboot_allowed);
464
465            let check_timing = self.update_next_update_time(co).await;
466            let wait_to_next_ping = self.make_wait_to_next_check(check_timing).await;
467            futures::pin_mut!(wait_to_next_ping);
468
469            loop {
470                // Wait for either the next time to check if reboot allowed or the next
471                // ping time or a request to start an update check.
472
473                select! {
474                    () = wait_to_see_if_reboot_allowed => {
475                        if self.policy_engine.reboot_allowed(&options, &install_result).await {
476                            break;
477                        }
478                        info!("Reboot not allowed at the moment, will try again in 30 minutes...");
479                        wait_to_see_if_reboot_allowed.set(
480                            self.timer.wait_for(CHECK_REBOOT_ALLOWED_INTERVAL).fuse()
481                        );
482                    },
483                    () = wait_to_next_ping => {
484                        self.ping_omaha(co).await;
485                        let check_timing = self.update_next_update_time(co).await;
486                        wait_to_next_ping.set(self.make_wait_to_next_check(check_timing).await);
487                    },
488                    ControlRequest::StartUpdateCheck{
489                        options: new_options,
490                        responder
491                    } = control.select_next_some() => {
492                        let _ = responder.send(StartUpdateCheckResponse::AlreadyRunning);
493                        if new_options.source == InstallSource::OnDemand {
494                            info!("Waiting for reboot, but ensuring that InstallSource is OnDemand");
495                            options.source = InstallSource::OnDemand;
496
497                            if self.policy_engine.reboot_allowed(&options, &install_result).await {
498                                info!("Upgraded update check request to on demand, policy allowed reboot");
499                                break;
500                            }
501                        };
502                    }
503                }
504            }
505        }
506        info!("Rebooting the system at the end of a successful update");
507        if let Err(e) = self.installer.perform_reboot().await {
508            error!("Unable to reboot the system: {}", e);
509        }
510    }
511
512    /// Report the duration the previous boot waited to reboot based on the update finish time in
513    /// storage, and the current time. Does not report a metric if there's an inconsistency in the
514    /// times stored or computed, i.e. if the reboot time is later than the current time.
515    /// Returns an error if time seems incorrect, e.g. update_finish_time is in the future.
516    fn report_waited_for_reboot_duration(
517        &mut self,
518        update_finish_time: SystemTime,
519        state_machine_start_monotonic_time: Instant,
520        now: ComplexTime,
521    ) -> Result<(), anyhow::Error> {
522        // If `update_finish_time` is in the future we don't have correct time, try again
523        // on the next loop.
524        let update_finish_time_to_now =
525            now.wall_duration_since(update_finish_time).map_err(|e| {
526                anyhow!(
527                    "Update finish time later than now, can't report waited for reboot duration,
528                    update finish time: {:?}, now: {:?}, error: {:?}",
529                    update_finish_time,
530                    now,
531                    e,
532                )
533            })?;
534
535        // It might take a while for us to get here, but we only want to report the
536        // time from update finish to state machine start after reboot, so we subtract
537        // the duration since then using monotonic time.
538
539        // We only want to report this metric if we can actually compute it.
540        // If for whatever reason the clock was wrong on the previous boot, or monotonic
541        // time is going backwards, better not to report this metric than to report an
542        // incorrect default value.
543        let state_machine_start_to_now = now
544            .mono
545            .checked_duration_since(state_machine_start_monotonic_time)
546            .ok_or_else(|| {
547                error!("Monotonic time appears to have gone backwards");
548                anyhow!(
549                    "State machine start later than now, can't report waited for reboot duration. \
550                    State machine start: {:?}, now: {:?}",
551                    state_machine_start_monotonic_time,
552                    now.mono,
553                )
554            })?;
555
556        let waited_for_reboot_duration = update_finish_time_to_now
557            .checked_sub(state_machine_start_to_now)
558            .ok_or_else(|| {
559                anyhow!(
560                    "Can't report waiting for reboot duration, update finish time to now smaller \
561                    than state machine start to now. Update finish time to now: {:?}, state \
562                    machine start to now: {:?}",
563                    update_finish_time_to_now,
564                    state_machine_start_to_now,
565                )
566            })?;
567
568        info!(
569            "Waited {} seconds for reboot.",
570            waited_for_reboot_duration.as_secs()
571        );
572        self.report_metrics(Metrics::WaitedForRebootDuration(waited_for_reboot_duration));
573        Ok(())
574    }
575
576    /// Report update check interval based on the last check time stored in storage.
577    /// It will also persist the new last check time to storage.
578    async fn report_check_interval(&mut self, install_source: InstallSource) {
579        let now = self.time_source.now();
580
581        match self.context.schedule.last_update_check_time {
582            // This is our first run; report the interval between that time and now,
583            // and update the context with the complex time.
584            Some(PartialComplexTime::Wall(t)) => match now.wall_duration_since(t) {
585                Ok(interval) => self.report_metrics(Metrics::UpdateCheckInterval {
586                    interval,
587                    clock: ClockType::Wall,
588                    install_source,
589                }),
590                Err(e) => warn!("Last check time is in the future: {}", e),
591            },
592
593            // We've reported an update check before, or we at least have a
594            // PartialComplexTime with a monotonic component. Report our interval
595            // between these Instants. (N.B. strictly speaking, we should only
596            // ever have a PCT::Complex here.)
597            Some(PartialComplexTime::Complex(t)) => match now.mono.checked_duration_since(t.mono) {
598                Some(interval) => self.report_metrics(Metrics::UpdateCheckInterval {
599                    interval,
600                    clock: ClockType::Monotonic,
601                    install_source,
602                }),
603                None => error!("Monotonic time in the past"),
604            },
605
606            // No last check time in storage, and no big deal. We'll continue from
607            // monotonic time from now on. This is the only place other than loading
608            // context from storage where the time can be set, so it's either unset
609            // because no storage, or a complex time. No need to match
610            // Some(PartialComplexTime::Monotonic)
611            _ => {}
612        }
613
614        self.context.schedule.last_update_check_time = now.into();
615    }
616
617    /// Perform update check and handle the result, including updating the update check context
618    /// and cohort.
619    /// Returns whether reboot is needed after the update.
620    async fn start_update_check(
621        &mut self,
622        request_params: RequestParams,
623        co: &mut async_generator::Yield<StateMachineEvent>,
624    ) -> RebootAfterUpdate<IN::InstallResult> {
625        let apps = self.app_set.lock().await.get_apps();
626        let result = self.perform_update_check(request_params, apps, co).await;
627
628        let (result, reboot_after_update) = match result {
629            Ok((result, reboot_after_update)) => {
630                info!("Update check result: {:?}", result);
631                // Update check succeeded, update |last_update_time|.
632                self.context.schedule.last_update_time = Some(self.time_source.now().into());
633
634                // Determine if any app failed to install, or we had a successful update.
635                let install_success =
636                    result.app_responses.iter().fold(None, |result, app| {
637                        match (result, &app.result) {
638                            (_, update_check::Action::InstallPlanExecutionError) => Some(false),
639                            (None, update_check::Action::Updated) => Some(true),
640                            (result, _) => result,
641                        }
642                    });
643
644                // Update check succeeded, reset |consecutive_failed_update_checks| to 0 and
645                // report metrics.
646                self.report_attempts_to_successful_check(true).await;
647
648                self.app_set
649                    .lock()
650                    .await
651                    .update_from_omaha(&result.app_responses);
652
653                // Only report |attempts_to_successful_install| if we get an error trying to
654                // install, or we succeed to install an update without error.
655                if let Some(success) = install_success {
656                    self.report_attempts_to_successful_install(success).await;
657                }
658
659                (Ok(result), reboot_after_update)
660                // TODO: update consecutive_proxied_requests
661            }
662            Err(error) => {
663                error!("Update check failed: {:?}", error);
664
665                let failure_reason = match &error {
666                    UpdateCheckError::ResponseParser(_) | UpdateCheckError::InstallPlan(_) => {
667                        // We talked to Omaha, update |last_update_time|.
668                        self.context.schedule.last_update_time =
669                            Some(self.time_source.now().into());
670
671                        UpdateCheckFailureReason::Omaha
672                    }
673                    UpdateCheckError::OmahaRequest(request_error) => match request_error {
674                        OmahaRequestError::Json(_)
675                        | OmahaRequestError::HttpBuilder(_)
676                        | OmahaRequestError::CupDecoration(_)
677                        | OmahaRequestError::CupValidation(_) => UpdateCheckFailureReason::Internal,
678                        OmahaRequestError::HttpTransport(_) | OmahaRequestError::HttpStatus(_) => {
679                            UpdateCheckFailureReason::Network
680                        }
681                    },
682                };
683                self.report_metrics(Metrics::UpdateCheckFailureReason(failure_reason));
684
685                self.report_attempts_to_successful_check(false).await;
686                (Err(error), RebootAfterUpdate::NotNeeded)
687            }
688        };
689
690        co.yield_(StateMachineEvent::ScheduleChange(self.context.schedule))
691            .await;
692        co.yield_(StateMachineEvent::ProtocolStateChange(
693            self.context.state.clone(),
694        ))
695        .await;
696        co.yield_(StateMachineEvent::UpdateCheckResult(result))
697            .await;
698
699        self.persist_data().await;
700
701        reboot_after_update
702    }
703
704    // Update self.context.state.consecutive_failed_update_checks and report the metric if
705    // `success`. Does not persist the value to storage, but rather relies on the caller.
706    async fn report_attempts_to_successful_check(&mut self, success: bool) {
707        let attempts = self.context.state.consecutive_failed_update_checks + 1;
708        if success {
709            self.context.state.consecutive_failed_update_checks = 0;
710            self.report_metrics(Metrics::AttemptsToSuccessfulCheck(attempts as u64));
711        } else {
712            self.context.state.consecutive_failed_update_checks = attempts;
713        }
714    }
715
716    /// Update `CONSECUTIVE_FAILED_INSTALL_ATTEMPTS` in storage and report the metrics if
717    /// `success`. Does not commit the change to storage.
718    async fn report_attempts_to_successful_install(&mut self, success: bool) {
719        let storage_ref = self.storage_ref.clone();
720        let mut storage = storage_ref.lock().await;
721        let attempts = storage
722            .get_int(CONSECUTIVE_FAILED_INSTALL_ATTEMPTS)
723            .await
724            .unwrap_or(0)
725            + 1;
726
727        self.report_metrics(Metrics::AttemptsToSuccessfulInstall {
728            count: attempts as u64,
729            successful: success,
730        });
731
732        if success {
733            storage
734                .remove_or_log(CONSECUTIVE_FAILED_INSTALL_ATTEMPTS)
735                .await;
736        } else if let Err(e) = storage
737            .set_int(CONSECUTIVE_FAILED_INSTALL_ATTEMPTS, attempts)
738            .await
739        {
740            error!(
741                "Unable to persist {}: {}",
742                CONSECUTIVE_FAILED_INSTALL_ATTEMPTS, e
743            );
744        }
745    }
746
747    /// Persist all necessary data to storage.
748    async fn persist_data(&self) {
749        let mut storage = self.storage_ref.lock().await;
750        self.context.persist(&mut *storage).await;
751        self.app_set.lock().await.persist(&mut *storage).await;
752
753        storage.commit_or_log().await;
754    }
755
756    /// This function constructs the chain of async futures needed to perform all of the async tasks
757    /// that comprise an update check.
758    async fn perform_update_check(
759        &mut self,
760        request_params: RequestParams,
761        apps: Vec<App>,
762        co: &mut async_generator::Yield<StateMachineEvent>,
763    ) -> Result<(update_check::Response, RebootAfterUpdate<IN::InstallResult>), UpdateCheckError>
764    {
765        Self::yield_state(State::CheckingForUpdates(request_params.source), co).await;
766
767        self.report_check_interval(request_params.source).await;
768
769        // Construct a request for the app(s).
770        let config = self.config.clone();
771        let mut request_builder = RequestBuilder::new(&config, &request_params);
772        for app in &apps {
773            request_builder = request_builder.add_update_check(app).add_ping(app);
774        }
775        let session_id = GUID::new();
776        request_builder = request_builder.session_id(session_id.clone());
777
778        let mut omaha_request_attempt = 1;
779
780        // Attempt in an loop of up to MAX_OMAHA_REQUEST_ATTEMPTS to communicate with Omaha.
781        // exit the loop early on success or an error that isn't related to a transport issue.
782        let loop_result = loop {
783            // Mark the start time for the request to omaha.
784            let omaha_check_start_time = self.time_source.now_in_monotonic();
785            request_builder = request_builder.request_id(GUID::new());
786            let result = self
787                .do_omaha_request_and_update_context(&request_builder, co)
788                .await;
789
790            // Report the response time of the omaha request.
791            {
792                // don't use Instant::elapsed(), it doesn't use the right TimeSource, and can panic!
793                // as a result
794                let now = self.time_source.now_in_monotonic();
795                let duration = now.checked_duration_since(omaha_check_start_time);
796
797                if let Some(response_time) = duration {
798                    self.report_metrics(Metrics::UpdateCheckResponseTime {
799                        response_time,
800                        successful: result.is_ok(),
801                    });
802                } else {
803                    // If this happens, it's a bug.
804                    error!(
805                        "now: {:?}, is before omaha_check_start_time: {:?}",
806                        now, omaha_check_start_time
807                    );
808                }
809            }
810
811            match result {
812                Ok(res) => {
813                    break Ok(res);
814                }
815                Err(OmahaRequestError::Json(e)) => {
816                    error!("Unable to construct request body! {:?}", e);
817                    Self::yield_state(State::ErrorCheckingForUpdate, co).await;
818                    break Err(UpdateCheckError::OmahaRequest(e.into()));
819                }
820                Err(OmahaRequestError::HttpBuilder(e)) => {
821                    error!("Unable to construct HTTP request! {:?}", e);
822                    Self::yield_state(State::ErrorCheckingForUpdate, co).await;
823                    break Err(UpdateCheckError::OmahaRequest(e.into()));
824                }
825                Err(OmahaRequestError::CupDecoration(e)) => {
826                    error!(
827                        "Unable to decorate HTTP request with CUPv2 parameters! {:?}",
828                        e
829                    );
830                    Self::yield_state(State::ErrorCheckingForUpdate, co).await;
831                    break Err(UpdateCheckError::OmahaRequest(e.into()));
832                }
833                Err(OmahaRequestError::CupValidation(e)) => {
834                    error!(
835                        "Unable to validate HTTP response with CUPv2 parameters! {:?}",
836                        e
837                    );
838                    Self::yield_state(State::ErrorCheckingForUpdate, co).await;
839                    break Err(UpdateCheckError::OmahaRequest(e.into()));
840                }
841                Err(OmahaRequestError::HttpTransport(e)) => {
842                    warn!("Unable to contact Omaha: {:?}", e);
843                    // Don't retry if the error was caused by user code, which means we weren't
844                    // using the library correctly.
845                    if omaha_request_attempt >= MAX_OMAHA_REQUEST_ATTEMPTS
846                        || e.is_user()
847                        || self.context.state.server_dictated_poll_interval.is_some()
848                    {
849                        Self::yield_state(State::ErrorCheckingForUpdate, co).await;
850                        break Err(UpdateCheckError::OmahaRequest(e.into()));
851                    }
852                }
853                Err(OmahaRequestError::HttpStatus(e)) => {
854                    warn!("Unable to contact Omaha: {:?}", e);
855                    if omaha_request_attempt >= MAX_OMAHA_REQUEST_ATTEMPTS
856                        || self.context.state.server_dictated_poll_interval.is_some()
857                    {
858                        Self::yield_state(State::ErrorCheckingForUpdate, co).await;
859                        break Err(UpdateCheckError::OmahaRequest(e.into()));
860                    }
861                }
862            }
863
864            // TODO(https://fxbug.dev/42117854): Move this to Policy.
865            // Randomized exponential backoff of 1, 2, & 4 seconds, +/- 500ms.
866            let backoff_time_secs = 1 << (omaha_request_attempt - 1);
867            let backoff_time = randomize(backoff_time_secs * 1000, 1000);
868            info!("Waiting {} ms before retrying...", backoff_time);
869            self.timer
870                .wait_for(Duration::from_millis(backoff_time))
871                .await;
872
873            omaha_request_attempt += 1;
874        };
875
876        self.report_metrics(Metrics::RequestsPerCheck {
877            count: omaha_request_attempt,
878            successful: loop_result.is_ok(),
879        });
880
881        let (_parts, data, request_metadata, signature) = loop_result?;
882
883        let response = match Self::parse_omaha_response(&data) {
884            Ok(res) => res,
885            Err(err) => {
886                warn!("Unable to parse Omaha response: {:?}", err);
887                Self::yield_state(State::ErrorCheckingForUpdate, co).await;
888                self.report_omaha_event_and_update_context(
889                    &request_params,
890                    Event::error(EventErrorCode::ParseResponse),
891                    &apps,
892                    &session_id,
893                    &apps.iter().map(|app| (app.id.clone(), None)).collect(),
894                    None,
895                    co,
896                )
897                .await;
898                return Err(UpdateCheckError::ResponseParser(err));
899            }
900        };
901
902        info!("result: {:?}", response);
903
904        co.yield_(StateMachineEvent::OmahaServerResponse(response.clone()))
905            .await;
906
907        let statuses = Self::get_app_update_statuses(&response);
908        for (app_id, status) in &statuses {
909            // TODO:  Report or metric statuses other than 'no-update' and 'ok'
910            info!("Omaha update check status: {} => {:?}", app_id, status);
911        }
912
913        let apps_with_update: Vec<_> = response
914            .apps
915            .iter()
916            .filter(|app| {
917                matches!(
918                    app.update_check,
919                    Some(UpdateCheck {
920                        status: OmahaStatus::Ok,
921                        ..
922                    })
923                )
924            })
925            .collect();
926
927        if apps_with_update.is_empty() {
928            // A successful, no-update, check
929
930            Self::yield_state(State::NoUpdateAvailable, co).await;
931            Self::make_not_updated_result(response, update_check::Action::NoUpdate)
932        } else {
933            info!(
934                "At least one app has an update, proceeding to build and process an Install Plan"
935            );
936            // A map from app id to the new version of the app, if an app has no update, then it
937            // won't appear in this map, if an app has update but there's no version in the omaha
938            // response, then its entry will be None.
939            let next_versions: HashMap<String, Option<String>> = apps_with_update
940                .iter()
941                .map(|app| (app.id.clone(), app.get_manifest_version()))
942                .collect();
943            let install_plan = match self
944                .installer
945                .try_create_install_plan(
946                    &request_params,
947                    request_metadata.as_ref(),
948                    &response,
949                    data,
950                    signature.map(|s| s.as_bytes().to_vec()),
951                )
952                .await
953            {
954                Ok(plan) => plan,
955                Err(e) => {
956                    error!("Unable to construct install plan! {}", e);
957                    Self::yield_state(State::InstallingUpdate, co).await;
958                    Self::yield_state(State::InstallationError, co).await;
959                    self.report_omaha_event_and_update_context(
960                        &request_params,
961                        Event::error(EventErrorCode::ConstructInstallPlan),
962                        &apps,
963                        &session_id,
964                        &next_versions,
965                        None,
966                        co,
967                    )
968                    .await;
969                    return Err(UpdateCheckError::InstallPlan(e.into()));
970                }
971            };
972
973            info!("Validating Install Plan with Policy");
974            let install_plan_decision = self.policy_engine.update_can_start(&install_plan).await;
975            match install_plan_decision {
976                UpdateDecision::Ok => {
977                    info!("Proceeding with install plan.");
978                }
979                UpdateDecision::DeferredByPolicy => {
980                    info!("Install plan was deferred by Policy.");
981                    // Report "error" to Omaha (as this is an event that needs reporting as the
982                    // install isn't starting immediately.
983                    let event = Event {
984                        event_type: EventType::UpdateComplete,
985                        event_result: EventResult::UpdateDeferred,
986                        ..Event::default()
987                    };
988                    self.report_omaha_event_and_update_context(
989                        &request_params,
990                        event,
991                        &apps,
992                        &session_id,
993                        &next_versions,
994                        None,
995                        co,
996                    )
997                    .await;
998
999                    Self::yield_state(State::InstallationDeferredByPolicy, co).await;
1000
1001                    return Self::make_not_updated_result(
1002                        response,
1003                        update_check::Action::DeferredByPolicy,
1004                    );
1005                }
1006                UpdateDecision::DeniedByPolicy => {
1007                    warn!("Install plan was denied by Policy, see Policy logs for reasoning");
1008                    self.report_omaha_event_and_update_context(
1009                        &request_params,
1010                        Event::error(EventErrorCode::DeniedByPolicy),
1011                        &apps,
1012                        &session_id,
1013                        &next_versions,
1014                        None,
1015                        co,
1016                    )
1017                    .await;
1018
1019                    return Self::make_not_updated_result(
1020                        response,
1021                        update_check::Action::DeniedByPolicy,
1022                    );
1023                }
1024            }
1025
1026            Self::yield_state(State::InstallingUpdate, co).await;
1027            self.report_omaha_event_and_update_context(
1028                &request_params,
1029                Event::success(EventType::UpdateDownloadStarted),
1030                &apps,
1031                &session_id,
1032                &next_versions,
1033                None,
1034                co,
1035            )
1036            .await;
1037
1038            let install_plan_id = install_plan.id();
1039            let update_start_time = self.time_source.now_in_walltime();
1040            let update_first_seen_time = self
1041                .record_update_first_seen_time(&install_plan_id, update_start_time)
1042                .await;
1043
1044            let (send, mut recv) = mpsc::channel(0);
1045            let observer = StateMachineProgressObserver(send);
1046            let perform_install = async {
1047                let result = self
1048                    .installer
1049                    .perform_install(&install_plan, Some(&observer))
1050                    .await;
1051                // Drop observer so that we can stop waiting for the next progress.
1052                drop(observer);
1053                result
1054            };
1055            let yield_progress = async {
1056                while let Some(progress) = recv.next().await {
1057                    co.yield_(StateMachineEvent::InstallProgressChange(progress))
1058                        .await;
1059                }
1060            };
1061
1062            let ((install_result, mut app_install_results), ()) =
1063                future::join(perform_install, yield_progress).await;
1064            let no_apps_failed = app_install_results.iter().all(|result| {
1065                matches!(
1066                    result,
1067                    AppInstallResult::Installed | AppInstallResult::Deferred
1068                )
1069            });
1070            let update_finish_time = self.time_source.now_in_walltime();
1071            let install_duration = match update_finish_time.duration_since(update_start_time) {
1072                Ok(duration) => {
1073                    let metrics = if no_apps_failed {
1074                        Metrics::SuccessfulUpdateDuration(duration)
1075                    } else {
1076                        Metrics::FailedUpdateDuration(duration)
1077                    };
1078                    self.report_metrics(metrics);
1079                    Some(duration)
1080                }
1081                Err(e) => {
1082                    warn!("Update start time is in the future: {}", e);
1083                    None
1084                }
1085            };
1086
1087            let config = self.config.clone();
1088            let mut request_builder = RequestBuilder::new(&config, &request_params);
1089            let mut events = vec![];
1090            let mut installed_apps = vec![];
1091            for (response_app, app_install_result) in
1092                apps_with_update.iter().zip(&app_install_results)
1093            {
1094                match apps.iter().find(|app| app.id == response_app.id) {
1095                    Some(app) => {
1096                        let event = match app_install_result {
1097                            AppInstallResult::Installed => {
1098                                installed_apps.push(app);
1099                                Event::success(EventType::UpdateDownloadFinished)
1100                            }
1101                            AppInstallResult::Deferred => Event {
1102                                event_type: EventType::UpdateComplete,
1103                                event_result: EventResult::UpdateDeferred,
1104                                ..Event::default()
1105                            },
1106                            AppInstallResult::Failed(_) => {
1107                                Event::error(EventErrorCode::Installation)
1108                            }
1109                        };
1110                        let event = Event {
1111                            previous_version: Some(app.version.to_string()),
1112                            next_version: response_app.get_manifest_version(),
1113                            download_time_ms: install_duration
1114                                .and_then(|d| d.as_millis().try_into().ok()),
1115                            ..event
1116                        };
1117                        request_builder = request_builder.add_event(app, event.clone());
1118                        events.push(event);
1119                    }
1120                    None => {
1121                        error!("unknown app id in omaha response: {:?}", response_app.id);
1122                    }
1123                }
1124            }
1125            request_builder = request_builder
1126                .session_id(session_id.clone())
1127                .request_id(GUID::new());
1128            if let Err(e) = self
1129                .do_omaha_request_and_update_context(&request_builder, co)
1130                .await
1131            {
1132                for event in events {
1133                    self.report_metrics(Metrics::OmahaEventLost(event));
1134                }
1135                warn!("Unable to report event to Omaha: {:?}", e);
1136            }
1137
1138            // TODO: Verify downloaded update if needed.
1139
1140            // For apps that successfully installed, we need to report an extra `UpdateComplete` event.
1141            if !installed_apps.is_empty() {
1142                self.report_omaha_event_and_update_context(
1143                    &request_params,
1144                    Event::success(EventType::UpdateComplete),
1145                    installed_apps,
1146                    &session_id,
1147                    &next_versions,
1148                    install_duration,
1149                    co,
1150                )
1151                .await;
1152            }
1153
1154            let mut errors = vec![];
1155            let daystart = response.daystart;
1156            let app_responses = response
1157                .apps
1158                .into_iter()
1159                .map(|app| update_check::AppResponse {
1160                    app_id: app.id,
1161                    cohort: app.cohort,
1162                    user_counting: daystart.clone().into(),
1163                    result: match app.update_check {
1164                        Some(UpdateCheck {
1165                            status: OmahaStatus::Ok,
1166                            ..
1167                        }) => match app_install_results.remove(0) {
1168                            AppInstallResult::Installed => update_check::Action::Updated,
1169                            AppInstallResult::Deferred => update_check::Action::DeferredByPolicy,
1170                            AppInstallResult::Failed(e) => {
1171                                errors.push(e);
1172                                update_check::Action::InstallPlanExecutionError
1173                            }
1174                        },
1175                        _ => update_check::Action::NoUpdate,
1176                    },
1177                })
1178                .collect();
1179
1180            if !errors.is_empty() {
1181                for e in errors {
1182                    co.yield_(StateMachineEvent::InstallerError(Some(Box::new(e))))
1183                        .await;
1184                }
1185                Self::yield_state(State::InstallationError, co).await;
1186
1187                return Ok((
1188                    update_check::Response { app_responses },
1189                    RebootAfterUpdate::NotNeeded,
1190                ));
1191            }
1192
1193            match update_finish_time.duration_since(update_first_seen_time) {
1194                Ok(duration) => {
1195                    self.report_metrics(Metrics::SuccessfulUpdateFromFirstSeen(duration))
1196                }
1197                Err(e) => warn!("Update first seen time is in the future: {}", e),
1198            }
1199            {
1200                let mut storage = self.storage_ref.lock().await;
1201                if let Err(e) = storage
1202                    .set_time(UPDATE_FINISH_TIME, update_finish_time)
1203                    .await
1204                {
1205                    error!("Unable to persist {}: {}", UPDATE_FINISH_TIME, e);
1206                }
1207                let app_set = self.app_set.lock().await;
1208                let system_app_id = app_set.get_system_app_id();
1209                // If not found then this is not a system update, so no need to write target version.
1210                if let Some(next_version) = next_versions.get(system_app_id) {
1211                    let target_version = next_version.as_deref().unwrap_or_else(|| {
1212                        error!("Target version string not found in Omaha response.");
1213                        "UNKNOWN"
1214                    });
1215                    if let Err(e) = storage.set_string(TARGET_VERSION, target_version).await {
1216                        error!("Unable to persist {}: {}", TARGET_VERSION, e);
1217                    }
1218                }
1219                storage.commit_or_log().await;
1220            }
1221
1222            let reboot_after_update = if self.policy_engine.reboot_needed(&install_plan).await {
1223                RebootAfterUpdate::Needed(install_result)
1224            } else {
1225                RebootAfterUpdate::NotNeeded
1226            };
1227
1228            Ok((
1229                update_check::Response { app_responses },
1230                reboot_after_update,
1231            ))
1232        }
1233    }
1234
1235    /// Report the given |event| to Omaha, errors occurred during reporting are logged but not
1236    /// acted on.
1237    #[allow(clippy::too_many_arguments)]
1238    async fn report_omaha_event_and_update_context<'a>(
1239        &'a mut self,
1240        request_params: &'a RequestParams,
1241        event: Event,
1242        apps: impl IntoIterator<Item = &App>,
1243        session_id: &GUID,
1244        next_versions: &HashMap<String, Option<String>>,
1245        install_duration: Option<Duration>,
1246        co: &mut async_generator::Yield<StateMachineEvent>,
1247    ) {
1248        let config = self.config.clone();
1249        let mut request_builder = RequestBuilder::new(&config, request_params);
1250        for app in apps {
1251            // Skip apps with no update.
1252            if let Some(next_version) = next_versions.get(&app.id) {
1253                let event = Event {
1254                    previous_version: Some(app.version.to_string()),
1255                    next_version: next_version.clone(),
1256                    download_time_ms: install_duration.and_then(|d| d.as_millis().try_into().ok()),
1257                    ..event.clone()
1258                };
1259                request_builder = request_builder.add_event(app, event);
1260            }
1261        }
1262        request_builder = request_builder
1263            .session_id(session_id.clone())
1264            .request_id(GUID::new());
1265        if let Err(e) = self
1266            .do_omaha_request_and_update_context(&request_builder, co)
1267            .await
1268        {
1269            self.report_metrics(Metrics::OmahaEventLost(event));
1270            warn!("Unable to report event to Omaha: {:?}", e);
1271        }
1272    }
1273
1274    /// Sends a ping to Omaha and updates context and app_set.
1275    async fn ping_omaha(&mut self, co: &mut async_generator::Yield<StateMachineEvent>) {
1276        let apps = self.app_set.lock().await.get_apps();
1277        let request_params = RequestParams {
1278            source: InstallSource::ScheduledTask,
1279            use_configured_proxies: true,
1280            disable_updates: false,
1281            offer_update_if_same_version: false,
1282        };
1283        let config = self.config.clone();
1284        let mut request_builder = RequestBuilder::new(&config, &request_params);
1285        for app in &apps {
1286            request_builder = request_builder.add_ping(app);
1287        }
1288        request_builder = request_builder
1289            .session_id(GUID::new())
1290            .request_id(GUID::new());
1291
1292        let (_parts, data, _request_metadata, _signature) = match self
1293            .do_omaha_request_and_update_context(&request_builder, co)
1294            .await
1295        {
1296            Ok(res) => res,
1297            Err(e) => {
1298                error!("Ping Omaha failed: {:#}", anyhow!(e));
1299                self.context.state.consecutive_failed_update_checks += 1;
1300                self.persist_data().await;
1301                return;
1302            }
1303        };
1304
1305        let response = match Self::parse_omaha_response(&data) {
1306            Ok(res) => res,
1307            Err(e) => {
1308                error!("Unable to parse Omaha response: {:#}", anyhow!(e));
1309                self.context.state.consecutive_failed_update_checks += 1;
1310                self.persist_data().await;
1311                return;
1312            }
1313        };
1314
1315        self.context.state.consecutive_failed_update_checks = 0;
1316
1317        // Even though this is a ping, we should still update the last_update_time for
1318        // policy to compute the next ping time.
1319        self.context.schedule.last_update_time = Some(self.time_source.now().into());
1320        co.yield_(StateMachineEvent::ScheduleChange(self.context.schedule))
1321            .await;
1322
1323        let app_responses = Self::make_app_responses(response, update_check::Action::NoUpdate);
1324        self.app_set.lock().await.update_from_omaha(&app_responses);
1325
1326        self.persist_data().await;
1327    }
1328
1329    /// Make an http request to Omaha, and collect the response into an error or a blob of bytes
1330    /// that can be parsed.
1331    ///
1332    /// Given the http client and the request build, this makes the http request, and then coalesces
1333    /// the various errors into a single error type for easier error handling by the make process
1334    /// flow.
1335    ///
1336    /// This function also converts an HTTP error response into an Error, to divert those into the
1337    /// error handling paths instead of the Ok() path.
1338    ///
1339    /// If a valid X-Retry-After header is found in the response, this function will update the
1340    /// server dictated poll interval in context.
1341    async fn do_omaha_request_and_update_context<'a>(
1342        &'a mut self,
1343        builder: &RequestBuilder<'a>,
1344        co: &mut async_generator::Yield<StateMachineEvent>,
1345    ) -> Result<
1346        (
1347            Parts,
1348            Vec<u8>,
1349            Option<RequestMetadata>,
1350            Option<DerSignature>,
1351        ),
1352        OmahaRequestError,
1353    > {
1354        let (request, request_metadata) = builder.build(self.cup_handler.as_ref())?;
1355        let response = Self::make_request(&mut self.http, request).await?;
1356
1357        let signature: Option<DerSignature> = if let (Some(handler), Some(metadata)) =
1358            (self.cup_handler.as_ref(), &request_metadata)
1359        {
1360            let signature = handler
1361                .verify_response(metadata, &response, metadata.public_key_id)
1362                .map_err(|e| {
1363                    error!("Could not verify response: {:?}", e);
1364                    e
1365                })?;
1366            Some(signature)
1367        } else {
1368            None
1369        };
1370
1371        let (parts, body) = response.into_parts();
1372
1373        // Clients MUST respect this header even if paired with non-successful HTTP response code.
1374        let server_dictated_poll_interval = parts.headers.get(X_RETRY_AFTER).and_then(|header| {
1375            match header
1376                .to_str()
1377                .map_err(|e| anyhow!(e))
1378                .and_then(|s| s.parse::<u64>().map_err(|e| anyhow!(e)))
1379            {
1380                Ok(seconds) => {
1381                    // Servers SHOULD NOT send a value in excess of 86400 (24 hours), and clients
1382                    // SHOULD treat values greater than 86400 as 86400.
1383                    Some(Duration::from_secs(min(seconds, 86400)))
1384                }
1385                Err(e) => {
1386                    error!("Unable to parse {} header: {:#}", X_RETRY_AFTER, e);
1387                    None
1388                }
1389            }
1390        });
1391        if self.context.state.server_dictated_poll_interval != server_dictated_poll_interval {
1392            self.context.state.server_dictated_poll_interval = server_dictated_poll_interval;
1393            co.yield_(StateMachineEvent::ProtocolStateChange(
1394                self.context.state.clone(),
1395            ))
1396            .await;
1397            let mut storage = self.storage_ref.lock().await;
1398            self.context.persist(&mut *storage).await;
1399            storage.commit_or_log().await;
1400        }
1401        if !parts.status.is_success() {
1402            // Convert HTTP failure responses into Errors.
1403            Err(OmahaRequestError::HttpStatus(parts.status))
1404        } else {
1405            // Pass successful responses to the caller.
1406            info!("Omaha HTTP response: {}", parts.status);
1407            Ok((parts, body, request_metadata, signature))
1408        }
1409    }
1410
1411    /// Make an http request and collect the response body into a Vec of bytes.
1412    ///
1413    /// Specifically, this takes the body of the response and concatenates it into a single Vec of
1414    /// bytes so that any errors in receiving it can be captured immediately, instead of needing to
1415    /// handle them as part of parsing the response body.
1416    async fn make_request(
1417        http_client: &mut HR,
1418        request: http::Request<hyper::Body>,
1419    ) -> Result<HttpResponse<Vec<u8>>, http_request::Error> {
1420        info!("Making http request to: {}", request.uri());
1421        http_client.request(request).await.map_err(|err| {
1422            warn!("Unable to perform request: {}", err);
1423            err
1424        })
1425    }
1426
1427    /// This method takes the response bytes from Omaha, and converts them into a protocol::Response
1428    /// struct, returning all of the various errors that can occur in that process as a consolidated
1429    /// error enum.
1430    fn parse_omaha_response(data: &[u8]) -> Result<Response, ResponseParseError> {
1431        parse_json_response(data).map_err(ResponseParseError::Json)
1432    }
1433
1434    /// Utility to extract pairs of app id => omaha status response, to make it easier to ask
1435    /// questions about the response.
1436    fn get_app_update_statuses(response: &Response) -> Vec<(&str, &OmahaStatus)> {
1437        response
1438            .apps
1439            .iter()
1440            .filter_map(|app| {
1441                app.update_check
1442                    .as_ref()
1443                    .map(|u| (app.id.as_str(), &u.status))
1444            })
1445            .collect()
1446    }
1447
1448    /// Utility to take a set of protocol::response::Apps and then construct a set of AppResponse
1449    /// from the update check based on those app IDs.
1450    ///
1451    /// TODO(https://fxbug.dev/42170288): Change the Policy and Installer to return a set of results, one for
1452    ///                        each app ID, then make this match that.
1453    fn make_app_responses(
1454        response: protocol::response::Response,
1455        action: update_check::Action,
1456    ) -> Vec<update_check::AppResponse> {
1457        let daystart = response.daystart;
1458        response
1459            .apps
1460            .into_iter()
1461            .map(|app| update_check::AppResponse {
1462                app_id: app.id,
1463                cohort: app.cohort,
1464                user_counting: daystart.clone().into(),
1465                result: action.clone(),
1466            })
1467            .collect()
1468    }
1469
1470    /// Make an Ok result for `perform_update_check()` when update wasn't installed/failed.
1471    fn make_not_updated_result(
1472        response: protocol::response::Response,
1473        action: update_check::Action,
1474    ) -> Result<(update_check::Response, RebootAfterUpdate<IN::InstallResult>), UpdateCheckError>
1475    {
1476        Ok((
1477            update_check::Response {
1478                app_responses: Self::make_app_responses(response, action),
1479            },
1480            RebootAfterUpdate::NotNeeded,
1481        ))
1482    }
1483
1484    /// Send the state to the observer.
1485    async fn yield_state(state: State, co: &mut async_generator::Yield<StateMachineEvent>) {
1486        co.yield_(StateMachineEvent::StateChange(state)).await;
1487    }
1488
1489    fn report_metrics(&mut self, metrics: Metrics) {
1490        if let Err(err) = self.metrics_reporter.report_metrics(metrics) {
1491            warn!("Unable to report metrics: {:?}", err);
1492        }
1493    }
1494
1495    async fn record_update_first_seen_time(
1496        &mut self,
1497        install_plan_id: &str,
1498        now: SystemTime,
1499    ) -> SystemTime {
1500        let mut storage = self.storage_ref.lock().await;
1501        let previous_id = storage.get_string(INSTALL_PLAN_ID).await;
1502        if let Some(previous_id) = previous_id {
1503            if previous_id == install_plan_id {
1504                return storage
1505                    .get_time(UPDATE_FIRST_SEEN_TIME)
1506                    .await
1507                    .unwrap_or(now);
1508            }
1509        }
1510        // Update INSTALL_PLAN_ID and UPDATE_FIRST_SEEN_TIME for new update.
1511        if let Err(e) = storage.set_string(INSTALL_PLAN_ID, install_plan_id).await {
1512            error!("Unable to persist {}: {}", INSTALL_PLAN_ID, e);
1513            return now;
1514        }
1515        if let Err(e) = storage.set_time(UPDATE_FIRST_SEEN_TIME, now).await {
1516            error!("Unable to persist {}: {}", UPDATE_FIRST_SEEN_TIME, e);
1517            let _ = storage.remove(INSTALL_PLAN_ID).await;
1518            return now;
1519        }
1520        storage.commit_or_log().await;
1521        now
1522    }
1523}
1524
1525/// Return a random number in [n - range / 2, n - range / 2 + range).
1526fn randomize(n: u64, range: u64) -> u64 {
1527    n - range / 2 + rand::random::<u64>() % range
1528}
1529
1530#[cfg(test)]
1531impl<PE, HR, IN, TM, MR, ST, AS, IR, PL, CH> StateMachine<PE, HR, IN, TM, MR, ST, AS, CH>
1532where
1533    PE: PolicyEngine<InstallResult = IR, InstallPlan = PL>,
1534    HR: HttpRequest,
1535    IN: Installer<InstallResult = IR, InstallPlan = PL>,
1536    TM: Timer,
1537    MR: MetricsReporter,
1538    ST: Storage,
1539    AS: AppSet,
1540    CH: Cupv2Handler,
1541    IR: 'static + Send,
1542    PL: Plan,
1543{
1544    /// Run perform_update_check once, returning the update check result.
1545    async fn oneshot(
1546        &mut self,
1547        request_params: RequestParams,
1548    ) -> Result<(update_check::Response, RebootAfterUpdate<IN::InstallResult>), UpdateCheckError>
1549    {
1550        let apps = self.app_set.lock().await.get_apps();
1551
1552        async_generator::generate(move |mut co| async move {
1553            self.perform_update_check(request_params, apps, &mut co)
1554                .await
1555        })
1556        .into_complete()
1557        .await
1558    }
1559
1560    /// Run start_upate_check once, discarding its states.
1561    async fn run_once(&mut self) {
1562        let request_params = RequestParams::default();
1563
1564        async_generator::generate(move |mut co| async move {
1565            self.start_update_check(request_params, &mut co).await;
1566        })
1567        .map(|_| ())
1568        .collect::<()>()
1569        .await;
1570    }
1571}
1572
1573#[cfg(test)]
1574mod tests {
1575    use super::update_check::{
1576        Action, CONSECUTIVE_FAILED_UPDATE_CHECKS, LAST_UPDATE_TIME, SERVER_DICTATED_POLL_INTERVAL,
1577    };
1578    use super::*;
1579    use crate::{
1580        app_set::VecAppSet,
1581        common::{
1582            App, CheckOptions, PersistedApp, ProtocolState, UpdateCheckSchedule, UserCounting,
1583        },
1584        configuration::Updater,
1585        cup_ecdsa::test_support::{make_cup_handler_for_test, MockCupv2Handler},
1586        http_request::mock::MockHttpRequest,
1587        installer::{
1588            stub::{StubInstallErrors, StubInstaller, StubPlan},
1589            ProgressObserver,
1590        },
1591        metrics::MockMetricsReporter,
1592        policy::{MockPolicyEngine, StubPolicyEngine},
1593        protocol::{request::OS, response, Cohort},
1594        storage::MemStorage,
1595        time::{
1596            timers::{BlockingTimer, MockTimer, RequestedWait},
1597            MockTimeSource, PartialComplexTime,
1598        },
1599        version::Version,
1600    };
1601    use assert_matches::assert_matches;
1602    use futures::executor::{block_on, LocalPool};
1603    use futures::future::LocalBoxFuture;
1604    use futures::task::LocalSpawnExt;
1605    use pretty_assertions::assert_eq;
1606    use serde_json::json;
1607    use std::cell::RefCell;
1608    use std::time::Duration;
1609
1610    fn make_test_app_set() -> Rc<Mutex<VecAppSet>> {
1611        Rc::new(Mutex::new(VecAppSet::new(vec![App::builder()
1612            .id("{00000000-0000-0000-0000-000000000001}")
1613            .version([1, 2, 3, 4])
1614            .cohort(Cohort::new("stable-channel"))
1615            .build()])))
1616    }
1617
1618    fn make_update_available_response() -> HttpResponse<Vec<u8>> {
1619        let response = json!({"response":{
1620          "server": "prod",
1621          "protocol": "3.0",
1622          "app": [{
1623            "appid": "{00000000-0000-0000-0000-000000000001}",
1624            "status": "ok",
1625            "updatecheck": {
1626              "status": "ok"
1627            }
1628          }],
1629        }});
1630        HttpResponse::new(serde_json::to_vec(&response).unwrap())
1631    }
1632
1633    fn make_noupdate_httpresponse() -> Vec<u8> {
1634        serde_json::to_vec(
1635            &(json!({"response":{
1636              "server": "prod",
1637              "protocol": "3.0",
1638              "app": [{
1639                "appid": "{00000000-0000-0000-0000-000000000001}",
1640                "status": "ok",
1641                "updatecheck": {
1642                  "status": "noupdate"
1643                }
1644              }]
1645            }})),
1646        )
1647        .unwrap()
1648    }
1649
1650    // Assert that the last request made to |http| is equal to the request built by
1651    // |request_builder|.
1652    async fn assert_request<'a>(http: &MockHttpRequest, request_builder: RequestBuilder<'a>) {
1653        let cup_handler = make_cup_handler_for_test();
1654        let (request, _request_metadata) = request_builder.build(Some(&cup_handler)).unwrap();
1655        let body = hyper::body::to_bytes(request).await.unwrap();
1656        // Compare string instead of Vec<u8> for easier debugging.
1657        let body_str = String::from_utf8_lossy(&body);
1658        http.assert_body_str(&body_str).await;
1659    }
1660
1661    #[test]
1662    fn run_simple_check_with_noupdate_result() {
1663        block_on(async {
1664            let http = MockHttpRequest::new(HttpResponse::new(make_noupdate_httpresponse()));
1665
1666            StateMachineBuilder::new_stub()
1667                .http(http)
1668                .oneshot(RequestParams::default())
1669                .await
1670                .unwrap();
1671
1672            info!("update check complete!");
1673        });
1674    }
1675
1676    #[test]
1677    fn test_cohort_returned_with_noupdate_result() {
1678        block_on(async {
1679            let response = json!({"response":{
1680              "server": "prod",
1681              "protocol": "3.0",
1682              "app": [{
1683                "appid": "{00000000-0000-0000-0000-000000000001}",
1684                "status": "ok",
1685                "cohort": "1",
1686                "cohortname": "stable-channel",
1687                "updatecheck": {
1688                  "status": "noupdate"
1689                }
1690              }]
1691            }});
1692            let response = serde_json::to_vec(&response).unwrap();
1693            let http = MockHttpRequest::new(HttpResponse::new(response));
1694
1695            let (response, reboot_after_update) = StateMachineBuilder::new_stub()
1696                .http(http)
1697                .oneshot(RequestParams::default())
1698                .await
1699                .unwrap();
1700            assert_eq!(
1701                "{00000000-0000-0000-0000-000000000001}",
1702                response.app_responses[0].app_id
1703            );
1704            assert_eq!(Some("1".into()), response.app_responses[0].cohort.id);
1705            assert_eq!(
1706                Some("stable-channel".into()),
1707                response.app_responses[0].cohort.name
1708            );
1709            assert_eq!(None, response.app_responses[0].cohort.hint);
1710
1711            assert_matches!(reboot_after_update, RebootAfterUpdate::NotNeeded);
1712        });
1713    }
1714
1715    #[test]
1716    fn test_cohort_returned_with_update_result() {
1717        block_on(async {
1718            let response = json!({"response":{
1719              "server": "prod",
1720              "protocol": "3.0",
1721              "app": [{
1722                "appid": "{00000000-0000-0000-0000-000000000001}",
1723                "status": "ok",
1724                "cohort": "1",
1725                "cohortname": "stable-channel",
1726                "updatecheck": {
1727                  "status": "ok"
1728                }
1729              }]
1730            }});
1731            let response = serde_json::to_vec(&response).unwrap();
1732            let http = MockHttpRequest::new(HttpResponse::new(response));
1733
1734            let (response, reboot_after_update) = StateMachineBuilder::new_stub()
1735                .http(http)
1736                .oneshot(RequestParams::default())
1737                .await
1738                .unwrap();
1739            assert_eq!(
1740                "{00000000-0000-0000-0000-000000000001}",
1741                response.app_responses[0].app_id
1742            );
1743            assert_eq!(Some("1".into()), response.app_responses[0].cohort.id);
1744            assert_eq!(
1745                Some("stable-channel".into()),
1746                response.app_responses[0].cohort.name
1747            );
1748            assert_eq!(None, response.app_responses[0].cohort.hint);
1749
1750            assert_matches!(reboot_after_update, RebootAfterUpdate::Needed(()));
1751        });
1752    }
1753
1754    #[test]
1755    fn test_report_parse_response_error() {
1756        block_on(async {
1757            let http = MockHttpRequest::new(HttpResponse::new("invalid response".into()));
1758
1759            let mut state_machine = StateMachineBuilder::new_stub().http(http).build().await;
1760
1761            let response = state_machine.oneshot(RequestParams::default()).await;
1762            assert_matches!(response, Err(UpdateCheckError::ResponseParser(_)));
1763
1764            let request_params = RequestParams::default();
1765            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
1766            let event = Event {
1767                previous_version: Some("1.2.3.4".to_string()),
1768                ..Event::error(EventErrorCode::ParseResponse)
1769            };
1770            let apps = state_machine.app_set.lock().await.get_apps();
1771            request_builder = request_builder
1772                .add_event(&apps[0], event)
1773                .session_id(GUID::from_u128(0))
1774                .request_id(GUID::from_u128(2));
1775            assert_request(&state_machine.http, request_builder).await;
1776        });
1777    }
1778
1779    #[test]
1780    fn test_report_construct_install_plan_error() {
1781        block_on(async {
1782            let response = json!({"response":{
1783              "server": "prod",
1784              "protocol": "4.0",
1785              "app": [{
1786                "appid": "{00000000-0000-0000-0000-000000000001}",
1787                "status": "ok",
1788                "updatecheck": {
1789                  "status": "ok"
1790                }
1791              }],
1792            }});
1793            let response = serde_json::to_vec(&response).unwrap();
1794            let http = MockHttpRequest::new(HttpResponse::new(response));
1795
1796            let mut state_machine = StateMachineBuilder::new_stub().http(http).build().await;
1797
1798            let response = state_machine.oneshot(RequestParams::default()).await;
1799            assert_matches!(response, Err(UpdateCheckError::InstallPlan(_)));
1800
1801            let request_params = RequestParams::default();
1802            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
1803            let event = Event {
1804                previous_version: Some("1.2.3.4".to_string()),
1805                ..Event::error(EventErrorCode::ConstructInstallPlan)
1806            };
1807            let apps = state_machine.app_set.lock().await.get_apps();
1808            request_builder = request_builder
1809                .add_event(&apps[0], event)
1810                .session_id(GUID::from_u128(0))
1811                .request_id(GUID::from_u128(2));
1812            assert_request(&state_machine.http, request_builder).await;
1813        });
1814    }
1815
1816    #[test]
1817    fn test_report_installation_error() {
1818        block_on(async {
1819            let response = json!({"response":{
1820              "server": "prod",
1821              "protocol": "3.0",
1822              "app": [{
1823                "appid": "{00000000-0000-0000-0000-000000000001}",
1824                "status": "ok",
1825                "updatecheck": {
1826                  "status": "ok",
1827                  "manifest": {
1828                      "version": "5.6.7.8",
1829                      "actions": {
1830                          "action": [],
1831                      },
1832                      "packages": {
1833                          "package": [],
1834                      },
1835                  }
1836                }
1837              }],
1838            }});
1839            let response = serde_json::to_vec(&response).unwrap();
1840            let http = MockHttpRequest::new(HttpResponse::new(response));
1841
1842            let mut state_machine = StateMachineBuilder::new_stub()
1843                .http(http)
1844                .installer(StubInstaller { should_fail: true })
1845                .build()
1846                .await;
1847
1848            let (response, reboot_after_update) = state_machine
1849                .oneshot(RequestParams::default())
1850                .await
1851                .unwrap();
1852            assert_eq!(
1853                Action::InstallPlanExecutionError,
1854                response.app_responses[0].result
1855            );
1856            assert_matches!(reboot_after_update, RebootAfterUpdate::NotNeeded);
1857
1858            let request_params = RequestParams::default();
1859            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
1860            let event = Event {
1861                previous_version: Some("1.2.3.4".to_string()),
1862                next_version: Some("5.6.7.8".to_string()),
1863                download_time_ms: Some(0),
1864                ..Event::error(EventErrorCode::Installation)
1865            };
1866            let apps = state_machine.app_set.lock().await.get_apps();
1867            request_builder = request_builder
1868                .add_event(&apps[0], event)
1869                .session_id(GUID::from_u128(0))
1870                .request_id(GUID::from_u128(3));
1871            assert_request(&state_machine.http, request_builder).await;
1872        });
1873    }
1874
1875    #[test]
1876    fn test_report_installation_error_multi_app() {
1877        block_on(async {
1878            // Intentionally made the app order in response and app_set different.
1879            let response = json!({"response":{
1880              "server": "prod",
1881              "protocol": "3.0",
1882              "app": [{
1883                "appid": "appid_3",
1884                "status": "ok",
1885                "updatecheck": {
1886                  "status": "ok",
1887                  "manifest": {
1888                      "version": "5.6.7.8",
1889                      "actions": {
1890                          "action": [],
1891                      },
1892                      "packages": {
1893                          "package": [],
1894                      },
1895                  }
1896                }
1897              },{
1898                "appid": "appid_1",
1899                "status": "ok",
1900                "updatecheck": {
1901                  "status": "ok",
1902                  "manifest": {
1903                      "version": "1.2.3.4",
1904                      "actions": {
1905                          "action": [],
1906                      },
1907                      "packages": {
1908                          "package": [],
1909                      },
1910                  }
1911                }
1912              },{
1913                "appid": "appid_2",
1914                "status": "ok",
1915                "updatecheck": {
1916                  "status": "noupdate",
1917                }
1918              }],
1919            }});
1920            let response = serde_json::to_vec(&response).unwrap();
1921            let mut http = MockHttpRequest::new(HttpResponse::new(response));
1922            http.add_response(HttpResponse::new(vec![]));
1923            let app_set = VecAppSet::new(vec![
1924                App::builder().id("appid_1").version([1, 2, 3, 3]).build(),
1925                App::builder().id("appid_2").version([9, 9, 9, 9]).build(),
1926                App::builder().id("appid_3").version([5, 6, 7, 7]).build(),
1927            ]);
1928            let app_set = Rc::new(Mutex::new(app_set));
1929            let (send_install, mut recv_install) = mpsc::channel(0);
1930
1931            let mut state_machine = StateMachineBuilder::new_stub()
1932                .app_set(Rc::clone(&app_set))
1933                .http(http)
1934                .installer(BlockingInstaller {
1935                    on_install: send_install,
1936                    on_reboot: None,
1937                })
1938                .build()
1939                .await;
1940
1941            let recv_install_fut = async move {
1942                let unblock_install = recv_install.next().await.unwrap();
1943                unblock_install
1944                    .send(vec![
1945                        AppInstallResult::Deferred,
1946                        AppInstallResult::Installed,
1947                    ])
1948                    .unwrap();
1949            };
1950
1951            let (oneshot_result, ()) = future::join(
1952                state_machine.oneshot(RequestParams::default()),
1953                recv_install_fut,
1954            )
1955            .await;
1956            let (response, reboot_after_update) = oneshot_result.unwrap();
1957
1958            assert_eq!("appid_3", response.app_responses[0].app_id);
1959            assert_eq!(Action::DeferredByPolicy, response.app_responses[0].result);
1960            assert_eq!("appid_1", response.app_responses[1].app_id);
1961            assert_eq!(Action::Updated, response.app_responses[1].result);
1962            assert_eq!("appid_2", response.app_responses[2].app_id);
1963            assert_eq!(Action::NoUpdate, response.app_responses[2].result);
1964            assert_matches!(reboot_after_update, RebootAfterUpdate::Needed(()));
1965
1966            let request_params = RequestParams::default();
1967            let apps = app_set.lock().await.get_apps();
1968
1969            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
1970            let event = Event {
1971                previous_version: Some("1.2.3.3".to_string()),
1972                next_version: Some("1.2.3.4".to_string()),
1973                download_time_ms: Some(0),
1974                ..Event::success(EventType::UpdateComplete)
1975            };
1976            request_builder = request_builder
1977                .add_event(&apps[0], event)
1978                .session_id(GUID::from_u128(0))
1979                .request_id(GUID::from_u128(4));
1980            assert_request(&state_machine.http, request_builder).await;
1981
1982            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
1983            let event1 = Event {
1984                previous_version: Some("1.2.3.3".to_string()),
1985                next_version: Some("1.2.3.4".to_string()),
1986                download_time_ms: Some(0),
1987                ..Event::success(EventType::UpdateDownloadFinished)
1988            };
1989            let event2 = Event {
1990                previous_version: Some("5.6.7.7".to_string()),
1991                next_version: Some("5.6.7.8".to_string()),
1992                download_time_ms: Some(0),
1993                event_type: EventType::UpdateComplete,
1994                event_result: EventResult::UpdateDeferred,
1995                ..Event::default()
1996            };
1997            request_builder = request_builder
1998                .add_event(&apps[2], event2)
1999                .add_event(&apps[0], event1)
2000                .session_id(GUID::from_u128(0))
2001                .request_id(GUID::from_u128(3));
2002            assert_request(&state_machine.http, request_builder).await;
2003        });
2004    }
2005
2006    // Test that our observer can see when there's an installation error, and that it gets
2007    // the right error type.
2008    #[test]
2009    fn test_observe_installation_error() {
2010        block_on(async {
2011            let http = MockHttpRequest::new(make_update_available_response());
2012
2013            let actual_errors = StateMachineBuilder::new_stub()
2014                .http(http)
2015                .installer(StubInstaller { should_fail: true })
2016                .oneshot_check()
2017                .await
2018                .filter_map(|event| {
2019                    future::ready(match event {
2020                        StateMachineEvent::InstallerError(Some(e)) => {
2021                            Some(*e.downcast::<StubInstallErrors>().unwrap())
2022                        }
2023                        _ => None,
2024                    })
2025                })
2026                .collect::<Vec<StubInstallErrors>>()
2027                .await;
2028
2029            let expected_errors = vec![StubInstallErrors::Failed];
2030            assert_eq!(actual_errors, expected_errors);
2031        });
2032    }
2033
2034    #[test]
2035    fn test_report_deferred_by_policy() {
2036        block_on(async {
2037            let http = MockHttpRequest::new(make_update_available_response());
2038
2039            let policy_engine = MockPolicyEngine {
2040                update_decision: UpdateDecision::DeferredByPolicy,
2041                ..MockPolicyEngine::default()
2042            };
2043            let mut state_machine = StateMachineBuilder::new_stub()
2044                .policy_engine(policy_engine)
2045                .http(http)
2046                .build()
2047                .await;
2048
2049            let (response, reboot_after_update) = state_machine
2050                .oneshot(RequestParams::default())
2051                .await
2052                .unwrap();
2053            assert_eq!(Action::DeferredByPolicy, response.app_responses[0].result);
2054            assert_matches!(reboot_after_update, RebootAfterUpdate::NotNeeded);
2055
2056            let request_params = RequestParams::default();
2057            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
2058            let event = Event {
2059                event_type: EventType::UpdateComplete,
2060                event_result: EventResult::UpdateDeferred,
2061                previous_version: Some("1.2.3.4".to_string()),
2062                ..Event::default()
2063            };
2064            let apps = state_machine.app_set.lock().await.get_apps();
2065            request_builder = request_builder
2066                .add_event(&apps[0], event)
2067                .session_id(GUID::from_u128(0))
2068                .request_id(GUID::from_u128(2));
2069            assert_request(&state_machine.http, request_builder).await;
2070        });
2071    }
2072
2073    #[test]
2074    fn test_report_denied_by_policy() {
2075        block_on(async {
2076            let response = make_update_available_response();
2077            let http = MockHttpRequest::new(response);
2078            let policy_engine = MockPolicyEngine {
2079                update_decision: UpdateDecision::DeniedByPolicy,
2080                ..MockPolicyEngine::default()
2081            };
2082
2083            let mut state_machine = StateMachineBuilder::new_stub()
2084                .policy_engine(policy_engine)
2085                .http(http)
2086                .build()
2087                .await;
2088
2089            let (response, reboot_after_update) = state_machine
2090                .oneshot(RequestParams::default())
2091                .await
2092                .unwrap();
2093            assert_eq!(Action::DeniedByPolicy, response.app_responses[0].result);
2094            assert_matches!(reboot_after_update, RebootAfterUpdate::NotNeeded);
2095
2096            let request_params = RequestParams::default();
2097            let mut request_builder = RequestBuilder::new(&state_machine.config, &request_params);
2098            let event = Event {
2099                previous_version: Some("1.2.3.4".to_string()),
2100                ..Event::error(EventErrorCode::DeniedByPolicy)
2101            };
2102            let apps = state_machine.app_set.lock().await.get_apps();
2103            request_builder = request_builder
2104                .add_event(&apps[0], event)
2105                .session_id(GUID::from_u128(0))
2106                .request_id(GUID::from_u128(2));
2107            assert_request(&state_machine.http, request_builder).await;
2108        });
2109    }
2110
2111    #[test]
2112    fn test_wait_timer() {
2113        let mut pool = LocalPool::new();
2114        let mock_time = MockTimeSource::new_from_now();
2115        let next_update_time = mock_time.now() + Duration::from_secs(111);
2116        let (timer, mut timers) = BlockingTimer::new();
2117        let policy_engine = MockPolicyEngine {
2118            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
2119            time_source: mock_time,
2120            ..MockPolicyEngine::default()
2121        };
2122
2123        let (_ctl, state_machine) = pool.run_until(
2124            StateMachineBuilder::new_stub()
2125                .policy_engine(policy_engine)
2126                .timer(timer)
2127                .start(),
2128        );
2129
2130        pool.spawner()
2131            .spawn_local(state_machine.map(|_| ()).collect())
2132            .unwrap();
2133
2134        // With otherwise stub implementations, the pool stalls when a timer is awaited.  Dropping
2135        // the state machine will panic if any timer durations were not used.
2136        let blocked_timer = pool.run_until(timers.next()).unwrap();
2137        assert_eq!(
2138            blocked_timer.requested_wait(),
2139            RequestedWait::Until(next_update_time.into())
2140        );
2141    }
2142
2143    #[test]
2144    fn test_cohort_and_user_counting_updates_are_used_in_subsequent_requests() {
2145        block_on(async {
2146            let response = json!({"response":{
2147                "server": "prod",
2148                "protocol": "3.0",
2149                "daystart": {
2150                  "elapsed_days": 1234567,
2151                  "elapsed_seconds": 3645
2152                },
2153                "app": [{
2154                  "appid": "{00000000-0000-0000-0000-000000000001}",
2155                  "status": "ok",
2156                  "cohort": "1",
2157                  "cohortname": "stable-channel",
2158                  "updatecheck": {
2159                    "status": "noupdate"
2160                  }
2161                }]
2162            }});
2163            let response = serde_json::to_vec(&response).unwrap();
2164            let mut http = MockHttpRequest::new(HttpResponse::new(response.clone()));
2165            http.add_response(HttpResponse::new(response));
2166            let apps = make_test_app_set();
2167
2168            let mut state_machine = StateMachineBuilder::new_stub()
2169                .http(http)
2170                .app_set(apps.clone())
2171                .build()
2172                .await;
2173
2174            // Run it the first time.
2175            state_machine.run_once().await;
2176
2177            let apps = apps.lock().await.get_apps();
2178            assert_eq!(Some("1".to_string()), apps[0].cohort.id);
2179            assert_eq!(None, apps[0].cohort.hint);
2180            assert_eq!(Some("stable-channel".to_string()), apps[0].cohort.name);
2181            assert_eq!(
2182                UserCounting::ClientRegulatedByDate(Some(1234567)),
2183                apps[0].user_counting
2184            );
2185
2186            // Run it the second time.
2187            state_machine.run_once().await;
2188
2189            let request_params = RequestParams::default();
2190            let expected_request_builder =
2191                RequestBuilder::new(&state_machine.config, &request_params)
2192                    .add_update_check(&apps[0])
2193                    .add_ping(&apps[0])
2194                    .session_id(GUID::from_u128(2))
2195                    .request_id(GUID::from_u128(3));
2196            // Check that the second update check used the new app.
2197            assert_request(&state_machine.http, expected_request_builder).await;
2198        });
2199    }
2200
2201    #[test]
2202    fn test_user_counting_returned() {
2203        block_on(async {
2204            let response = json!({"response":{
2205            "server": "prod",
2206            "protocol": "3.0",
2207            "daystart": {
2208              "elapsed_days": 1234567,
2209              "elapsed_seconds": 3645
2210            },
2211            "app": [{
2212              "appid": "{00000000-0000-0000-0000-000000000001}",
2213              "status": "ok",
2214              "cohort": "1",
2215              "cohortname": "stable-channel",
2216              "updatecheck": {
2217                "status": "noupdate"
2218                  }
2219              }]
2220            }});
2221            let response = serde_json::to_vec(&response).unwrap();
2222            let http = MockHttpRequest::new(HttpResponse::new(response));
2223
2224            let (response, reboot_after_update) = StateMachineBuilder::new_stub()
2225                .http(http)
2226                .oneshot(RequestParams::default())
2227                .await
2228                .unwrap();
2229
2230            assert_eq!(
2231                UserCounting::ClientRegulatedByDate(Some(1234567)),
2232                response.app_responses[0].user_counting
2233            );
2234            assert_matches!(reboot_after_update, RebootAfterUpdate::NotNeeded);
2235        });
2236    }
2237
2238    #[test]
2239    fn test_observe_state() {
2240        block_on(async {
2241            let actual_states = StateMachineBuilder::new_stub()
2242                .oneshot_check()
2243                .await
2244                .filter_map(|event| {
2245                    future::ready(match event {
2246                        StateMachineEvent::StateChange(state) => Some(state),
2247                        _ => None,
2248                    })
2249                })
2250                .collect::<Vec<State>>()
2251                .await;
2252
2253            let expected_states = vec![
2254                State::CheckingForUpdates(InstallSource::ScheduledTask),
2255                State::ErrorCheckingForUpdate,
2256            ];
2257            assert_eq!(actual_states, expected_states);
2258        });
2259    }
2260
2261    #[test]
2262    fn test_observe_schedule() {
2263        block_on(async {
2264            let mock_time = MockTimeSource::new_from_now();
2265            let actual_schedules = StateMachineBuilder::new_stub()
2266                .policy_engine(StubPolicyEngine::new(&mock_time))
2267                .oneshot_check()
2268                .await
2269                .filter_map(|event| {
2270                    future::ready(match event {
2271                        StateMachineEvent::ScheduleChange(schedule) => Some(schedule),
2272                        _ => None,
2273                    })
2274                })
2275                .collect::<Vec<UpdateCheckSchedule>>()
2276                .await;
2277
2278            // The resultant schedule should only contain the timestamp of the above update check.
2279            let expected_schedule = UpdateCheckSchedule::builder()
2280                .last_update_time(mock_time.now())
2281                .last_update_check_time(mock_time.now())
2282                .build();
2283
2284            assert_eq!(actual_schedules, vec![expected_schedule]);
2285        });
2286    }
2287
2288    #[test]
2289    fn test_observe_protocol_state() {
2290        block_on(async {
2291            let actual_protocol_states = StateMachineBuilder::new_stub()
2292                .oneshot_check()
2293                .await
2294                .filter_map(|event| {
2295                    future::ready(match event {
2296                        StateMachineEvent::ProtocolStateChange(state) => Some(state),
2297                        _ => None,
2298                    })
2299                })
2300                .collect::<Vec<ProtocolState>>()
2301                .await;
2302
2303            let expected_protocol_state = ProtocolState {
2304                consecutive_failed_update_checks: 1,
2305                ..ProtocolState::default()
2306            };
2307
2308            assert_eq!(actual_protocol_states, vec![expected_protocol_state]);
2309        });
2310    }
2311
2312    #[test]
2313    fn test_observe_omaha_server_response() {
2314        block_on(async {
2315            let response = json!({"response":{
2316              "server": "prod",
2317              "protocol": "3.0",
2318              "app": [{
2319                "appid": "{00000000-0000-0000-0000-000000000001}",
2320                "status": "ok",
2321                "cohort": "1",
2322                "cohortname": "stable-channel",
2323                "updatecheck": {
2324                  "status": "noupdate"
2325                }
2326              }]
2327            }});
2328            let response = serde_json::to_vec(&response).unwrap();
2329            let expected_omaha_response = response::parse_json_response(&response).unwrap();
2330            let http = MockHttpRequest::new(HttpResponse::new(response));
2331
2332            let actual_omaha_response = StateMachineBuilder::new_stub()
2333                .http(http)
2334                .oneshot_check()
2335                .await
2336                .filter_map(|event| {
2337                    future::ready(match event {
2338                        StateMachineEvent::OmahaServerResponse(response) => Some(response),
2339                        _ => None,
2340                    })
2341                })
2342                .collect::<Vec<response::Response>>()
2343                .await;
2344
2345            assert_eq!(actual_omaha_response, vec![expected_omaha_response]);
2346        });
2347    }
2348
2349    #[test]
2350    fn test_metrics_report_omaha_event_lost() {
2351        block_on(async {
2352            // This is sufficient to trigger a lost Omaha event as oneshot triggers an
2353            // update check, which gets the invalid response (but hasn't checked the
2354            // validity yet). This invalid response still contains an OK status, resulting
2355            // in the UpdateCheckResponseTime and RequestsPerCheck events being generated
2356            // reporting success.
2357            //
2358            // The response is then parsed and found to be incorrect; this parse error is
2359            // attempted to be sent back to Omaha as an event with the ParseResponse error
2360            // associated. However, the MockHttpRequest has already consumed the one
2361            // response it knew how to give; this event is reported via HTTP, but is "lost"
2362            // because the mock responds with a 500 error when it has no responses left to
2363            // return.
2364            //
2365            // That finally results in the OmahaEventLost.
2366            let http = MockHttpRequest::new(HttpResponse::new("invalid response".into()));
2367            let mut metrics_reporter = MockMetricsReporter::new();
2368            let _response = StateMachineBuilder::new_stub()
2369                .http(http)
2370                .metrics_reporter(&mut metrics_reporter)
2371                .oneshot(RequestParams::default())
2372                .await;
2373
2374            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
2375            // patterns yet.
2376            #[rustfmt::skip]
2377            assert_matches!(
2378                metrics_reporter.metrics.as_slice(),
2379                [
2380                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
2381                    Metrics::RequestsPerCheck { count: 1, successful: true },
2382                    Metrics::OmahaEventLost(Event {
2383                        event_type: EventType::UpdateComplete,
2384                        event_result: EventResult::Error,
2385                        errorcode: Some(EventErrorCode::ParseResponse),
2386                        previous_version: None,
2387                        next_version: None,
2388                        download_time_ms: None,
2389                    })
2390                ]
2391            );
2392        });
2393    }
2394
2395    #[test]
2396    fn test_metrics_report_update_check_response_time() {
2397        block_on(async {
2398            let mut metrics_reporter = MockMetricsReporter::new();
2399            let _response = StateMachineBuilder::new_stub()
2400                .metrics_reporter(&mut metrics_reporter)
2401                .oneshot(RequestParams::default())
2402                .await;
2403
2404            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
2405            // patterns yet.
2406            #[rustfmt::skip]
2407            assert_matches!(
2408                metrics_reporter.metrics.as_slice(),
2409                [
2410                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
2411                    Metrics::RequestsPerCheck { count: 1, successful: true },
2412                ]
2413            );
2414        });
2415    }
2416
2417    #[test]
2418    fn test_metrics_report_update_check_response_time_on_failure() {
2419        block_on(async {
2420            let mut metrics_reporter = MockMetricsReporter::new();
2421            let mut http = MockHttpRequest::default();
2422
2423            for _ in 0..MAX_OMAHA_REQUEST_ATTEMPTS {
2424                http.add_error(http_request::mock_errors::make_transport_error());
2425            }
2426
2427            // Note: we exit the update loop before we fetch the successful result, so we never see
2428            // this result.
2429            http.add_response(hyper::Response::default());
2430
2431            let _response = StateMachineBuilder::new_stub()
2432                .http(http)
2433                .metrics_reporter(&mut metrics_reporter)
2434                .oneshot(RequestParams::default())
2435                .await;
2436
2437            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
2438            // patterns yet.
2439            #[rustfmt::skip]
2440            assert_matches!(
2441                metrics_reporter.metrics.as_slice(),
2442                [
2443                    Metrics::UpdateCheckResponseTime { response_time: _, successful: false },
2444                    Metrics::UpdateCheckResponseTime { response_time: _, successful: false },
2445                    Metrics::UpdateCheckResponseTime { response_time: _, successful: false },
2446                    Metrics::RequestsPerCheck { count: 3, successful: false },
2447                ]
2448            );
2449        });
2450    }
2451
2452    #[test]
2453    fn test_metrics_report_update_check_response_time_on_failure_followed_by_success() {
2454        block_on(async {
2455            let mut metrics_reporter = MockMetricsReporter::new();
2456            let mut http = MockHttpRequest::default();
2457
2458            for _ in 0..MAX_OMAHA_REQUEST_ATTEMPTS - 1 {
2459                http.add_error(http_request::mock_errors::make_transport_error());
2460            }
2461            http.add_response(hyper::Response::default());
2462
2463            let _response = StateMachineBuilder::new_stub()
2464                .http(http)
2465                .metrics_reporter(&mut metrics_reporter)
2466                .oneshot(RequestParams::default())
2467                .await;
2468
2469            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
2470            // patterns yet.
2471            #[rustfmt::skip]
2472            assert_matches!(
2473                metrics_reporter.metrics.as_slice(),
2474                [
2475                    Metrics::UpdateCheckResponseTime { response_time: _, successful: false },
2476                    Metrics::UpdateCheckResponseTime { response_time: _, successful: false },
2477                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
2478                    Metrics::RequestsPerCheck { count: 3, successful: true },
2479                    Metrics::OmahaEventLost(Event {
2480                        event_type: EventType::UpdateComplete,
2481                        event_result: EventResult::Error,
2482                        errorcode: Some(EventErrorCode::ParseResponse),
2483                        previous_version: None,
2484                        next_version: None,
2485                        download_time_ms: None
2486                    }),
2487                ]
2488            );
2489        });
2490    }
2491
2492    #[test]
2493    fn test_metrics_report_requests_per_check() {
2494        block_on(async {
2495            let mut metrics_reporter = MockMetricsReporter::new();
2496            let _response = StateMachineBuilder::new_stub()
2497                .metrics_reporter(&mut metrics_reporter)
2498                .oneshot(RequestParams::default())
2499                .await;
2500
2501            assert!(metrics_reporter
2502                .metrics
2503                .contains(&Metrics::RequestsPerCheck {
2504                    count: 1,
2505                    successful: true
2506                }));
2507        });
2508    }
2509
2510    #[test]
2511    fn test_metrics_report_requests_per_check_on_failure_followed_by_success() {
2512        block_on(async {
2513            let mut metrics_reporter = MockMetricsReporter::new();
2514            let mut http = MockHttpRequest::default();
2515
2516            for _ in 0..MAX_OMAHA_REQUEST_ATTEMPTS - 1 {
2517                http.add_error(http_request::mock_errors::make_transport_error());
2518            }
2519
2520            http.add_response(hyper::Response::default());
2521
2522            let _response = StateMachineBuilder::new_stub()
2523                .http(http)
2524                .metrics_reporter(&mut metrics_reporter)
2525                .oneshot(RequestParams::default())
2526                .await;
2527
2528            assert!(!metrics_reporter.metrics.is_empty());
2529            assert!(metrics_reporter
2530                .metrics
2531                .contains(&Metrics::RequestsPerCheck {
2532                    count: MAX_OMAHA_REQUEST_ATTEMPTS,
2533                    successful: true
2534                }));
2535        });
2536    }
2537
2538    #[test]
2539    fn test_metrics_report_requests_per_check_on_failure() {
2540        block_on(async {
2541            let mut metrics_reporter = MockMetricsReporter::new();
2542            let mut http = MockHttpRequest::default();
2543
2544            for _ in 0..MAX_OMAHA_REQUEST_ATTEMPTS {
2545                http.add_error(http_request::mock_errors::make_transport_error());
2546            }
2547
2548            // Note we will give up before we get this successful request.
2549            http.add_response(hyper::Response::default());
2550
2551            let _response = StateMachineBuilder::new_stub()
2552                .http(http)
2553                .metrics_reporter(&mut metrics_reporter)
2554                .oneshot(RequestParams::default())
2555                .await;
2556
2557            assert!(!metrics_reporter.metrics.is_empty());
2558            assert!(metrics_reporter
2559                .metrics
2560                .contains(&Metrics::RequestsPerCheck {
2561                    count: MAX_OMAHA_REQUEST_ATTEMPTS,
2562                    successful: false
2563                }));
2564        });
2565    }
2566
2567    #[test]
2568    fn test_requests_per_check_backoff_with_mock_timer() {
2569        block_on(async {
2570            let mut timer = MockTimer::new();
2571            timer.expect_for_range(Duration::from_millis(500), Duration::from_millis(1500));
2572            timer.expect_for_range(Duration::from_millis(1500), Duration::from_millis(2500));
2573            let requested_waits = timer.get_requested_waits_view();
2574            let response = StateMachineBuilder::new_stub()
2575                .http(MockHttpRequest::empty())
2576                .timer(timer)
2577                .oneshot(RequestParams::default())
2578                .await;
2579
2580            let waits = requested_waits.borrow();
2581            assert_eq!(waits.len(), 2);
2582            assert_matches!(
2583                waits[0],
2584                RequestedWait::For(d) if d >= Duration::from_millis(500) && d <= Duration::from_millis(1500)
2585            );
2586            assert_matches!(
2587                waits[1],
2588                RequestedWait::For(d) if d >= Duration::from_millis(1500) && d <= Duration::from_millis(2500)
2589            );
2590
2591            assert_matches!(
2592                response,
2593                Err(UpdateCheckError::OmahaRequest(
2594                    OmahaRequestError::HttpStatus(_)
2595                ))
2596            );
2597        });
2598    }
2599
2600    #[test]
2601    fn test_metrics_report_update_check_failure_reason_omaha() {
2602        block_on(async {
2603            let mut metrics_reporter = MockMetricsReporter::new();
2604            let mut state_machine = StateMachineBuilder::new_stub()
2605                .metrics_reporter(&mut metrics_reporter)
2606                .build()
2607                .await;
2608
2609            state_machine.run_once().await;
2610
2611            assert!(metrics_reporter
2612                .metrics
2613                .contains(&Metrics::UpdateCheckFailureReason(
2614                    UpdateCheckFailureReason::Omaha
2615                )));
2616        });
2617    }
2618
2619    #[test]
2620    fn test_metrics_report_update_check_failure_reason_network() {
2621        block_on(async {
2622            let mut metrics_reporter = MockMetricsReporter::new();
2623            let mut state_machine = StateMachineBuilder::new_stub()
2624                .http(MockHttpRequest::empty())
2625                .metrics_reporter(&mut metrics_reporter)
2626                .build()
2627                .await;
2628
2629            state_machine.run_once().await;
2630
2631            assert!(metrics_reporter
2632                .metrics
2633                .contains(&Metrics::UpdateCheckFailureReason(
2634                    UpdateCheckFailureReason::Network
2635                )));
2636        });
2637    }
2638
2639    #[test]
2640    fn test_persist_last_update_time() {
2641        block_on(async {
2642            let storage = Rc::new(Mutex::new(MemStorage::new()));
2643
2644            StateMachineBuilder::new_stub()
2645                .storage(Rc::clone(&storage))
2646                .oneshot_check()
2647                .await
2648                .map(|_| ())
2649                .collect::<()>()
2650                .await;
2651
2652            let storage = storage.lock().await;
2653            storage.get_int(LAST_UPDATE_TIME).await.unwrap();
2654            assert!(storage.committed());
2655        });
2656    }
2657
2658    #[test]
2659    fn test_persist_server_dictated_poll_interval() {
2660        block_on(async {
2661            let response = HttpResponse::builder()
2662                .header(X_RETRY_AFTER, 1234)
2663                .body(make_noupdate_httpresponse())
2664                .unwrap();
2665            let http = MockHttpRequest::new(response);
2666            let storage = Rc::new(Mutex::new(MemStorage::new()));
2667
2668            let mut state_machine = StateMachineBuilder::new_stub()
2669                .http(http)
2670                .storage(Rc::clone(&storage))
2671                .build()
2672                .await;
2673            state_machine
2674                .oneshot(RequestParams::default())
2675                .await
2676                .unwrap();
2677
2678            assert_eq!(
2679                state_machine.context.state.server_dictated_poll_interval,
2680                Some(Duration::from_secs(1234))
2681            );
2682
2683            let storage = storage.lock().await;
2684            assert_eq!(
2685                storage.get_int(SERVER_DICTATED_POLL_INTERVAL).await,
2686                Some(1234000000)
2687            );
2688            assert!(storage.committed());
2689        });
2690    }
2691
2692    #[test]
2693    fn test_persist_server_dictated_poll_interval_http_error() {
2694        block_on(async {
2695            let response = HttpResponse::builder()
2696                .status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
2697                .header(X_RETRY_AFTER, 1234)
2698                .body(vec![])
2699                .unwrap();
2700            let http = MockHttpRequest::new(response);
2701            let storage = Rc::new(Mutex::new(MemStorage::new()));
2702
2703            let mut state_machine = StateMachineBuilder::new_stub()
2704                .http(http)
2705                .storage(Rc::clone(&storage))
2706                .build()
2707                .await;
2708            assert_matches!(
2709                state_machine.oneshot(RequestParams::default()).await,
2710                Err(UpdateCheckError::OmahaRequest(
2711                    OmahaRequestError::HttpStatus(_)
2712                ))
2713            );
2714
2715            assert_eq!(
2716                state_machine.context.state.server_dictated_poll_interval,
2717                Some(Duration::from_secs(1234))
2718            );
2719
2720            let storage = storage.lock().await;
2721            assert_eq!(
2722                storage.get_int(SERVER_DICTATED_POLL_INTERVAL).await,
2723                Some(1234000000)
2724            );
2725            assert!(storage.committed());
2726        });
2727    }
2728
2729    #[test]
2730    fn test_persist_server_dictated_poll_interval_max_duration() {
2731        block_on(async {
2732            let response = HttpResponse::builder()
2733                .status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
2734                .header(X_RETRY_AFTER, 123456789)
2735                .body(vec![])
2736                .unwrap();
2737            let http = MockHttpRequest::new(response);
2738            let storage = Rc::new(Mutex::new(MemStorage::new()));
2739
2740            let mut state_machine = StateMachineBuilder::new_stub()
2741                .http(http)
2742                .storage(Rc::clone(&storage))
2743                .build()
2744                .await;
2745            assert_matches!(
2746                state_machine.oneshot(RequestParams::default()).await,
2747                Err(UpdateCheckError::OmahaRequest(
2748                    OmahaRequestError::HttpStatus(_)
2749                ))
2750            );
2751
2752            assert_eq!(
2753                state_machine.context.state.server_dictated_poll_interval,
2754                Some(Duration::from_secs(86400))
2755            );
2756
2757            let storage = storage.lock().await;
2758            assert_eq!(
2759                storage.get_int(SERVER_DICTATED_POLL_INTERVAL).await,
2760                Some(86400000000)
2761            );
2762            assert!(storage.committed());
2763        });
2764    }
2765
2766    #[test]
2767    fn test_server_dictated_poll_interval_with_transport_error_no_retry() {
2768        block_on(async {
2769            let mut http = MockHttpRequest::empty();
2770            http.add_error(http_request::mock_errors::make_transport_error());
2771            let mut storage = MemStorage::new();
2772            let _ = storage.set_int(SERVER_DICTATED_POLL_INTERVAL, 1234000000);
2773            let _ = storage.commit();
2774            let storage = Rc::new(Mutex::new(storage));
2775
2776            let mut state_machine = StateMachineBuilder::new_stub()
2777                .http(http)
2778                .storage(Rc::clone(&storage))
2779                .build()
2780                .await;
2781            // This verifies that state machine does not retry because MockHttpRequest will only
2782            // return the transport error on the first request, any additional requests will get
2783            // HttpStatus error.
2784            assert_matches!(
2785                state_machine.oneshot(RequestParams::default()).await,
2786                Err(UpdateCheckError::OmahaRequest(
2787                    OmahaRequestError::HttpTransport(_)
2788                ))
2789            );
2790
2791            assert_eq!(
2792                state_machine.context.state.server_dictated_poll_interval,
2793                Some(Duration::from_secs(1234))
2794            );
2795        });
2796    }
2797
2798    #[test]
2799    fn test_persist_app() {
2800        block_on(async {
2801            let storage = Rc::new(Mutex::new(MemStorage::new()));
2802            let app_set = make_test_app_set();
2803
2804            StateMachineBuilder::new_stub()
2805                .storage(Rc::clone(&storage))
2806                .app_set(app_set.clone())
2807                .oneshot_check()
2808                .await
2809                .map(|_| ())
2810                .collect::<()>()
2811                .await;
2812
2813            let storage = storage.lock().await;
2814            let apps = app_set.lock().await.get_apps();
2815            storage.get_string(&apps[0].id).await.unwrap();
2816            assert!(storage.committed());
2817        });
2818    }
2819
2820    #[test]
2821    fn test_load_last_update_time() {
2822        block_on(async {
2823            let mut storage = MemStorage::new();
2824            let mut mock_time = MockTimeSource::new_from_now();
2825            mock_time.truncate_submicrosecond_walltime();
2826            let last_update_time = mock_time.now_in_walltime() - Duration::from_secs(999);
2827            storage
2828                .set_time(LAST_UPDATE_TIME, last_update_time)
2829                .await
2830                .unwrap();
2831
2832            let state_machine = StateMachineBuilder::new_stub()
2833                .policy_engine(StubPolicyEngine::new(&mock_time))
2834                .storage(Rc::new(Mutex::new(storage)))
2835                .build()
2836                .await;
2837
2838            assert_eq!(
2839                state_machine.context.schedule.last_update_time.unwrap(),
2840                PartialComplexTime::Wall(last_update_time)
2841            );
2842        });
2843    }
2844
2845    #[test]
2846    fn test_load_server_dictated_poll_interval() {
2847        block_on(async {
2848            let mut storage = MemStorage::new();
2849            storage
2850                .set_int(SERVER_DICTATED_POLL_INTERVAL, 56789)
2851                .await
2852                .unwrap();
2853
2854            let state_machine = StateMachineBuilder::new_stub()
2855                .storage(Rc::new(Mutex::new(storage)))
2856                .build()
2857                .await;
2858
2859            assert_eq!(
2860                Some(Duration::from_micros(56789)),
2861                state_machine.context.state.server_dictated_poll_interval
2862            );
2863        });
2864    }
2865
2866    #[test]
2867    fn test_load_app() {
2868        block_on(async {
2869            let app_set = VecAppSet::new(vec![App::builder()
2870                .id("{00000000-0000-0000-0000-000000000001}")
2871                .version([1, 2, 3, 4])
2872                .build()]);
2873            let mut storage = MemStorage::new();
2874            let persisted_app = PersistedApp {
2875                cohort: Cohort {
2876                    id: Some("cohort_id".to_string()),
2877                    hint: Some("test_channel".to_string()),
2878                    name: None,
2879                },
2880                user_counting: UserCounting::ClientRegulatedByDate(Some(22222)),
2881            };
2882            let json = serde_json::to_string(&persisted_app).unwrap();
2883            let apps = app_set.get_apps();
2884            storage.set_string(&apps[0].id, &json).await.unwrap();
2885
2886            let app_set = Rc::new(Mutex::new(app_set));
2887
2888            let _state_machine = StateMachineBuilder::new_stub()
2889                .storage(Rc::new(Mutex::new(storage)))
2890                .app_set(Rc::clone(&app_set))
2891                .build()
2892                .await;
2893
2894            let apps = app_set.lock().await.get_apps();
2895            assert_eq!(persisted_app.cohort, apps[0].cohort);
2896            assert_eq!(
2897                UserCounting::ClientRegulatedByDate(Some(22222)),
2898                apps[0].user_counting
2899            );
2900        });
2901    }
2902
2903    #[test]
2904    fn test_report_check_interval_with_no_storage() {
2905        block_on(async {
2906            let mut mock_time = MockTimeSource::new_from_now();
2907            let mut state_machine = StateMachineBuilder::new_stub()
2908                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
2909                .metrics_reporter(MockMetricsReporter::new())
2910                .build()
2911                .await;
2912
2913            state_machine
2914                .report_check_interval(InstallSource::ScheduledTask)
2915                .await;
2916            // No metrics should be reported because no LAST_UPDATE_TIME in storage.
2917            assert!(state_machine.metrics_reporter.metrics.is_empty());
2918
2919            // A second update check should report metrics.
2920            let interval = Duration::from_micros(999999);
2921            mock_time.advance(interval);
2922
2923            state_machine
2924                .report_check_interval(InstallSource::ScheduledTask)
2925                .await;
2926
2927            assert_eq!(
2928                state_machine.metrics_reporter.metrics,
2929                vec![Metrics::UpdateCheckInterval {
2930                    interval,
2931                    clock: ClockType::Monotonic,
2932                    install_source: InstallSource::ScheduledTask,
2933                }]
2934            );
2935        });
2936    }
2937
2938    #[test]
2939    fn test_report_check_interval_mono_transition() {
2940        block_on(async {
2941            let mut mock_time = MockTimeSource::new_from_now();
2942            let mut state_machine = StateMachineBuilder::new_stub()
2943                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
2944                .metrics_reporter(MockMetricsReporter::new())
2945                .build()
2946                .await;
2947
2948            // Make sure that, provided a wall time, we get an initial report
2949            // using the wall time.
2950            let initial_duration = Duration::from_secs(999);
2951            let initial_time = mock_time.now_in_walltime() - initial_duration;
2952            state_machine.context.schedule.last_update_check_time =
2953                Some(PartialComplexTime::Wall(initial_time));
2954            state_machine
2955                .report_check_interval(InstallSource::ScheduledTask)
2956                .await;
2957
2958            // Advance one more time, and this time we should see a monotonic delta.
2959            let interval = Duration::from_micros(999999);
2960            mock_time.advance(interval);
2961            state_machine
2962                .report_check_interval(InstallSource::ScheduledTask)
2963                .await;
2964
2965            // One final time, to demonstrate monotonic time edges to
2966            // monotonic time.
2967            mock_time.advance(interval);
2968            state_machine
2969                .report_check_interval(InstallSource::ScheduledTask)
2970                .await;
2971            assert_eq!(
2972                state_machine.metrics_reporter.metrics,
2973                vec![
2974                    Metrics::UpdateCheckInterval {
2975                        interval: initial_duration,
2976                        clock: ClockType::Wall,
2977                        install_source: InstallSource::ScheduledTask,
2978                    },
2979                    Metrics::UpdateCheckInterval {
2980                        interval,
2981                        clock: ClockType::Monotonic,
2982                        install_source: InstallSource::ScheduledTask,
2983                    },
2984                    Metrics::UpdateCheckInterval {
2985                        interval,
2986                        clock: ClockType::Monotonic,
2987                        install_source: InstallSource::ScheduledTask,
2988                    },
2989                ]
2990            );
2991        });
2992    }
2993
2994    #[derive(Debug)]
2995    pub struct TestInstaller {
2996        reboot_called: Rc<RefCell<bool>>,
2997        install_fails: usize,
2998        mock_time: MockTimeSource,
2999    }
3000    struct TestInstallerBuilder {
3001        install_fails: usize,
3002        mock_time: MockTimeSource,
3003    }
3004    impl TestInstaller {
3005        fn builder(mock_time: MockTimeSource) -> TestInstallerBuilder {
3006            TestInstallerBuilder {
3007                install_fails: 0,
3008                mock_time,
3009            }
3010        }
3011    }
3012    impl TestInstallerBuilder {
3013        fn add_install_fail(mut self) -> Self {
3014            self.install_fails += 1;
3015            self
3016        }
3017        fn build(self) -> TestInstaller {
3018            TestInstaller {
3019                reboot_called: Rc::new(RefCell::new(false)),
3020                install_fails: self.install_fails,
3021                mock_time: self.mock_time,
3022            }
3023        }
3024    }
3025    const INSTALL_DURATION: Duration = Duration::from_micros(98765433);
3026
3027    impl Installer for TestInstaller {
3028        type InstallPlan = StubPlan;
3029        type Error = StubInstallErrors;
3030        type InstallResult = ();
3031
3032        fn perform_install<'a>(
3033            &'a mut self,
3034            _install_plan: &StubPlan,
3035            observer: Option<&'a dyn ProgressObserver>,
3036        ) -> LocalBoxFuture<'a, (Self::InstallResult, Vec<AppInstallResult<Self::Error>>)> {
3037            if self.install_fails > 0 {
3038                self.install_fails -= 1;
3039                future::ready((
3040                    (),
3041                    vec![AppInstallResult::Failed(StubInstallErrors::Failed)],
3042                ))
3043                .boxed()
3044            } else {
3045                self.mock_time.advance(INSTALL_DURATION);
3046                async move {
3047                    if let Some(observer) = observer {
3048                        observer.receive_progress(None, 0.0, None, None).await;
3049                        observer.receive_progress(None, 0.3, None, None).await;
3050                        observer.receive_progress(None, 0.9, None, None).await;
3051                        observer.receive_progress(None, 1.0, None, None).await;
3052                    }
3053                    ((), vec![AppInstallResult::Installed])
3054                }
3055                .boxed_local()
3056            }
3057        }
3058
3059        fn perform_reboot(&mut self) -> LocalBoxFuture<'_, Result<(), anyhow::Error>> {
3060            self.reboot_called.replace(true);
3061            future::ready(Ok(())).boxed_local()
3062        }
3063
3064        fn try_create_install_plan<'a>(
3065            &'a self,
3066            _request_params: &'a RequestParams,
3067            _request_metadata: Option<&'a RequestMetadata>,
3068            _response: &'a Response,
3069            _response_bytes: Vec<u8>,
3070            _ecdsa_signature: Option<Vec<u8>>,
3071        ) -> LocalBoxFuture<'a, Result<Self::InstallPlan, Self::Error>> {
3072            future::ready(Ok(StubPlan)).boxed_local()
3073        }
3074    }
3075
3076    #[test]
3077    fn test_report_successful_update_duration() {
3078        block_on(async {
3079            let http = MockHttpRequest::new(make_update_available_response());
3080            let storage = Rc::new(Mutex::new(MemStorage::new()));
3081
3082            let mut mock_time = MockTimeSource::new_from_now();
3083            mock_time.truncate_submicrosecond_walltime();
3084            let now = mock_time.now();
3085
3086            let update_completed_time = now + INSTALL_DURATION;
3087            let expected_update_duration = update_completed_time.wall_duration_since(now).unwrap();
3088
3089            let first_seen_time = now - Duration::from_micros(1000);
3090
3091            let expected_duration_since_first_seen = update_completed_time
3092                .wall_duration_since(first_seen_time)
3093                .unwrap();
3094
3095            let mut state_machine = StateMachineBuilder::new_stub()
3096                .http(http)
3097                .installer(TestInstaller::builder(mock_time.clone()).build())
3098                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
3099                .metrics_reporter(MockMetricsReporter::new())
3100                .storage(Rc::clone(&storage))
3101                .build()
3102                .await;
3103
3104            {
3105                let mut storage = storage.lock().await;
3106                storage.set_string(INSTALL_PLAN_ID, "").await.unwrap();
3107                storage
3108                    .set_time(UPDATE_FIRST_SEEN_TIME, first_seen_time)
3109                    .await
3110                    .unwrap();
3111                storage.commit().await.unwrap();
3112            }
3113
3114            state_machine.run_once().await;
3115
3116            #[rustfmt::skip]
3117            assert_matches!(
3118                state_machine.metrics_reporter.metrics.as_slice(),
3119                [
3120                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
3121                    Metrics::RequestsPerCheck { count: 1, successful: true },
3122                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateDownloadStarted, event_result: EventResult::Success, .. }),
3123                    Metrics::SuccessfulUpdateDuration(install_duration),
3124                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateDownloadFinished, event_result: EventResult::Success, .. }),
3125                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateComplete, event_result: EventResult::Success, .. }),
3126                    Metrics::SuccessfulUpdateFromFirstSeen(duration_since_first_seen),
3127                    Metrics::AttemptsToSuccessfulCheck(1),
3128                    Metrics::AttemptsToSuccessfulInstall { count: 1, successful: true },
3129                ]
3130                if
3131                    *install_duration == expected_update_duration &&
3132                    *duration_since_first_seen == expected_duration_since_first_seen
3133            );
3134        });
3135    }
3136
3137    #[test]
3138    fn test_report_failed_update_duration() {
3139        block_on(async {
3140            let http = MockHttpRequest::new(make_update_available_response());
3141            let mut state_machine = StateMachineBuilder::new_stub()
3142                .http(http)
3143                .installer(StubInstaller { should_fail: true })
3144                .metrics_reporter(MockMetricsReporter::new())
3145                .build()
3146                .await;
3147            // clock::mock::set(time::i64_to_time(123456789));
3148
3149            state_machine.run_once().await;
3150
3151            assert!(state_machine
3152                .metrics_reporter
3153                .metrics
3154                .contains(&Metrics::FailedUpdateDuration(Duration::from_micros(0))));
3155        });
3156    }
3157
3158    #[test]
3159    fn test_record_update_first_seen_time() {
3160        block_on(async {
3161            let storage = Rc::new(Mutex::new(MemStorage::new()));
3162            let mut state_machine = StateMachineBuilder::new_stub()
3163                .storage(Rc::clone(&storage))
3164                .build()
3165                .await;
3166
3167            let mut mock_time = MockTimeSource::new_from_now();
3168            mock_time.truncate_submicrosecond_walltime();
3169            let now = mock_time.now_in_walltime();
3170            assert_eq!(
3171                state_machine.record_update_first_seen_time("id", now).await,
3172                now
3173            );
3174            {
3175                let storage = storage.lock().await;
3176                assert_eq!(
3177                    storage.get_string(INSTALL_PLAN_ID).await,
3178                    Some("id".to_string())
3179                );
3180                assert_eq!(storage.get_time(UPDATE_FIRST_SEEN_TIME).await, Some(now));
3181                assert_eq!(storage.len(), 2);
3182                assert!(storage.committed());
3183            }
3184
3185            mock_time.advance(Duration::from_secs(1000));
3186            let now2 = mock_time.now_in_walltime();
3187            assert_eq!(
3188                state_machine
3189                    .record_update_first_seen_time("id", now2)
3190                    .await,
3191                now
3192            );
3193            {
3194                let storage = storage.lock().await;
3195                assert_eq!(
3196                    storage.get_string(INSTALL_PLAN_ID).await,
3197                    Some("id".to_string())
3198                );
3199                assert_eq!(storage.get_time(UPDATE_FIRST_SEEN_TIME).await, Some(now));
3200                assert_eq!(storage.len(), 2);
3201                assert!(storage.committed());
3202            }
3203            assert_eq!(
3204                state_machine
3205                    .record_update_first_seen_time("id2", now2)
3206                    .await,
3207                now2
3208            );
3209            {
3210                let storage = storage.lock().await;
3211                assert_eq!(
3212                    storage.get_string(INSTALL_PLAN_ID).await,
3213                    Some("id2".to_string())
3214                );
3215                assert_eq!(storage.get_time(UPDATE_FIRST_SEEN_TIME).await, Some(now2));
3216                assert_eq!(storage.len(), 2);
3217                assert!(storage.committed());
3218            }
3219        });
3220    }
3221
3222    #[test]
3223    fn test_report_attempts_to_successful_check() {
3224        block_on(async {
3225            let storage = Rc::new(Mutex::new(MemStorage::new()));
3226            let mut state_machine = StateMachineBuilder::new_stub()
3227                .installer(StubInstaller { should_fail: true })
3228                .metrics_reporter(MockMetricsReporter::new())
3229                .storage(Rc::clone(&storage))
3230                .build()
3231                .await;
3232
3233            state_machine
3234                .report_attempts_to_successful_check(true)
3235                .await;
3236
3237            // consecutive_failed_update_attempts should be zero (there were no previous failures)
3238            // but we should record an attempt in metrics
3239            assert_eq!(
3240                state_machine.context.state.consecutive_failed_update_checks,
3241                0
3242            );
3243            assert_eq!(
3244                state_machine.metrics_reporter.metrics,
3245                vec![Metrics::AttemptsToSuccessfulCheck(1)]
3246            );
3247
3248            state_machine
3249                .report_attempts_to_successful_check(false)
3250                .await;
3251            assert_eq!(
3252                state_machine.context.state.consecutive_failed_update_checks,
3253                1
3254            );
3255
3256            state_machine
3257                .report_attempts_to_successful_check(false)
3258                .await;
3259            assert_eq!(
3260                state_machine.context.state.consecutive_failed_update_checks,
3261                2
3262            );
3263
3264            // consecutive_failed_update_attempts should be reset to zero on success
3265            // but we should record the previous number of failed attempts (2) + 1 in metrics
3266            state_machine
3267                .report_attempts_to_successful_check(true)
3268                .await;
3269            assert_eq!(
3270                state_machine.context.state.consecutive_failed_update_checks,
3271                0
3272            );
3273            assert_eq!(
3274                state_machine.metrics_reporter.metrics,
3275                vec![
3276                    Metrics::AttemptsToSuccessfulCheck(1),
3277                    Metrics::AttemptsToSuccessfulCheck(3)
3278                ]
3279            );
3280        });
3281    }
3282
3283    #[test]
3284    fn test_ping_omaha_updates_consecutive_failed_update_checks_and_persists() {
3285        block_on(async {
3286            let mut http = MockHttpRequest::empty();
3287            http.add_error(http_request::mock_errors::make_transport_error());
3288            http.add_response(HttpResponse::new(vec![]));
3289            let response = json!({"response":{
3290              "server": "prod",
3291              "protocol": "3.0",
3292              "app": [{
3293                "appid": "{00000000-0000-0000-0000-000000000001}",
3294                "status": "ok",
3295              }],
3296            }});
3297            let response = serde_json::to_vec(&response).unwrap();
3298            http.add_response(HttpResponse::new(response));
3299
3300            let storage = Rc::new(Mutex::new(MemStorage::new()));
3301
3302            // Start out with a value in storage...
3303            {
3304                let mut storage = storage.lock().await;
3305                let _ = storage.set_int(CONSECUTIVE_FAILED_UPDATE_CHECKS, 1);
3306                let _ = storage.commit();
3307            }
3308
3309            let mut state_machine = StateMachineBuilder::new_stub()
3310                .storage(Rc::clone(&storage))
3311                .http(http)
3312                .build()
3313                .await;
3314
3315            async_generator::generate(move |mut co| async move {
3316                // Failed ping increases `consecutive_failed_update_checks`, adding the value from
3317                // storage.
3318                state_machine.ping_omaha(&mut co).await;
3319                assert_eq!(
3320                    state_machine.context.state.consecutive_failed_update_checks,
3321                    2
3322                );
3323                {
3324                    let storage = storage.lock().await;
3325                    assert_eq!(
3326                        storage.get_int(CONSECUTIVE_FAILED_UPDATE_CHECKS).await,
3327                        Some(2)
3328                    );
3329                }
3330
3331                state_machine.ping_omaha(&mut co).await;
3332                assert_eq!(
3333                    state_machine.context.state.consecutive_failed_update_checks,
3334                    3
3335                );
3336                {
3337                    let storage = storage.lock().await;
3338                    assert_eq!(
3339                        storage.get_int(CONSECUTIVE_FAILED_UPDATE_CHECKS).await,
3340                        Some(3)
3341                    );
3342                }
3343
3344                // Successful ping resets `consecutive_failed_update_checks`.
3345                state_machine.ping_omaha(&mut co).await;
3346                assert_eq!(
3347                    state_machine.context.state.consecutive_failed_update_checks,
3348                    0
3349                );
3350                {
3351                    let storage = storage.lock().await;
3352                    assert_eq!(
3353                        storage.get_int(CONSECUTIVE_FAILED_UPDATE_CHECKS).await,
3354                        None
3355                    );
3356                }
3357            })
3358            .into_complete()
3359            .await;
3360        });
3361    }
3362
3363    #[test]
3364    fn test_report_attempts_to_successful_install() {
3365        block_on(async {
3366            let http = MockHttpRequest::new(make_update_available_response());
3367            let storage = Rc::new(Mutex::new(MemStorage::new()));
3368
3369            let mock_time = MockTimeSource::new_from_now();
3370
3371            let mut state_machine = StateMachineBuilder::new_stub()
3372                .http(http)
3373                .installer(TestInstaller::builder(mock_time.clone()).build())
3374                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
3375                .metrics_reporter(MockMetricsReporter::new())
3376                .storage(Rc::clone(&storage))
3377                .build()
3378                .await;
3379
3380            state_machine.run_once().await;
3381
3382            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
3383            // patterns yet.
3384            #[rustfmt::skip]
3385            assert_matches!(
3386                state_machine.metrics_reporter.metrics.as_slice(),
3387                [
3388                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
3389                    Metrics::RequestsPerCheck { count: 1, successful: true },
3390                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateDownloadStarted, event_result: EventResult::Success, .. }),
3391                    Metrics::SuccessfulUpdateDuration(_),
3392                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateDownloadFinished, event_result: EventResult::Success, .. }),
3393                    Metrics::OmahaEventLost(Event { event_type: EventType::UpdateComplete, event_result: EventResult::Success, .. }),
3394                    Metrics::SuccessfulUpdateFromFirstSeen(_),
3395                    Metrics::AttemptsToSuccessfulCheck(1),
3396                    Metrics::AttemptsToSuccessfulInstall { count: 1, successful: true },
3397                ]
3398            );
3399        });
3400    }
3401
3402    #[test]
3403    fn test_report_attempts_to_successful_install_fails_then_succeeds() {
3404        block_on(async {
3405            let mut http = MockHttpRequest::new(make_update_available_response());
3406            // Responses to events. This first batch corresponds to the install failure, so these
3407            // should be the update download started, and another for a failed install.
3408            // `Event::error(EventErrorCode::Installation)`.
3409            http.add_response(HttpResponse::new(vec![]));
3410            http.add_response(HttpResponse::new(vec![]));
3411
3412            // Respond to the next request.
3413            http.add_response(make_update_available_response());
3414            // Responses to events. This corresponds to the update download started, and the other
3415            // for a successful install.
3416            http.add_response(HttpResponse::new(vec![]));
3417            http.add_response(HttpResponse::new(vec![]));
3418
3419            let storage = Rc::new(Mutex::new(MemStorage::new()));
3420            let mock_time = MockTimeSource::new_from_now();
3421
3422            let mut state_machine = StateMachineBuilder::new_stub()
3423                .http(http)
3424                .installer(
3425                    TestInstaller::builder(mock_time.clone())
3426                        .add_install_fail()
3427                        .build(),
3428                )
3429                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
3430                .metrics_reporter(MockMetricsReporter::new())
3431                .storage(Rc::clone(&storage))
3432                .build()
3433                .await;
3434
3435            state_machine.run_once().await;
3436            state_machine.run_once().await;
3437
3438            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
3439            // patterns yet.
3440            #[rustfmt::skip]
3441            assert_matches!(
3442                state_machine.metrics_reporter.metrics.as_slice(),
3443                [
3444                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
3445                    Metrics::RequestsPerCheck { count: 1, successful: true },
3446                    Metrics::FailedUpdateDuration(_),
3447                    Metrics::AttemptsToSuccessfulCheck(1),
3448                    Metrics::AttemptsToSuccessfulInstall { count: 1, successful: false },
3449                    Metrics::UpdateCheckInterval { .. },
3450                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
3451                    Metrics::RequestsPerCheck { count: 1, successful: true },
3452                    Metrics::SuccessfulUpdateDuration(_),
3453                    Metrics::OmahaEventLost(Event { .. }),
3454                    Metrics::SuccessfulUpdateFromFirstSeen(_),
3455                    Metrics::AttemptsToSuccessfulCheck(1),
3456                    Metrics::AttemptsToSuccessfulInstall { count: 2, successful: true }
3457                ]
3458            );
3459        });
3460    }
3461
3462    #[test]
3463    fn test_report_attempts_to_successful_install_does_not_report_for_no_update() {
3464        block_on(async {
3465            let response = json!({"response":{
3466              "server": "prod",
3467              "protocol": "3.0",
3468              "app": [{
3469                "appid": "{00000000-0000-0000-0000-000000000001}",
3470                "status": "ok",
3471                "updatecheck": {
3472                  "status": "noupdate",
3473                  "info": "no update for you"
3474                }
3475              }],
3476            }});
3477            let response = serde_json::to_vec(&response).unwrap();
3478            let http = MockHttpRequest::new(HttpResponse::new(response.clone()));
3479
3480            let storage = Rc::new(Mutex::new(MemStorage::new()));
3481            let mock_time = MockTimeSource::new_from_now();
3482
3483            let mut state_machine = StateMachineBuilder::new_stub()
3484                .http(http)
3485                .installer(TestInstaller::builder(mock_time.clone()).build())
3486                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
3487                .metrics_reporter(MockMetricsReporter::new())
3488                .storage(Rc::clone(&storage))
3489                .build()
3490                .await;
3491
3492            state_machine.run_once().await;
3493
3494            // FIXME(https://github.com/rust-lang/rustfmt/issues/4530) rustfmt doesn't wrap slice
3495            // patterns yet.
3496            #[rustfmt::skip]
3497            assert_matches!(
3498                state_machine.metrics_reporter.metrics.as_slice(),
3499                [
3500                    Metrics::UpdateCheckResponseTime { response_time: _, successful: true },
3501                    Metrics::RequestsPerCheck { count: 1, successful: true },
3502                    Metrics::AttemptsToSuccessfulCheck(1),
3503                ]
3504            );
3505        });
3506    }
3507
3508    #[test]
3509    fn test_successful_update_triggers_reboot() {
3510        let mut pool = LocalPool::new();
3511        let spawner = pool.spawner();
3512
3513        let http = MockHttpRequest::new(make_update_available_response());
3514        let mock_time = MockTimeSource::new_from_now();
3515        let next_update_time = mock_time.now();
3516        let (timer, mut timers) = BlockingTimer::new();
3517
3518        let installer = TestInstaller::builder(mock_time.clone()).build();
3519        let reboot_called = Rc::clone(&installer.reboot_called);
3520        let (_ctl, state_machine) = pool.run_until(
3521            StateMachineBuilder::new_stub()
3522                .http(http)
3523                .installer(installer)
3524                .policy_engine(StubPolicyEngine::new(mock_time))
3525                .timer(timer)
3526                .start(),
3527        );
3528        let observer = TestObserver::default();
3529        spawner
3530            .spawn_local(observer.observe(state_machine))
3531            .unwrap();
3532
3533        let blocked_timer = pool.run_until(timers.next()).unwrap();
3534        assert_eq!(
3535            blocked_timer.requested_wait(),
3536            RequestedWait::Until(next_update_time.into())
3537        );
3538        blocked_timer.unblock();
3539        pool.run_until_stalled();
3540
3541        assert!(*reboot_called.borrow());
3542    }
3543
3544    #[test]
3545    fn test_skip_reboot_if_not_needed() {
3546        let mut pool = LocalPool::new();
3547        let spawner = pool.spawner();
3548
3549        let http = MockHttpRequest::new(make_update_available_response());
3550        let mock_time = MockTimeSource::new_from_now();
3551        let next_update_time = mock_time.now();
3552        let reboot_check_options_received = Rc::new(RefCell::new(vec![]));
3553        let policy_engine = MockPolicyEngine {
3554            reboot_check_options_received: Rc::clone(&reboot_check_options_received),
3555            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
3556            time_source: mock_time.clone(),
3557            reboot_needed: Rc::new(RefCell::new(false)),
3558            ..MockPolicyEngine::default()
3559        };
3560        let (timer, mut timers) = BlockingTimer::new();
3561
3562        let installer = TestInstaller::builder(mock_time).build();
3563        let reboot_called = Rc::clone(&installer.reboot_called);
3564        let (_ctl, state_machine) = pool.run_until(
3565            StateMachineBuilder::new_stub()
3566                .http(http)
3567                .installer(installer)
3568                .policy_engine(policy_engine)
3569                .timer(timer)
3570                .start(),
3571        );
3572        let observer = TestObserver::default();
3573        spawner
3574            .spawn_local(observer.observe(state_machine))
3575            .unwrap();
3576
3577        let blocked_timer = pool.run_until(timers.next()).unwrap();
3578        assert_eq!(
3579            blocked_timer.requested_wait(),
3580            RequestedWait::Until(next_update_time.into())
3581        );
3582        blocked_timer.unblock();
3583        pool.run_until_stalled();
3584
3585        assert_eq!(
3586            observer.take_states(),
3587            vec![
3588                State::CheckingForUpdates(InstallSource::ScheduledTask),
3589                State::InstallingUpdate,
3590                State::Idle
3591            ]
3592        );
3593
3594        assert_eq!(*reboot_check_options_received.borrow(), vec![]);
3595        assert!(!*reboot_called.borrow());
3596    }
3597
3598    #[test]
3599    fn test_failed_update_does_not_trigger_reboot() {
3600        let mut pool = LocalPool::new();
3601        let spawner = pool.spawner();
3602
3603        let http = MockHttpRequest::new(make_update_available_response());
3604        let mock_time = MockTimeSource::new_from_now();
3605        let next_update_time = mock_time.now();
3606        let (timer, mut timers) = BlockingTimer::new();
3607
3608        let installer = TestInstaller::builder(mock_time.clone())
3609            .add_install_fail()
3610            .build();
3611        let reboot_called = Rc::clone(&installer.reboot_called);
3612        let (_ctl, state_machine) = pool.run_until(
3613            StateMachineBuilder::new_stub()
3614                .http(http)
3615                .installer(installer)
3616                .policy_engine(StubPolicyEngine::new(mock_time))
3617                .timer(timer)
3618                .start(),
3619        );
3620        let observer = TestObserver::default();
3621        spawner
3622            .spawn_local(observer.observe(state_machine))
3623            .unwrap();
3624
3625        let blocked_timer = pool.run_until(timers.next()).unwrap();
3626        assert_eq!(
3627            blocked_timer.requested_wait(),
3628            RequestedWait::Until(next_update_time.into())
3629        );
3630        blocked_timer.unblock();
3631        pool.run_until_stalled();
3632
3633        assert!(!*reboot_called.borrow());
3634    }
3635
3636    // Verify that if we are in the middle of checking for or applying an update, a new OnDemand
3637    // update check request will "upgrade" the inflight check request to behave as if it was
3638    // OnDemand. In particular, this should cause an immediate reboot.
3639    #[test]
3640    fn test_reboots_immediately_if_user_initiated_update_requests_occurs_during_install() {
3641        let mut pool = LocalPool::new();
3642        let spawner = pool.spawner();
3643
3644        let http = MockHttpRequest::new(make_update_available_response());
3645        let mock_time = MockTimeSource::new_from_now();
3646
3647        let (send_install, mut recv_install) = mpsc::channel(0);
3648        let (send_reboot, mut recv_reboot) = mpsc::channel(0);
3649        let reboot_check_options_received = Rc::new(RefCell::new(vec![]));
3650        let policy_engine = MockPolicyEngine {
3651            reboot_check_options_received: Rc::clone(&reboot_check_options_received),
3652            check_timing: Some(CheckTiming::builder().time(mock_time.now()).build()),
3653            ..MockPolicyEngine::default()
3654        };
3655
3656        let (mut ctl, state_machine) = pool.run_until(
3657            StateMachineBuilder::new_stub()
3658                .http(http)
3659                .installer(BlockingInstaller {
3660                    on_install: send_install,
3661                    on_reboot: Some(send_reboot),
3662                })
3663                .policy_engine(policy_engine)
3664                .start(),
3665        );
3666
3667        let observer = TestObserver::default();
3668        spawner
3669            .spawn_local(observer.observe(state_machine))
3670            .unwrap();
3671
3672        let unblock_install = pool.run_until(recv_install.next()).unwrap();
3673        pool.run_until_stalled();
3674        assert_eq!(
3675            observer.take_states(),
3676            vec![
3677                State::CheckingForUpdates(InstallSource::ScheduledTask),
3678                State::InstallingUpdate
3679            ]
3680        );
3681
3682        pool.run_until(async {
3683            assert_eq!(
3684                ctl.start_update_check(CheckOptions {
3685                    source: InstallSource::OnDemand
3686                })
3687                .await,
3688                Ok(StartUpdateCheckResponse::AlreadyRunning)
3689            );
3690        });
3691
3692        pool.run_until_stalled();
3693        assert_eq!(observer.take_states(), vec![]);
3694
3695        unblock_install
3696            .send(vec![AppInstallResult::Installed])
3697            .unwrap();
3698        pool.run_until_stalled();
3699        assert_eq!(observer.take_states(), vec![State::WaitingForReboot]);
3700
3701        let unblock_reboot = pool.run_until(recv_reboot.next()).unwrap();
3702        pool.run_until_stalled();
3703        unblock_reboot.send(Ok(())).unwrap();
3704
3705        // Make sure when we checked whether we could reboot, it was from an OnDemand source
3706        assert_eq!(
3707            *reboot_check_options_received.borrow(),
3708            vec![CheckOptions {
3709                source: InstallSource::OnDemand
3710            }]
3711        );
3712    }
3713
3714    // Verifies that if the state machine is done with an install and waiting for a reboot, and a
3715    // user-initiated UpdateCheckRequest comes in, we reboot immediately.
3716    #[test]
3717    fn test_reboots_immediately_when_check_now_comes_in_during_wait() {
3718        let mut pool = LocalPool::new();
3719        let spawner = pool.spawner();
3720
3721        let mut http = MockHttpRequest::new(make_update_available_response());
3722        // Responses to events.
3723        http.add_response(HttpResponse::new(vec![]));
3724        http.add_response(HttpResponse::new(vec![]));
3725        http.add_response(HttpResponse::new(vec![]));
3726        // Response to the ping.
3727        http.add_response(make_update_available_response());
3728        let mut mock_time = MockTimeSource::new_from_now();
3729        mock_time.truncate_submicrosecond_walltime();
3730        let next_update_time = mock_time.now() + Duration::from_secs(1000);
3731        let (timer, mut timers) = BlockingTimer::new();
3732        let reboot_allowed = Rc::new(RefCell::new(false));
3733        let reboot_check_options_received = Rc::new(RefCell::new(vec![]));
3734        let policy_engine = MockPolicyEngine {
3735            time_source: mock_time.clone(),
3736            reboot_allowed: Rc::clone(&reboot_allowed),
3737            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
3738            reboot_check_options_received: Rc::clone(&reboot_check_options_received),
3739            ..MockPolicyEngine::default()
3740        };
3741        let installer = TestInstaller::builder(mock_time.clone()).build();
3742        let reboot_called = Rc::clone(&installer.reboot_called);
3743        let storage_ref = Rc::new(Mutex::new(MemStorage::new()));
3744        let apps = make_test_app_set();
3745
3746        let (mut ctl, state_machine) = pool.run_until(
3747            StateMachineBuilder::new_stub()
3748                .app_set(apps)
3749                .http(http)
3750                .installer(installer)
3751                .policy_engine(policy_engine)
3752                .timer(timer)
3753                .storage(Rc::clone(&storage_ref))
3754                .start(),
3755        );
3756
3757        let observer = TestObserver::default();
3758        spawner
3759            .spawn_local(observer.observe(state_machine))
3760            .unwrap();
3761
3762        // The first wait before update check.
3763        let blocked_timer = pool.run_until(timers.next()).unwrap();
3764        assert_eq!(
3765            blocked_timer.requested_wait(),
3766            RequestedWait::Until(next_update_time.into())
3767        );
3768        blocked_timer.unblock();
3769        pool.run_until_stalled();
3770
3771        // The timers for reboot and ping, even though the order should be deterministic, but that
3772        // is an implementation detail, the test should still pass if that order changes.
3773        let blocked_timer1 = pool.run_until(timers.next()).unwrap();
3774        let blocked_timer2 = pool.run_until(timers.next()).unwrap();
3775        let (wait_for_reboot_timer, _wait_for_next_ping_timer) =
3776            match blocked_timer1.requested_wait() {
3777                RequestedWait::For(_) => (blocked_timer1, blocked_timer2),
3778                RequestedWait::Until(_) => (blocked_timer2, blocked_timer1),
3779            };
3780        // This is the timer waiting for next reboot_allowed check.
3781        assert_eq!(
3782            wait_for_reboot_timer.requested_wait(),
3783            RequestedWait::For(CHECK_REBOOT_ALLOWED_INTERVAL)
3784        );
3785
3786        // If we send an update check request that's from a user (source == OnDemand), we should
3787        // short-circuit the wait for reboot, and update immediately.
3788        assert!(!*reboot_called.borrow());
3789        *reboot_allowed.borrow_mut() = true;
3790        pool.run_until(async {
3791            assert_eq!(
3792                ctl.start_update_check(CheckOptions {
3793                    source: InstallSource::OnDemand
3794                })
3795                .await,
3796                Ok(StartUpdateCheckResponse::AlreadyRunning)
3797            );
3798        });
3799        pool.run_until_stalled();
3800        assert!(*reboot_called.borrow());
3801
3802        // Check that we got one check for reboot from a Scheduled Task (the start of the wait),
3803        // and then another came in with OnDemand, as we "upgraded it" with our OnDemand check
3804        // request
3805        assert_eq!(
3806            *reboot_check_options_received.borrow(),
3807            vec![
3808                CheckOptions {
3809                    source: InstallSource::ScheduledTask
3810                },
3811                CheckOptions {
3812                    source: InstallSource::OnDemand
3813                },
3814            ]
3815        );
3816    }
3817
3818    // Verifies that if reboot is not allowed, state machine will send pings to Omaha while waiting
3819    // for reboot, and it will reply AlreadyRunning to any StartUpdateCheck requests, and when it's
3820    // finally time to reboot, it will trigger reboot.
3821    #[test]
3822    fn test_wait_for_reboot() {
3823        let mut pool = LocalPool::new();
3824        let spawner = pool.spawner();
3825
3826        let mut http = MockHttpRequest::new(make_update_available_response());
3827        // Responses to events.
3828        http.add_response(HttpResponse::new(vec![]));
3829        http.add_response(HttpResponse::new(vec![]));
3830        http.add_response(HttpResponse::new(vec![]));
3831        // Response to the ping.
3832        http.add_response(make_update_available_response());
3833        let ping_request_viewer = MockHttpRequest::from_request_cell(http.get_request_cell());
3834        let mut mock_time = MockTimeSource::new_from_now();
3835        mock_time.truncate_submicrosecond_walltime();
3836        let next_update_time = mock_time.now() + Duration::from_secs(1000);
3837        let (timer, mut timers) = BlockingTimer::new();
3838        let reboot_allowed = Rc::new(RefCell::new(false));
3839        let policy_engine = MockPolicyEngine {
3840            time_source: mock_time.clone(),
3841            reboot_allowed: Rc::clone(&reboot_allowed),
3842            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
3843            ..MockPolicyEngine::default()
3844        };
3845        let installer = TestInstaller::builder(mock_time.clone()).build();
3846        let reboot_called = Rc::clone(&installer.reboot_called);
3847        let storage_ref = Rc::new(Mutex::new(MemStorage::new()));
3848        let apps = make_test_app_set();
3849
3850        let (mut ctl, state_machine) = pool.run_until(
3851            StateMachineBuilder::new_stub()
3852                .app_set(apps.clone())
3853                .http(http)
3854                .installer(installer)
3855                .policy_engine(policy_engine)
3856                .timer(timer)
3857                .storage(Rc::clone(&storage_ref))
3858                .start(),
3859        );
3860
3861        let observer = TestObserver::default();
3862        spawner
3863            .spawn_local(observer.observe(state_machine))
3864            .unwrap();
3865
3866        // The first wait before update check.
3867        let blocked_timer = pool.run_until(timers.next()).unwrap();
3868        assert_eq!(
3869            blocked_timer.requested_wait(),
3870            RequestedWait::Until(next_update_time.into())
3871        );
3872        blocked_timer.unblock();
3873        pool.run_until_stalled();
3874
3875        // The timers for reboot and ping, even though the order should be deterministic, but that
3876        // is an implementation detail, the test should still pass if that order changes.
3877        let blocked_timer1 = pool.run_until(timers.next()).unwrap();
3878        let blocked_timer2 = pool.run_until(timers.next()).unwrap();
3879        let (wait_for_reboot_timer, wait_for_next_ping_timer) =
3880            match blocked_timer1.requested_wait() {
3881                RequestedWait::For(_) => (blocked_timer1, blocked_timer2),
3882                RequestedWait::Until(_) => (blocked_timer2, blocked_timer1),
3883            };
3884        // This is the timer waiting for next reboot_allowed check.
3885        assert_eq!(
3886            wait_for_reboot_timer.requested_wait(),
3887            RequestedWait::For(CHECK_REBOOT_ALLOWED_INTERVAL)
3888        );
3889        // This is the timer waiting for the next ping.
3890        assert_eq!(
3891            wait_for_next_ping_timer.requested_wait(),
3892            RequestedWait::Until(next_update_time.into())
3893        );
3894        // Unblock the ping.
3895        mock_time.advance(Duration::from_secs(1000));
3896        wait_for_next_ping_timer.unblock();
3897        pool.run_until_stalled();
3898
3899        // Verify that it sends a ping.
3900        let config = crate::configuration::test_support::config_generator();
3901        let request_params = RequestParams::default();
3902
3903        let apps = pool.run_until(apps.lock()).get_apps();
3904        let mut expected_request_builder = RequestBuilder::new(&config, &request_params)
3905            // 0: session id for update check
3906            // 1: request id for update check
3907            // 2-4: request id for events
3908            .session_id(GUID::from_u128(5))
3909            .request_id(GUID::from_u128(6));
3910        for app in &apps {
3911            expected_request_builder = expected_request_builder.add_ping(app);
3912        }
3913        pool.run_until(assert_request(
3914            &ping_request_viewer,
3915            expected_request_builder,
3916        ));
3917
3918        pool.run_until(async {
3919            assert_eq!(
3920                ctl.start_update_check(CheckOptions::default()).await,
3921                Ok(StartUpdateCheckResponse::AlreadyRunning)
3922            );
3923        });
3924
3925        // Last update time is updated in storage.
3926        pool.run_until(async {
3927            let storage = storage_ref.lock().await;
3928            let context = update_check::Context::load(&*storage).await;
3929            assert_eq!(
3930                context.schedule.last_update_time,
3931                Some(mock_time.now_in_walltime().into())
3932            );
3933        });
3934
3935        // State machine should be waiting for the next ping.
3936        let wait_for_next_ping_timer = pool.run_until(timers.next()).unwrap();
3937        assert_eq!(
3938            wait_for_next_ping_timer.requested_wait(),
3939            RequestedWait::Until(next_update_time.into())
3940        );
3941
3942        // Let state machine check reboot_allowed again, but still don't allow it.
3943        wait_for_reboot_timer.unblock();
3944        pool.run_until_stalled();
3945        assert!(!*reboot_called.borrow());
3946
3947        // State machine should be waiting for the next reboot.
3948        let wait_for_reboot_timer = pool.run_until(timers.next()).unwrap();
3949        assert_eq!(
3950            wait_for_reboot_timer.requested_wait(),
3951            RequestedWait::For(CHECK_REBOOT_ALLOWED_INTERVAL)
3952        );
3953
3954        // Time for a second ping.
3955        wait_for_next_ping_timer.unblock();
3956        pool.run_until_stalled();
3957
3958        // Verify that it sends another ping.
3959        let mut expected_request_builder = RequestBuilder::new(&config, &request_params)
3960            .session_id(GUID::from_u128(7))
3961            .request_id(GUID::from_u128(8));
3962        for app in &apps {
3963            expected_request_builder = expected_request_builder.add_ping(app);
3964        }
3965        pool.run_until(assert_request(
3966            &ping_request_viewer,
3967            expected_request_builder,
3968        ));
3969
3970        assert!(!*reboot_called.borrow());
3971
3972        // Now allow reboot.
3973        *reboot_called.borrow_mut() = true;
3974        wait_for_reboot_timer.unblock();
3975        pool.run_until_stalled();
3976        assert!(*reboot_called.borrow());
3977    }
3978
3979    #[derive(Debug)]
3980    struct BlockingInstaller {
3981        on_install: mpsc::Sender<oneshot::Sender<Vec<AppInstallResult<StubInstallErrors>>>>,
3982        on_reboot: Option<mpsc::Sender<oneshot::Sender<Result<(), anyhow::Error>>>>,
3983    }
3984
3985    impl Installer for BlockingInstaller {
3986        type InstallPlan = StubPlan;
3987        type Error = StubInstallErrors;
3988        type InstallResult = ();
3989
3990        fn perform_install(
3991            &mut self,
3992            _install_plan: &StubPlan,
3993            _observer: Option<&dyn ProgressObserver>,
3994        ) -> LocalBoxFuture<'_, (Self::InstallResult, Vec<AppInstallResult<Self::Error>>)> {
3995            let (send, recv) = oneshot::channel();
3996            let send_fut = self.on_install.send(send);
3997
3998            async move {
3999                send_fut.await.unwrap();
4000                ((), recv.await.unwrap())
4001            }
4002            .boxed_local()
4003        }
4004
4005        fn perform_reboot(&mut self) -> LocalBoxFuture<'_, Result<(), anyhow::Error>> {
4006            match &mut self.on_reboot {
4007                Some(on_reboot) => {
4008                    let (send, recv) = oneshot::channel();
4009                    let send_fut = on_reboot.send(send);
4010
4011                    async move {
4012                        send_fut.await.unwrap();
4013                        recv.await.unwrap()
4014                    }
4015                    .boxed_local()
4016                }
4017                None => future::ready(Ok(())).boxed_local(),
4018            }
4019        }
4020
4021        fn try_create_install_plan<'a>(
4022            &'a self,
4023            _request_params: &'a RequestParams,
4024            _request_metadata: Option<&'a RequestMetadata>,
4025            _response: &'a Response,
4026            _response_bytes: Vec<u8>,
4027            _ecdsa_signature: Option<Vec<u8>>,
4028        ) -> LocalBoxFuture<'a, Result<Self::InstallPlan, Self::Error>> {
4029            future::ready(Ok(StubPlan)).boxed_local()
4030        }
4031    }
4032
4033    #[derive(Debug, Default)]
4034    struct TestObserver {
4035        states: Rc<RefCell<Vec<State>>>,
4036    }
4037
4038    impl TestObserver {
4039        fn observe(&self, s: impl Stream<Item = StateMachineEvent>) -> impl Future<Output = ()> {
4040            let states = Rc::clone(&self.states);
4041            async move {
4042                futures::pin_mut!(s);
4043                while let Some(event) = s.next().await {
4044                    if let StateMachineEvent::StateChange(state) = event {
4045                        states.borrow_mut().push(state);
4046                    }
4047                }
4048            }
4049        }
4050
4051        fn observe_until_terminal(
4052            &self,
4053            s: impl Stream<Item = StateMachineEvent>,
4054        ) -> impl Future<Output = ()> {
4055            let states = Rc::clone(&self.states);
4056            async move {
4057                futures::pin_mut!(s);
4058                while let Some(event) = s.next().await {
4059                    if let StateMachineEvent::StateChange(state) = event {
4060                        states.borrow_mut().push(state);
4061                        match state {
4062                            State::Idle | State::WaitingForReboot => return,
4063                            _ => {}
4064                        }
4065                    }
4066                }
4067            }
4068        }
4069
4070        fn take_states(&self) -> Vec<State> {
4071            std::mem::take(&mut *self.states.borrow_mut())
4072        }
4073    }
4074
4075    #[test]
4076    fn test_start_update_during_update_replies_with_in_progress() {
4077        let mut pool = LocalPool::new();
4078        let spawner = pool.spawner();
4079
4080        let http = MockHttpRequest::new(make_update_available_response());
4081        let (send_install, mut recv_install) = mpsc::channel(0);
4082        let (mut ctl, state_machine) = pool.run_until(
4083            StateMachineBuilder::new_stub()
4084                .http(http)
4085                .installer(BlockingInstaller {
4086                    on_install: send_install,
4087                    on_reboot: None,
4088                })
4089                .start(),
4090        );
4091
4092        let observer = TestObserver::default();
4093        spawner
4094            .spawn_local(observer.observe_until_terminal(state_machine))
4095            .unwrap();
4096
4097        let unblock_install = pool.run_until(recv_install.next()).unwrap();
4098        pool.run_until_stalled();
4099        assert_eq!(
4100            observer.take_states(),
4101            vec![
4102                State::CheckingForUpdates(InstallSource::ScheduledTask),
4103                State::InstallingUpdate
4104            ]
4105        );
4106
4107        pool.run_until(async {
4108            assert_eq!(
4109                ctl.start_update_check(CheckOptions::default()).await,
4110                Ok(StartUpdateCheckResponse::AlreadyRunning)
4111            );
4112        });
4113        pool.run_until_stalled();
4114        assert_eq!(observer.take_states(), vec![]);
4115
4116        unblock_install
4117            .send(vec![AppInstallResult::Installed])
4118            .unwrap();
4119        pool.run_until_stalled();
4120
4121        assert_eq!(observer.take_states(), vec![State::WaitingForReboot]);
4122    }
4123
4124    #[test]
4125    fn test_start_update_during_timer_starts_update() {
4126        let mut pool = LocalPool::new();
4127        let spawner = pool.spawner();
4128
4129        let mut mock_time = MockTimeSource::new_from_now();
4130        let next_update_time = mock_time.now() + Duration::from_secs(321);
4131
4132        let (timer, mut timers) = BlockingTimer::new();
4133        let policy_engine = MockPolicyEngine {
4134            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
4135            time_source: mock_time.clone(),
4136            ..MockPolicyEngine::default()
4137        };
4138        let (mut ctl, state_machine) = pool.run_until(
4139            StateMachineBuilder::new_stub()
4140                .policy_engine(policy_engine)
4141                .timer(timer)
4142                .start(),
4143        );
4144
4145        let observer = TestObserver::default();
4146        spawner
4147            .spawn_local(observer.observe(state_machine))
4148            .unwrap();
4149
4150        let blocked_timer = pool.run_until(timers.next()).unwrap();
4151        assert_eq!(
4152            blocked_timer.requested_wait(),
4153            RequestedWait::Until(next_update_time.into())
4154        );
4155        mock_time.advance(Duration::from_secs(200));
4156        assert_eq!(observer.take_states(), vec![]);
4157
4158        // Nothing happens while the timer is waiting.
4159        pool.run_until_stalled();
4160        assert_eq!(observer.take_states(), vec![]);
4161
4162        blocked_timer.unblock();
4163        let blocked_timer = pool.run_until(timers.next()).unwrap();
4164        assert_eq!(
4165            blocked_timer.requested_wait(),
4166            RequestedWait::Until(next_update_time.into())
4167        );
4168        assert_eq!(
4169            observer.take_states(),
4170            vec![
4171                State::CheckingForUpdates(InstallSource::ScheduledTask),
4172                State::ErrorCheckingForUpdate,
4173                State::Idle
4174            ]
4175        );
4176
4177        // Unless a control signal to start an update check comes in.
4178        pool.run_until(async {
4179            assert_eq!(
4180                ctl.start_update_check(CheckOptions::default()).await,
4181                Ok(StartUpdateCheckResponse::Started)
4182            );
4183        });
4184        pool.run_until_stalled();
4185        assert_eq!(
4186            observer.take_states(),
4187            vec![
4188                State::CheckingForUpdates(InstallSource::ScheduledTask),
4189                State::ErrorCheckingForUpdate,
4190                State::Idle
4191            ]
4192        );
4193    }
4194
4195    #[test]
4196    fn test_start_update_check_returns_throttled() {
4197        let mut pool = LocalPool::new();
4198        let spawner = pool.spawner();
4199
4200        let mut mock_time = MockTimeSource::new_from_now();
4201        let next_update_time = mock_time.now() + Duration::from_secs(321);
4202
4203        let (timer, mut timers) = BlockingTimer::new();
4204        let policy_engine = MockPolicyEngine {
4205            check_timing: Some(CheckTiming::builder().time(next_update_time).build()),
4206            time_source: mock_time.clone(),
4207            check_decision: CheckDecision::ThrottledByPolicy,
4208            ..MockPolicyEngine::default()
4209        };
4210        let (mut ctl, state_machine) = pool.run_until(
4211            StateMachineBuilder::new_stub()
4212                .policy_engine(policy_engine)
4213                .timer(timer)
4214                .start(),
4215        );
4216
4217        let observer = TestObserver::default();
4218        spawner
4219            .spawn_local(observer.observe(state_machine))
4220            .unwrap();
4221
4222        let blocked_timer = pool.run_until(timers.next()).unwrap();
4223        assert_eq!(
4224            blocked_timer.requested_wait(),
4225            RequestedWait::Until(next_update_time.into())
4226        );
4227        mock_time.advance(Duration::from_secs(200));
4228        assert_eq!(observer.take_states(), vec![]);
4229
4230        pool.run_until(async {
4231            assert_eq!(
4232                ctl.start_update_check(CheckOptions::default()).await,
4233                Ok(StartUpdateCheckResponse::Throttled)
4234            );
4235        });
4236        pool.run_until_stalled();
4237        assert_eq!(observer.take_states(), vec![]);
4238    }
4239
4240    #[test]
4241    fn test_progress_observer() {
4242        block_on(async {
4243            let http = MockHttpRequest::new(make_update_available_response());
4244            let mock_time = MockTimeSource::new_from_now();
4245            let progresses = StateMachineBuilder::new_stub()
4246                .http(http)
4247                .installer(TestInstaller::builder(mock_time.clone()).build())
4248                .policy_engine(StubPolicyEngine::new(mock_time))
4249                .oneshot_check()
4250                .await
4251                .filter_map(|event| {
4252                    future::ready(match event {
4253                        StateMachineEvent::InstallProgressChange(InstallProgress { progress }) => {
4254                            Some(progress)
4255                        }
4256                        _ => None,
4257                    })
4258                })
4259                .collect::<Vec<f32>>()
4260                .await;
4261            assert_eq!(progresses, [0.0, 0.3, 0.9, 1.0]);
4262        });
4263    }
4264
4265    #[test]
4266    // A scenario in which
4267    // (now_in_monotonic - state_machine_start_in_monotonic) > (update_finish_time - now_in_wall)
4268    // should not panic.
4269    fn test_report_waited_for_reboot_duration_doesnt_panic_on_wrong_current_time() {
4270        block_on(async {
4271            let metrics_reporter = MockMetricsReporter::new();
4272
4273            let state_machine_start_monotonic = Instant::now();
4274            let update_finish_time = SystemTime::now();
4275
4276            // Set the monotonic increase in time larger than the wall time increase since the end
4277            // of the last update.
4278            // This can happen if we don't have a reliable current wall time.
4279            let now_wall = update_finish_time + Duration::from_secs(1);
4280            let now_monotonic = state_machine_start_monotonic + Duration::from_secs(10);
4281
4282            let mut state_machine = StateMachineBuilder::new_stub()
4283                .metrics_reporter(metrics_reporter)
4284                .build()
4285                .await;
4286
4287            // Time has advanced monotonically since we noted the start of the state machine for
4288            // longer than the wall time difference between update finish time and now.
4289            // This computation should currently overflow.
4290            state_machine
4291                .report_waited_for_reboot_duration(
4292                    update_finish_time,
4293                    state_machine_start_monotonic,
4294                    ComplexTime {
4295                        wall: now_wall,
4296                        mono: now_monotonic,
4297                    },
4298                )
4299                .expect_err("should overflow and error out");
4300
4301            // We should have reported no metrics
4302            assert!(state_machine.metrics_reporter.metrics.is_empty());
4303        });
4304    }
4305
4306    #[test]
4307    fn test_report_waited_for_reboot_duration() {
4308        let mut pool = LocalPool::new();
4309        let spawner = pool.spawner();
4310
4311        let response = json!({"response": {
4312            "server": "prod",
4313            "protocol": "3.0",
4314            "app": [{
4315            "appid": "{00000000-0000-0000-0000-000000000001}",
4316            "status": "ok",
4317            "updatecheck": {
4318                "status": "ok",
4319                "manifest": {
4320                    "version": "1.2.3.5",
4321                    "actions": {
4322                        "action": [],
4323                    },
4324                    "packages": {
4325                        "package": [],
4326                    },
4327                }
4328            }
4329            }],
4330        }});
4331        let response = serde_json::to_vec(&response).unwrap();
4332        let http = MockHttpRequest::new(HttpResponse::new(response));
4333        let mut mock_time = MockTimeSource::new_from_now();
4334        mock_time.truncate_submicrosecond_walltime();
4335        let storage = Rc::new(Mutex::new(MemStorage::new()));
4336
4337        // Do one update.
4338        assert_matches!(
4339            pool.run_until(
4340                StateMachineBuilder::new_stub()
4341                    .http(http)
4342                    .policy_engine(StubPolicyEngine::new(mock_time.clone()))
4343                    .storage(Rc::clone(&storage))
4344                    .oneshot(RequestParams::default())
4345            ),
4346            Ok(_)
4347        );
4348
4349        mock_time.advance(Duration::from_secs(999));
4350
4351        // Execute state machine `run()`, simulating that we already rebooted.
4352        let config = Config {
4353            updater: Updater {
4354                name: "updater".to_string(),
4355                version: Version::from([0, 1]),
4356            },
4357            os: OS {
4358                version: "1.2.3.5".to_string(),
4359                ..OS::default()
4360            },
4361            service_url: "http://example.com/".to_string(),
4362            omaha_public_keys: None,
4363        };
4364        let metrics_reporter = Rc::new(RefCell::new(MockMetricsReporter::new()));
4365        let (_ctl, state_machine) = pool.run_until(
4366            StateMachineBuilder::new_stub()
4367                .config(config)
4368                .metrics_reporter(Rc::clone(&metrics_reporter))
4369                .policy_engine(StubPolicyEngine::new(mock_time.clone()))
4370                .storage(Rc::clone(&storage))
4371                .timer(MockTimer::new())
4372                .start(),
4373        );
4374
4375        // Move state machine forward using observer.
4376        let observer = TestObserver::default();
4377        spawner
4378            .spawn_local(observer.observe(state_machine))
4379            .unwrap();
4380        pool.run_until_stalled();
4381
4382        assert_eq!(
4383            metrics_reporter
4384                .borrow()
4385                .metrics
4386                .iter()
4387                .filter(|m| matches!(m, Metrics::WaitedForRebootDuration(_)))
4388                .collect::<Vec<_>>(),
4389            vec![&Metrics::WaitedForRebootDuration(Duration::from_secs(999))]
4390        );
4391
4392        // Verify that storage is cleaned up.
4393        pool.run_until(async {
4394            let storage = storage.lock().await;
4395            assert_eq!(storage.get_time(UPDATE_FINISH_TIME).await, None);
4396            assert_eq!(storage.get_string(TARGET_VERSION).await, None);
4397            assert!(storage.committed());
4398        })
4399    }
4400
4401    // The same as |run_simple_check_with_noupdate_result|, but with CUPv2 protocol validation.
4402    #[test]
4403    fn run_cup_but_decoration_error() {
4404        block_on(async {
4405            let http = MockHttpRequest::new(HttpResponse::new(make_noupdate_httpresponse()));
4406
4407            let stub_cup_handler = MockCupv2Handler::new().set_decoration_error(|| {
4408                Some(CupDecorationError::ParseError(
4409                    "".parse::<http::Uri>().unwrap_err(),
4410                ))
4411            });
4412
4413            assert_matches!(
4414                StateMachineBuilder::new_stub()
4415                    .http(http)
4416                    .cup_handler(Some(stub_cup_handler))
4417                    .oneshot(RequestParams::default())
4418                    .await,
4419                Err(UpdateCheckError::OmahaRequest(
4420                    OmahaRequestError::CupDecoration(CupDecorationError::ParseError(_))
4421                ))
4422            );
4423
4424            info!("update check complete!");
4425        });
4426    }
4427
4428    #[test]
4429    fn run_cup_but_verification_error() {
4430        block_on(async {
4431            let http = MockHttpRequest::new(HttpResponse::new(make_noupdate_httpresponse()));
4432
4433            let stub_cup_handler = MockCupv2Handler::new()
4434                .set_verification_error(|| Some(CupVerificationError::EtagHeaderMissing));
4435
4436            assert_matches!(
4437                StateMachineBuilder::new_stub()
4438                    .http(http)
4439                    .cup_handler(Some(stub_cup_handler))
4440                    .oneshot(RequestParams::default())
4441                    .await,
4442                Err(UpdateCheckError::OmahaRequest(
4443                    OmahaRequestError::CupValidation(CupVerificationError::EtagHeaderMissing)
4444                ))
4445            );
4446
4447            info!("update check complete!");
4448        });
4449    }
4450
4451    #[test]
4452    fn run_cup_valid() {
4453        block_on(async {
4454            let http = MockHttpRequest::new(HttpResponse::new(make_noupdate_httpresponse()));
4455
4456            assert_matches!(
4457                StateMachineBuilder::new_stub()
4458                    .http(http)
4459                    // Default stub_cup_handler, which is permissive.
4460                    .oneshot(RequestParams::default())
4461                    .await,
4462                Ok(_)
4463            );
4464
4465            info!("update check complete!");
4466        });
4467    }
4468}