chromium/components/reporting/util/task_runner_context.h

// Copyright 2020 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_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_
#define COMPONENTS_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_

#include <utility>

#include "base/check.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"

namespace reporting {

// This class defines context for multiple actions executed on a sequenced task
// runner with the ability to make asynchronous calls to other threads and
// resuming sequenced execution by calling |Schedule| or |ScheduleAfter|.
// Multiple actions can be scheduled at once; they will be executed on the same
// sequenced task runner. Ends execution and self-destructs when one of the
// actions calls |Response| (all previously scheduled actions must be completed
// or cancelled by then, otherwise they will crash).
//
// Code snippet:
//
// Declaration:
// class SeriesOfActionsContext {
//    public:
//     SeriesOfActionsContext(
//         ...,
//         base::OnceCallback<void(...)> callback,
//         scoped_refptr<base::SequencedTaskRunner> task_runner)
//         : TaskRunnerContext<...>(std::move(callback),
//                                  std::move(task_runner)) {}
//
//    private:
//     // Context can only be deleted by calling Response method.
//     ~SeriesOfActionsContext() override = default;
//
//     void Action1(...) {
//       ...
//       if (...) {
//         Response(...);
//         return;
//       }
//       Schedule(&SeriesOfActionsContext::Action2,
//                base::Unretained(this),
//                ...);
//       ...
//       ScheduleAfter(delay,
//                     &SeriesOfActionsContext::Action3,
//                     base::Unretained(this),
//                     ...);
//     }
//
//     void OnStart() override { Action1(...); }
//   };
//
// Usage:
//   Start<SeriesOfActionsContext>(
//       ...,
//       returning_callback,
//       base::SequencedTaskRunner::GetCurrentDefault());
//
template <typename ResponseType>
class TaskRunnerContext {};

// Constructs the context and starts execution on the assigned sequential task
// runner. Can be called from any thread to schedule the first action in the
// sequence.
template <typename ContextType /* derived from TaskRunnerContext*/,
          class... Args>
void Start(Args&&... args) {}

}  // namespace reporting

#endif  // COMPONENTS_REPORTING_UTIL_TASK_RUNNER_CONTEXT_H_