File: reporting_service.h

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (197 lines) | stat: -rw-r--r-- 7,709 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file defines a service that sends metrics logs to a server.

#ifndef COMPONENTS_METRICS_REPORTING_SERVICE_H_
#define COMPONENTS_METRICS_REPORTING_SERVICE_H_

#include <stdint.h>

#include <string>
#include <string_view>

#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/metrics/data_use_tracker.h"
#include "components/metrics/metrics_log_uploader.h"
#include "components/metrics/metrics_logs_event_manager.h"
#include "third_party/metrics_proto/reporting_info.pb.h"
#include "url/gurl.h"

class PrefService;
class PrefRegistrySimple;

namespace metrics {

class LogStore;
class MetricsUploadScheduler;
class MetricsServiceClient;

// ReportingService is an abstract class which uploads serialized logs from a
// LogStore to a remote server. A concrete implementation of this class must
// provide the specific LogStore and parameters for the MetricsLogUploader, and
// can also implement hooks to record histograms based on certain events that
// occur while attempting to upload logs.
class ReportingService {
 public:
  // Creates a ReportingService with the given |client|, |local_state|,
  // |max_retransmit_size|, and |logs_event_manager|. Does not take ownership
  // of the parameters; instead it stores a weak pointer to each. Caller should
  // ensure that the parameters are valid for the lifetime of this class.
  // |logs_event_manager| is used to notify observers of log events. Can be set
  // to null if observing the events is not necessary.
  ReportingService(MetricsServiceClient* client,
                   PrefService* local_state,
                   size_t max_retransmit_size,
                   MetricsLogsEventManager* logs_event_manager);

  ReportingService(const ReportingService&) = delete;
  ReportingService& operator=(const ReportingService&) = delete;

  virtual ~ReportingService();

  // Completes setup tasks that can't be done at construction time.
  // Loads persisted logs and creates the MetricsUploadScheduler.
  void Initialize();

  // Starts the metrics reporting system.
  // Should be called when metrics enabled or new logs are created.
  // When the service is already running, this is a safe no-op.
  void Start();

  // Shuts down the metrics system. Should be called at shutdown, or if metrics
  // are turned off.
  void Stop();

  // Enable/disable transmission of accumulated logs and crash reports (dumps).
  // Calling Start() automatically enables reporting, but sending is
  // asyncronous so this can be called immediately after Start() to prevent
  // any uploading.
  void EnableReporting();
  void DisableReporting();

  // True iff reporting is currently enabled.
  bool reporting_active() const;

#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  void OnAppEnterBackground();
  void OnAppEnterForeground();
#endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)

  // Registers local state prefs used by this class. This should only be called
  // once.
  static void RegisterPrefs(PrefRegistrySimple* registry);

 protected:
  MetricsServiceClient* client() const { return client_; }

 private:
  // Retrieves the log store backing this service.
  virtual LogStore* log_store() = 0;

  // Getters for MetricsLogUploader parameters.
  virtual GURL GetUploadUrl() const = 0;
  virtual GURL GetInsecureUploadUrl() const = 0;
  virtual std::string_view upload_mime_type() const = 0;
  virtual MetricsLogUploader::MetricServiceType service_type() const = 0;

  // Methods for recording data to histograms.
  virtual void LogActualUploadInterval(base::TimeDelta interval) {}
  virtual void LogCellularConstraint(bool upload_canceled) {}
  virtual void LogResponseOrErrorCode(int response_code,
                                      int error_code,
                                      bool was_https) {}
  virtual void LogSuccessLogSize(size_t log_size) {}
  virtual void LogSuccessMetadata(const std::string& staged_log) {}
  virtual void LogLargeRejection(size_t log_size) {}

  // If recording is enabled, begins uploading the next completed log from
  // the log manager, staging it if necessary.
  void SendNextLog();

  // Uploads the currently staged log (which must be non-null).
  void SendStagedLog();

  // Called after transmission completes (either successfully or with failure).
  // If |force_discard| is true, discard the log regardless of the response or
  // error code. For example, this is used for builds that do not include any
  // metrics server URLs (no reason to keep re-sending to a non-existent URL).
  void OnLogUploadComplete(int response_code,
                           int error_code,
                           bool was_https,
                           bool force_discard,
                           std::string_view force_discard_reason);

  // Used to interact with the embedder. Weak pointer; must outlive |this|
  // instance.
  const raw_ptr<MetricsServiceClient> client_;

  // Used to flush changes to disk after uploading a log. Weak pointer; must
  // outlive |this| instance.
  const raw_ptr<PrefService> local_state_;

  // Largest log size to attempt to retransmit.
  size_t max_retransmit_size_;

  // Event manager to notify observers of log events.
  const raw_ptr<MetricsLogsEventManager> logs_event_manager_;

  // Indicate whether recording and reporting are currently happening.
  // These should not be set directly, but by calling SetRecording and
  // SetReporting.
  bool reporting_active_;

  // Instance of the helper class for uploading logs.
  std::unique_ptr<MetricsLogUploader> log_uploader_;

  // Whether there is a current log upload in progress.
  bool log_upload_in_progress_;

#if BUILDFLAG(IS_ANDROID)
  // Whether the current log upload was initiated while the app was in the
  // background. Set only when there is a log upload in progress (i.e. when
  // `log_upload_in_progress_` above is true).
  // TODO: crbug.com/420459511 - Consider putting this and
  // `log_upload_in_progress_` together into a struct.
  std::optional<bool> log_upload_initiated_from_background_ = std::nullopt;

  // Set when the most recent uploads have failed. Its value will be whether the
  // first failure was from an upload initiated from the background. Unset when
  // a successful upload occurs.
  std::optional<bool> failures_started_from_background_ = std::nullopt;
#endif  // BUILDFLAG(IS_ANDROID)

  // The scheduler for determining when uploads should happen.
  std::unique_ptr<MetricsUploadScheduler> upload_scheduler_;

  // Pointer used for obtaining data use pref updater callback on above layers.
  std::unique_ptr<DataUseTracker> data_use_tracker_;

  // The tick count of the last time log upload has been finished and null if no
  // upload has been done yet.
  base::TimeTicks last_upload_finish_time_;

  // Info on current reporting state to send along with reports.
  ReportingInfo reporting_info_;

#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  // Indicates whether the browser is currently in the foreground. Used to
  // determine whether |local_state_| should be flushed immediately after
  // uploading a log.
  bool is_in_foreground_ = false;
#endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)

  SEQUENCE_CHECKER(sequence_checker_);

  // Weak pointers factory used to post task on different threads. All weak
  // pointers managed by this factory have the same lifetime as
  // ReportingService.
  base::WeakPtrFactory<ReportingService> self_ptr_factory_{this};
};

}  // namespace metrics

#endif  // COMPONENTS_METRICS_REPORTING_SERVICE_H_