1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/metrics/metrics_upload_scheduler.h"
9 #include "base/feature_list.h"
10 #include "base/metrics/field_trial_params.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "build/build_config.h"
14 #include "components/metrics/metrics_scheduler.h"
19 // When uploading metrics to the server fails, we progressively wait longer and
20 // longer before sending the next log. This backoff process helps reduce load
21 // on a server that is having issues.
22 // The following is the multiplier we use to expand that inter-log duration.
23 const double kBackoffMultiplier = 2;
25 // The maximum backoff interval in hours.
26 const int kMaxBackoffIntervalHours = 24;
28 // Minutes to wait if we are unable to upload due to data usage cap.
29 const int kOverDataUsageIntervalMinutes = 5;
31 // Increases the upload interval each time it's called, to handle the case
32 // where the server is having issues.
33 base::TimeDelta BackOffUploadInterval(base::TimeDelta interval) {
34 DCHECK_GT(kBackoffMultiplier, 1.0);
35 interval = base::Microseconds(
36 static_cast<int64_t>(kBackoffMultiplier * interval.InMicroseconds()));
38 base::TimeDelta max_interval = base::Hours(kMaxBackoffIntervalHours);
39 if (interval > max_interval || interval.InSeconds() < 0) {
40 interval = max_interval;
47 MetricsUploadScheduler::MetricsUploadScheduler(
48 const base::RepeatingClosure& upload_callback,
49 bool fast_startup_for_testing)
50 : MetricsScheduler(upload_callback, fast_startup_for_testing),
51 unsent_logs_interval_(GetUnsentLogsInterval()),
52 initial_backoff_interval_(GetInitialBackoffInterval()),
53 backoff_interval_(initial_backoff_interval_) {}
55 MetricsUploadScheduler::~MetricsUploadScheduler() = default;
58 base::TimeDelta MetricsUploadScheduler::GetUnsentLogsInterval() {
59 return base::Seconds(3);
63 base::TimeDelta MetricsUploadScheduler::GetInitialBackoffInterval() {
64 return base::Minutes(5);
67 void MetricsUploadScheduler::UploadFinished(bool server_is_healthy) {
68 // If the server is having issues, back off. Otherwise, reset to default
69 // (unless there are more logs to send, in which case the next upload should
71 if (!server_is_healthy) {
72 TaskDone(backoff_interval_);
73 backoff_interval_ = BackOffUploadInterval(backoff_interval_);
75 backoff_interval_ = initial_backoff_interval_;
76 TaskDone(unsent_logs_interval_);
80 void MetricsUploadScheduler::StopAndUploadCancelled() {
82 TaskDone(unsent_logs_interval_);
85 void MetricsUploadScheduler::UploadOverDataUsageCap() {
86 TaskDone(base::Minutes(kOverDataUsageIntervalMinutes));
89 } // namespace metrics