File: controller_impl.h

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (293 lines) | stat: -rw-r--r-- 12,485 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// 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.

#ifndef COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_CONTROLLER_IMPL_H_
#define COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_CONTROLLER_IMPL_H_

#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <vector>

#include "base/cancelable_callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/trace_event/memory_dump_provider.h"
#include "components/download/internal/background_service/controller.h"
#include "components/download/internal/background_service/download_blockage_status.h"
#include "components/download/internal/background_service/download_driver.h"
#include "components/download/internal/background_service/entry.h"
#include "components/download/internal/background_service/log_source.h"
#include "components/download/internal/background_service/model.h"
#include "components/download/internal/background_service/scheduler/device_status_listener.h"
#include "components/download/internal/background_service/service_config_impl.h"
#include "components/download/internal/background_service/startup_status.h"
#include "components/download/internal/background_service/stats.h"
#include "components/download/public/background_service/client.h"
#include "components/download/public/background_service/download_params.h"
#include "components/download/public/background_service/navigation_monitor.h"
#include "components/download/public/task/task_scheduler.h"

namespace download {

class ClientSet;
class DownloadDriver;
class FileMonitor;
class LogSink;
class Model;
class NavigationMonitor;
class Scheduler;

struct Configuration;
struct DownloadMetaData;
struct SchedulingParams;

// The internal Controller implementation.  This class does all of the heavy
// lifting for the BackgroundDownloadService.
class ControllerImpl : public Controller,
                       public DownloadDriver::Client,
                       public Model::Client,
                       public DeviceStatusListener::Observer,
                       public NavigationMonitor::Observer,
                       public LogSource,
                       public base::trace_event::MemoryDumpProvider {
 public:
  // |config| and |log_sink| are externally owned and must be guaranteed to
  // outlive this class.
  ControllerImpl(std::unique_ptr<Configuration> config,
                 std::unique_ptr<Logger> logger,
                 LogSink* log_sink,
                 std::unique_ptr<ClientSet> clients,
                 std::unique_ptr<DownloadDriver> driver,
                 std::unique_ptr<Model> model,
                 std::unique_ptr<DeviceStatusListener> device_status_listener,
                 NavigationMonitor* navigation_monitor,
                 std::unique_ptr<Scheduler> scheduler,
                 std::unique_ptr<TaskScheduler> task_scheduler,
                 std::unique_ptr<FileMonitor> file_monitor,
                 const base::FilePath& download_file_dir);

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

  ~ControllerImpl() override;

  // Controller implementation.
  void Initialize(base::OnceClosure callback) override;
  const ServiceConfig& GetConfig() override;
  BackgroundDownloadService::ServiceStatus GetStatus() override;
  State GetState() override;
  void StartDownload(DownloadParams params) override;
  void PauseDownload(const std::string& guid) override;
  void ResumeDownload(const std::string& guid) override;
  void CancelDownload(const std::string& guid) override;
  void ChangeDownloadCriteria(const std::string& guid,
                              const SchedulingParams& params) override;
  DownloadClient GetOwnerOfDownload(const std::string& guid) override;
  void OnStartScheduledTask(DownloadTaskType task_type,
                            TaskFinishedCallback callback) override;
  bool OnStopScheduledTask(DownloadTaskType task_type) override;
  Logger* GetLogger() override;

 private:
  // DownloadDriver::Client implementation.
  void OnDriverReady(bool success) override;
  void OnDriverHardRecoverComplete(bool success) override;
  void OnDownloadCreated(const DriverEntry& download) override;
  void OnDownloadFailed(const DriverEntry& download,
                        FailureType failure_type) override;
  void OnDownloadSucceeded(const DriverEntry& download) override;
  void OnDownloadUpdated(const DriverEntry& download) override;
  bool IsTrackingDownload(const std::string& guid) const override;
  void OnUploadProgress(const std::string& guid,
                        uint64_t bytes_uploaded) const override;

  // Model::Client implementation.
  void OnModelReady(bool success) override;
  void OnModelHardRecoverComplete(bool success) override;
  void OnItemAdded(bool success,
                   DownloadClient client,
                   const std::string& guid) override;
  void OnItemUpdated(bool success,
                     DownloadClient client,
                     const std::string& guid) override;
  void OnItemRemoved(bool success,
                     DownloadClient client,
                     const std::string& guid) override;

  // LogSource implementation.
  Controller::State GetControllerState() override;
  const StartupStatus& GetStartupStatus() override;
  LogSource::EntryDetailsList GetServiceDownloads() override;
  std::optional<EntryDetails> GetServiceDownload(
      const std::string& guid) override;

  // MemoryDumpProvider implementation.
  bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
                    base::trace_event::ProcessMemoryDump* pmd) override;

  // Called when the file monitor and download file directory are initialized.
  void OnFileMonitorReady(bool success);

  // Called when the file monitor finishes attempting to recover itself.
  void OnFileMonitorHardRecoverComplete(bool success);

  // DeviceStatusListener::Observer implementation.
  void OnDeviceStatusChanged(const DeviceStatus& device_status) override;

  // NavigationMonitor::Observer implementation.
  void OnNavigationEvent() override;

  // Checks if initialization is complete and successful.  If so, completes the
  // internal state initialization.
  void AttemptToFinalizeSetup();

  // Called when setup and recovery failed.  Shuts down the service and notifies
  // the Clients.
  void HandleUnrecoverableSetup();

  // If initialization failed, try to reset the state of all components and
  // restart them.  If that attempt fails the service will be unavailable.
  void StartHardRecoveryAttempt();

