xref: /aosp_15_r20/external/cronet/base/trace_event/memory_dump_scheduler.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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.
4 
5 #ifndef BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_
6 #define BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_
7 
8 #include <stdint.h>
9 
10 #include <vector>
11 
12 #include "base/base_export.h"
13 #include "base/functional/callback.h"
14 #include "base/trace_event/memory_dump_request_args.h"
15 
16 namespace base {
17 class SequencedTaskRunner;
18 
19 namespace trace_event {
20 
21 // Schedules global dump requests based on the triggers added. The methods of
22 // this class are NOT thread safe and the client has to take care of invoking
23 // all the methods of the class safely.
24 class BASE_EXPORT MemoryDumpScheduler {
25  public:
26   using PeriodicCallback = RepeatingCallback<void(MemoryDumpLevelOfDetail)>;
27 
28   // Passed to Start().
29   struct BASE_EXPORT Config {
30     struct Trigger {
31       MemoryDumpLevelOfDetail level_of_detail;
32       uint32_t period_ms;
33     };
34 
35     Config();
36     Config(const Config&);
37     ~Config();
38 
39     std::vector<Trigger> triggers;
40     PeriodicCallback callback;
41   };
42 
43   static MemoryDumpScheduler* GetInstance();
44 
45   MemoryDumpScheduler(const MemoryDumpScheduler&) = delete;
46   MemoryDumpScheduler& operator=(const MemoryDumpScheduler&) = delete;
47 
48   void Start(Config, scoped_refptr<SequencedTaskRunner> task_runner);
49   void Stop();
is_enabled_for_testing()50   bool is_enabled_for_testing() const { return bool(task_runner_); }
51 
52  private:
53   friend class MemoryDumpSchedulerTest;
54   MemoryDumpScheduler();
55   ~MemoryDumpScheduler();
56 
57   void StartInternal(Config);
58   void StopInternal();
59   void Tick(uint32_t expected_generation);
60 
61   // Accessed only by the public methods (never from the task runner itself).
62   scoped_refptr<SequencedTaskRunner> task_runner_;
63 
64   // These fields instead are only accessed from within the task runner.
65   uint32_t period_ms_ = 0;  // 0 == disabled.
66   // Used to invalidate outstanding tasks after Stop().
67   uint32_t generation_ = 0;
68   uint32_t tick_count_;
69   uint32_t light_dump_rate_;
70   uint32_t heavy_dump_rate_;
71   PeriodicCallback callback_;
72 };
73 
74 }  // namespace trace_event
75 }  // namespace base
76 
77 #endif  // BASE_TRACE_EVENT_MEMORY_DUMP_SCHEDULER_H_
78