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