• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 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 COMPONENTS_METRICS_STRUCTURED_LIB_EVENT_BUFFER_H_
6 #define COMPONENTS_METRICS_STRUCTURED_LIB_EVENT_BUFFER_H_
7 
8 #include <concepts>
9 #include <type_traits>
10 
11 #include "base/files/file_path.h"
12 #include "base/functional/callback.h"
13 #include "base/time/time.h"
14 #include "base/types/expected.h"
15 #include "components/metrics/structured/lib/resource_info.h"
16 #include "third_party/protobuf/src/google/protobuf/message_lite.h"
17 
18 namespace metrics::structured {
19 // The result of adding an event to a buffer.
20 enum class Result {
21   // Event was added successfully.
22   kOk = 0,
23   // Event was added but another might not fit.
24   kShouldFlush = 1,
25   // Event was not added. Must flush now.
26   kFull = 2,
27   // Any error that occurred.
28   kError = 3,
29 };
30 
31 // Errors of flushing a buffer to disk.
32 enum FlushError {
33   kQuotaExceeded = 1,
34   kWriteError = 2,
35   kDiskFull = 3,
36   kSerializationFailed = 4,
37 };
38 
39 // Represents a flushed buffer.
40 struct FlushedKey {
41   // The size of the file flushed.
42   int64_t size;
43   // Path of the file.
44   base::FilePath path;
45   // When the flushed file was created.
46   base::Time creation_time;
47 };
48 
49 using FlushedCallback =
50     base::OnceCallback<void(base::expected<FlushedKey, FlushError>)>;
51 
52 // Abstraction for how in-memory events are managed on device.
53 template <typename T>
requires(std::derived_from<T,google::protobuf::MessageLite>)54   requires(std::derived_from<T, google::protobuf::MessageLite>)
55 class EventBuffer {
56  public:
57   explicit EventBuffer(ResourceInfo info) : resource_info_(info) {}
58 
59   virtual ~EventBuffer() = default;
60 
61   // Adds an event to |this| buffer.
62   virtual Result AddEvent(T event) = 0;
63 
64   // Clears the content of the buffer.
65   virtual void Purge() = 0;
66 
67   // The number of events stored in the buffer.
68   virtual uint64_t Size() = 0;
69 
70   // Serialize the contents of |this|.
71   virtual google::protobuf::RepeatedPtrField<T> Serialize() = 0;
72 
73   // Flushes the buffer to |path|, once the flush is complete |callback| is
74   // executed.
75   virtual void Flush(const base::FilePath& path, FlushedCallback callback) = 0;
76 
77   const ResourceInfo& resource_info() const { return resource_info_; }
78 
79  protected:
80   ResourceInfo resource_info_;
81 };
82 
83 }  // namespace metrics::structured
84 
85 #endif  // COMPONENTS_METRICS_STRUCTURED_LIB_EVENT_BUFFER_H_
86