1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef mozilla_MemoryTelemetry_h
8 #define mozilla_MemoryTelemetry_h
9 
10 #include "mozilla/TimeStamp.h"
11 #include "mozilla/Result.h"
12 #include "nsIObserver.h"
13 #include "nsITimer.h"
14 #include "nsTArray.h"
15 #include "nsWeakReference.h"
16 
17 #include <functional>
18 
19 class nsIEventTarget;
20 
21 namespace mozilla {
22 
23 namespace ipc {
24 enum class ResponseRejectReason;
25 }
26 
27 /**
28  * Periodically gathers memory usage metrics after cycle collection, and
29  * populates telemetry histograms with their values.
30  */
31 class MemoryTelemetry final : public nsIObserver,
32                               public nsSupportsWeakReference {
33  public:
34   NS_DECL_ISUPPORTS
35   NS_DECL_NSIOBSERVER
36 
37   static MemoryTelemetry& Get();
38 
39   nsresult GatherReports(
40       const std::function<void()>& aCompletionCallback = nullptr);
41 
42   void GetUniqueSetSize(std::function<void(const int64_t&)>&& aCallback);
43 
44   /**
45    * Does expensive initialization, which should happen only after startup has
46    * completed, and the event loop is idle.
47    */
48   nsresult DelayedInit();
49 
50   nsresult Shutdown();
51 
52  private:
53   MemoryTelemetry();
54 
55   ~MemoryTelemetry() = default;
56 
57   void Init();
58 
59   static Result<uint32_t, nsresult> GetOpenTabsCount();
60 
61   void GatherTotalMemory();
62   nsresult FinishGatheringTotalMemory(int64_t aTotalMemory,
63                                       const nsTArray<int64_t>& aChildSizes);
64 
65   nsCOMPtr<nsIEventTarget> mThreadPool;
66 
67   bool mGatheringTotalMemory = false;
68 
69   TimeStamp mLastPoll{};
70 };
71 
72 }  // namespace mozilla
73 
74 #endif  // defined mozilla_MemoryTelemetry_h
75