  // Checks for all the currently active driver downloads.  This lets us know
  // which ones are active that we haven't tracked.
  void PollActiveDriverDownloads();

  // Cancels and cleans upany requests that are no longer associated with a
  // Client in |clients_|.
  void CancelOrphanedRequests();

  // Cleans up any files that are left on the disk without any entries.
  void CleanupUnknownFiles();

  // Fixes any discrepancies in state between |model_| and |driver_|.  Meant to
  // resolve state issues during startup.
  void ResolveInitialRequestStates();

  // Updates the driver states based on the states of entries in download
  // service.
  void UpdateDriverStates();

  // See |UpdateDriverState|.
  void UpdateDriverStateWithGuid(const std::string& guid);

  // Processes the download based on the state of |entry|. May start, pause
  // or resume a download accordingly.
  void UpdateDriverState(Entry* entry);

  // Returns a struct representing various reasons whether the download cannot
  // start or continue at this time.
  DownloadBlockageStatus IsDownloadBlocked(Entry* entry);

  // Notifies all Client in |clients_| that this controller is initialized and
  // lets them know which download requests we are aware of for their
  // DownloadClient.
  void NotifyClientsOfStartup(bool state_lost);

  // Notifies the service that the startup has completed so that it can start
  // processing any pending requests.
  void NotifyServiceOfStartup();

  void HandleStartDownloadResponse(DownloadClient client,
                                   const std::string& guid,
                                   DownloadParams::StartResult result);
  void HandleStartDownloadResponse(DownloadClient client,
                                   const std::string& guid,
                                   DownloadParams::StartResult result,
                                   DownloadParams::StartCallback callback);

  // Handles and clears any pending task finished callbacks.
  void HandleTaskFinished(DownloadTaskType task_type,
                          stats::ScheduledTaskStatus status);
  void OnCompleteCleanupTask();

  void HandleCompleteDownload(CompletionType type, const std::string& guid);

  // Find more available entries to download, until the number of active entries
  // reached maximum.
  void ActivateMoreDownloads();

  // Whether the download should be paused or postponed in case of an active
  // navigation is in progress.
  bool ShouldBlockDownloadOnNavigation(Entry* entry);

  void RemoveCleanupEligibleDownloads();

  void HandleExternalDownload(const std::string& guid, bool active);
  void PrepareToStartDownload(Entry* entry);
  void OnDownloadReadyToStart(
      const std::string& guid,
      scoped_refptr<network::ResourceRequestBody> post_body);

  // Postable methods meant to just be pass throughs to Client APIs.  This is
  // meant to help prevent reentrancy.
  void SendOnServiceInitialized(DownloadClient client_id,
                                bool state_lost,
                                const std::vector<DownloadMetaData>& downloads);
  void SendOnServiceUnavailable();
  void SendOnDownloadUpdated(DownloadClient client_id,
                             const std::string& guid,
                             uint64_t bytes_uploaded,
                             uint64_t bytes_downloaded);
  void SendOnDownloadSucceeded(DownloadClient client_id,
                               const std::string& guid,
                               const CompletionInfo& completion_info);
  void SendOnDownloadFailed(DownloadClient client_id,
                            const std::string& guid,
                            const CompletionInfo& completion_info,
                            download::Client::FailureReason reason);

  // Schedules a cleanup task in future based on status of entries.
  void ScheduleCleanupTask();

  // Posts a task to cancel the downloads in future based on the cancel_after
  // time of the entries. If cancel time for an entry is already surpassed, the
  // task will be posted right away which will clean the entry.
  void ScheduleKillDownloadTaskIfNecessary();

  // Kills the downloads which have surpassed their cancel_after time.
  void KillTimedOutDownloads();

  // A periodical task that will kill all the pending uploads that haven't
  // received upload data from their respective clients.
  void KillTimedOutUploads();

  // The directory in which the downloaded files are stored.
  const base::FilePath download_file_dir_;

  // Owned Dependencies.
  std::unique_ptr<Configuration> config_;
  ServiceConfigImpl service_config_;
  std::unique_ptr<Logger> logger_;
  raw_ptr<LogSink, DanglingUntriaged> log_sink_;
  std::unique_ptr<ClientSet> clients_;
  std::unique_ptr<DownloadDriver> driver_;
  std::unique_ptr<Model> model_;
  std::unique_ptr<DeviceStatusListener> device_status_listener_;
  raw_ptr<NavigationMonitor> navigation_monitor_;
  std::unique_ptr<Scheduler> scheduler_;
  std::unique_ptr<TaskScheduler> task_scheduler_;
  std::unique_ptr<FileMonitor> file_monitor_;

  // Internal state.
  base::OnceClosure init_callback_;
  State controller_state_;
  StartupStatus startup_status_;
  std::set<std::string> externally_active_downloads_;
  std::set<std::string> pending_uploads_;
  std::map<std::string, DownloadParams::StartCallback> start_callbacks_;
  std::map<DownloadTaskType, TaskFinishedCallback> task_finished_callbacks_;
  base::CancelableOnceClosure cancel_downloads_callback_;
  base::CancelableOnceClosure cancel_uploads_callback_;

  // Only used to post tasks on the same thread.
  base::WeakPtrFactory<ControllerImpl> weak_ptr_factory_{this};
};

}  // namespace download

#endif  // COMPONENTS_DOWNLOAD_INTERNAL_BACKGROUND_SERVICE_CONTROLLER_IMPL_H_