• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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_STRUCTURED_METRICS_CLIENT_H_
6 #define COMPONENTS_METRICS_STRUCTURED_STRUCTURED_METRICS_CLIENT_H_
7 
8 #include "base/memory/raw_ptr.h"
9 #include "base/no_destructor.h"
10 
11 #include "components/metrics/structured/delegating_events_processor.h"
12 #include "components/metrics/structured/event.h"
13 #include "components/metrics/structured/events_processor_interface.h"
14 
15 namespace metrics::structured {
16 
17 // Singleton to interact with StructuredMetrics.
18 //
19 // It allows a delegate to be set to control the recording logic as different
20 // embedders have different requirements (ie ash vs lacros).
21 class StructuredMetricsClient {
22  public:
23   class RecordingDelegate {
24    public:
25     virtual ~RecordingDelegate() = default;
26 
27     // Return true when the delegate is ready to write events.
28     virtual bool IsReadyToRecord() const = 0;
29 
30     // Recording logic.
31     virtual void RecordEvent(Event&& event) = 0;
32   };
33 
34   StructuredMetricsClient(const StructuredMetricsClient& client) = delete;
35   StructuredMetricsClient& operator=(const StructuredMetricsClient& client) =
36       delete;
37 
38   // Provides access to global StructuredMetricsClient instance to record
39   // metrics. This is typically used in the codegen.
40   static StructuredMetricsClient* Get();
41 
42   // Forwards to |delegate_|. If no delegate has been set, then no-op.
43   void Record(Event&& event);
44 
45   // Sets the delegate for the client's recording logic. Should be called before
46   // anything else. |this| does not take ownership of |delegate| and assumes
47   // that the caller will properly manage the lifetime of delegate and call
48   // |UnsetDelegate| before |delegate| is destructed.
49   void SetDelegate(RecordingDelegate* delegate);
50   void UnsetDelegate();
51 
52  private:
53   friend class base::NoDestructor<StructuredMetricsClient>;
54 
55   StructuredMetricsClient();
56   ~StructuredMetricsClient();
57 
58   // Not owned. Assumes that the delegate's lifetime will exceed |this|.
59   raw_ptr<RecordingDelegate> delegate_ = nullptr;
60 };
61 
62 }  // namespace metrics::structured
63 
64 #endif  // COMPONENTS_METRICS_STRUCTURED_STRUCTURED_METRICS_CLIENT_H_
65