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
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_FILE_UPLOAD_JOB_H_
#define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_FILE_UPLOAD_JOB_H_
#include <string>
#include <string_view>
#include <utility>
#include "base/containers/flat_map.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/no_destructor.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/thread_annotations.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/policy/messaging_layer/proto/synced/log_upload_event.pb.h"
#include "components/reporting/proto/synced/record.pb.h"
#include "components/reporting/proto/synced/record_constants.pb.h"
#include "components/reporting/proto/synced/upload_tracker.pb.h"
#include "components/reporting/resources/resource_manager.h"
#include "components/reporting/util/status.h"
#include "components/reporting/util/statusor.h"
namespace reporting {
// Restartable chunky upload, to reliably deliver a file to an external location
// (defined by the `Delegate`). It is created when certain upload is seen for
// the first time; however, it is not always at the 0 offset - it may have been
// started and made some progress before the device has been restarted.
class FileUploadJob {
public:
class TestEnvironment;
// Base class for actual upload activity.
// Pure virtual methods need to be implemented or mocked by the derived class,
// which would also populate and interpret `origin_path`, `upload_parameters`,
// `session_token` and `access_parameters`.
class Delegate {
public:
using SmartPtr = std::unique_ptr<Delegate, base::OnTaskRunnerDeleter>;
virtual ~Delegate();
// Asynchronously initializes upload.
// Calls back with `total` and `session_token` are set, or Status in case
// of error.
virtual void DoInitiate(
std::string_view origin_path,
std::string_view upload_parameters,
base::OnceCallback<
void(StatusOr<std::pair<int64_t /*total*/,
std::string /*session_token*/>>)> cb) = 0;
// Asynchronously uploads the next chunk.
// Uses `scoped_reservation` to manage memory usage by data buffer.
// Calls back with new `uploaded` and `session_token` (could be the same),
// or Status in case of an error.
virtual void DoNextStep(
int64_t total,
int64_t uploaded,
std::string_view session_token,
ScopedReservation scoped_reservation,
base::OnceCallback<
void(StatusOr<std::pair<int64_t /*uploaded*/,
std::string /*session_token*/>>)> cb) = 0;
// Asynchronously finalizes upload (once `uploaded` reached `total`).
// Calls back with `access_parameters`, or Status in case of error.
virtual void DoFinalize(
std::string_view session_token,
base::OnceCallback<void(StatusOr<std::string /*access_parameters*/>)>
cb) = 0;
// Asynchronously deletes the original file (either upon success, or when
// the failure happened when `retry_count` dropped to 0). Doesn't wait for
// completion and doesn't report the outcome.
virtual void DoDeleteFile(std::string_view origin_path) = 0;
// Returns weak pointer.
base::WeakPtr<Delegate> GetWeakPtr();
protected:
Delegate();
base::WeakPtrFactory<Delegate> weak_ptr_factory_{this};
};
// Singleton manager class responsible for keeping track of incoming jobs:
// when an event shows up for processing, it needs to create a FileUploadJob
// but only if the same job is not already in progress because of the same
// upload events showing up earlier.
class Manager {
public:
// Job lifetime (extended on every update).
static constexpr base::TimeDelta kLifeTime = base::Hours(1);
// Access single instance of the manager.
static Manager* GetInstance();
~Manager();
// Registers new job to the map or finds it, if the matching one is already
// there. Hands over to the callback (if it is indeed new, the first action
// needs to be initiation, otherwise processing based on the current state).
// The returned job is owned by the `Manager`.
void Register(Priority priority,
Record record_copy,
::ash::reporting::LogUploadEvent log_upload_event,
Delegate::SmartPtr delegate,
base::OnceCallback<void(StatusOr<FileUploadJob*>)> result_cb);
// Accessor.
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner() const;
private:
friend class base::NoDestructor<Manager>;
friend class TestEnvironment;
// Private constructor, used only internally and in TestEnvironment.
Manager();
// Task runner is not declared `const` for testing: to be able to reset it.
scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_;
SEQUENCE_CHECKER(manager_sequence_checker_);
// Access manager instance, used only internally and in TestEnvironment.
static std::unique_ptr<FileUploadJob::Manager>& instance_ref();
// Map of the jobs in progress. Indexed by serialized UploadSettings proto -
// so any new upload job with e.g. different `retry_count` or different
// `upload_parameters` is accepted. Job is removed from the map once
// respective event is confirmed.
base::flat_map<std::string, std::unique_ptr<FileUploadJob>>
uploads_in_progress_ GUARDED_BY_CONTEXT(manager_sequence_checker_);
};
// Helper class associating the job to the event currently being processed.
class EventHelper {
public:
EventHelper(base::WeakPtr<FileUploadJob> job,
Priority priority,
Record record_copy,
::ash::reporting::LogUploadEvent log_upload_event);
EventHelper(const EventHelper& other) = delete;
EventHelper& operator=(const EventHelper& other) = delete;
~EventHelper();
// FileUploadJob progresses based on the last recorded state.
// Called once the job is located or created.
// Uses `scoped_reservation` to manage memory usage by data buffer.
// `done_cb_` is going to post update as the next tracking event.
void Run(const ScopedReservation& scoped_reservation,
base::OnceCallback<void(Status)> done_cb);
private:
// Complete and call `done_cb_` (with OK, if the event is accepted for
// upload, error status if not).
void Complete(Status status = Status::StatusOK());
// Repost new event if successful, then complete.
void RepostAndComplete();
// Compose and post a retry event (with decremented retry count and no
// tracker - thus initiating a new FileUploadJob).
void PostRetry() const;
SEQUENCE_CHECKER(sequence_checker_);
const base::WeakPtr<FileUploadJob> job_;
Priority priority_;
Record record_copy_;
::ash::reporting::LogUploadEvent log_upload_event_;
base::OnceCallback<void(Status)> done_cb_;
base::WeakPtrFactory<EventHelper> weak_ptr_factory_{this};
};
// Constructor populates both `settings` and `tracker`, based on `LOG_UPLOAD`
// event. When upload is going to be started, `tracker` is empty yet.
FileUploadJob(const UploadSettings& settings,
const UploadTracker& tracker,
Delegate::SmartPtr delegate);
FileUploadJob(const FileUploadJob& other) = delete;
FileUploadJob& operator=(const FileUploadJob& other) = delete;
~FileUploadJob();
// The Job activity starts with a call to `Initiate`: before that time
// `tracker_` is populated for the first time to enable continuous workflow,
// including `session_token` that must be set and identifies the external
// access on the next steps.
// Then the Job proceeds with one or more calls to `NextStep`: after every
// step `tracker_` is updated and `scoped_reservation` is used to manage
// memory usage by data buffer. Note that `session_token` might change if it
// is necessary to track the progress externally.
// After the Job finished uploading, it calls `Finalize`, setting up
// `access_parameters` or error status in `tracker_`.
// The Job can be recreated and restarted from any step based on input
// `tracker` parameter (for example, when a device is restarted, `tracker`
// is loaded from LOG_UPLOAD event).
// All 3 APIs below execute asynchronously; if is safe to call them repeatedly
// (if the job is executing an API call, the new one will be a no-op. It is
// possible (but not necessary) to provide `done_cb` callback to be called
// once finished - this option is mostly used for testing.
void Initiate(base::OnceClosure done_cb = base::DoNothing());
void NextStep(const ScopedReservation& scoped_reservation,
base::OnceClosure done_cb = base::DoNothing());
void Finalize(base::OnceClosure done_cb = base::DoNothing());
// Test-only explicit setter of the event helper.
void SetEventHelperForTest(std::unique_ptr<EventHelper> event_helper);
// Accessors.
EventHelper* event_helper() const;
const UploadSettings& settings() const;
const UploadTracker& tracker() const;
base::WeakPtr<FileUploadJob> GetWeakPtr();
private:
// The next three methods complement `Initiate`, `NextStep` and `Finalize` -
// they are invoked after delegate calls are executed on a thread pool, and
// resume execution on the Job's default task runner.
void DoneInitiate(
base::ScopedClosureRunner done,
StatusOr<std::pair<int64_t /*total*/, std::string /*session_token*/>>
result);
void DoneNextStep(
base::ScopedClosureRunner done,
StatusOr<std::pair<int64_t /*uploaded*/, std::string /*session_token*/>>
result);
void DoneFinalize(base::ScopedClosureRunner done,
StatusOr<std::string /*access_parameters*/> result);
// Creates scoped closure runner that augments `done_cb` with the ability to
// asynchronously delete the original file upon success or the failure that
// happened when `retry_count` dropped to 0.
base::ScopedClosureRunner CompletionCb(base::OnceClosure done_cb);
// Post event.
static void AddRecordToStorage(Priority priority,
Record record_copy,
base::OnceCallback<void(Status)> done_cb);
SEQUENCE_CHECKER(job_sequence_checker_);
// Delegate that performs actual actions.
const Delegate::SmartPtr delegate_;
// Job parameters matching the event.
const UploadSettings settings_;
UploadTracker tracker_ GUARDED_BY_CONTEXT(job_sequence_checker_);
// Event helper instance for event currently being processed by the job
// (null when no event is processed).
std::unique_ptr<EventHelper> event_helper_
GUARDED_BY_CONTEXT(job_sequence_checker_);
// Expiration timer of the job. Once the timer fires, the job is unregistered
// and destructed. The timer is reset every time the job is accessed.
base::RetainingOneShotTimer timer_ GUARDED_BY_CONTEXT(job_sequence_checker_);
// Weak pointer factory to be used for returning from async calls to Delegate.
// Must be the last member in the class.
base::WeakPtrFactory<FileUploadJob> weak_ptr_factory_{this};
};
} // namespace reporting
#endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_FILE_UPLOAD_JOB_H_
|