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