xref: /aosp_15_r20/external/cronet/base/metrics/histogram_delta_serialization.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 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_METRICS_HISTOGRAM_DELTA_SERIALIZATION_H_
6 #define BASE_METRICS_HISTOGRAM_DELTA_SERIALIZATION_H_
7 
8 #include <memory>
9 #include <string>
10 #include <vector>
11 
12 #include "base/base_export.h"
13 #include "base/memory/raw_ptr.h"
14 #include "base/metrics/histogram_flattener.h"
15 #include "base/metrics/histogram_snapshot_manager.h"
16 #include "base/threading/thread_checker.h"
17 
18 namespace base {
19 
20 class HistogramBase;
21 
22 // Serializes and restores histograms deltas.
23 class BASE_EXPORT HistogramDeltaSerialization : public HistogramFlattener {
24  public:
25   // |caller_name| is string used in histograms for counting inconsistencies.
26   explicit HistogramDeltaSerialization(const std::string& caller_name);
27 
28   HistogramDeltaSerialization(const HistogramDeltaSerialization&) = delete;
29   HistogramDeltaSerialization& operator=(const HistogramDeltaSerialization&) =
30       delete;
31 
32   ~HistogramDeltaSerialization() override;
33 
34   // Computes deltas in histogram bucket counts relative to the previous call to
35   // this method. Stores the deltas in serialized form into |serialized_deltas|.
36   // If |serialized_deltas| is null, no data is serialized, though the next call
37   // will compute the deltas relative to this one. Setting |include_persistent|
38   // will include histograms held in persistent memory (and thus may be reported
39   // elsewhere); otherwise only histograms local to this process are serialized.
40   void PrepareAndSerializeDeltas(std::vector<std::string>* serialized_deltas,
41                                  bool include_persistent);
42 
43   // Deserialize deltas and add samples to corresponding histograms, creating
44   // them if necessary. Silently ignores errors in |serialized_deltas|.
45   static void DeserializeAndAddSamples(
46       const std::vector<std::string>& serialized_deltas);
47 
48  private:
49   // HistogramFlattener implementation.
50   void RecordDelta(const HistogramBase& histogram,
51                    const HistogramSamples& snapshot) override;
52 
53   ThreadChecker thread_checker_;
54 
55   // Calculates deltas in histogram counters.
56   HistogramSnapshotManager histogram_snapshot_manager_;
57 
58   // Output buffer for serialized deltas.
59   raw_ptr<std::vector<std::string>> serialized_deltas_;
60 };
61 
62 }  // namespace base
63 
64 #endif  // BASE_METRICS_HISTOGRAM_DELTA_SERIALIZATION_H_
65