1 // Copyright 2018 The Chromium Authors. All rights reserved.
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 SERVICES_NETWORK_KEEPALIVE_STATISTICS_RECORDER_H_
6 #define SERVICES_NETWORK_KEEPALIVE_STATISTICS_RECORDER_H_
7 
8 #include <map>
9 
10 #include "base/component_export.h"
11 #include "base/macros.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/unguessable_token.h"
15 
16 namespace network {
17 
18 // KeepaliveStatisticsRecorder keeps tracks of the number of inflight requests
19 // with "keepalive" set and records UMA histograms.
COMPONENT_EXPORT(NETWORK_SERVICE)20 class COMPONENT_EXPORT(NETWORK_SERVICE) KeepaliveStatisticsRecorder
21     : public base::SupportsWeakPtr<KeepaliveStatisticsRecorder> {
22  public:
23   struct PerTopLevelFrameStats {
24     int num_registrations = 1;
25     int num_inflight_requests = 0;
26     int peak_inflight_requests = 0;
27     int total_request_size = 0;
28   };
29 
30   KeepaliveStatisticsRecorder();
31   ~KeepaliveStatisticsRecorder();
32 
33   // Registers / Unregisters |top_level_frame| to this object.
34   // There can be multiple Register / Unregister calls with the same
35   // |top_level_frame|, and this object thinks a an entry for |top_level_frame|
36   // is gone when the number of Register calls with |top_level_frame| equals to
37   // the number of Unregister calls with |token|.
38   void Register(const base::UnguessableToken& top_level_frame_id);
39   void Unregister(const base::UnguessableToken& top_level_frame_id);
40 
41   // Called when a request with keepalive set starts.
42   void OnLoadStarted(const base::UnguessableToken& top_level_frame_id,
43                      int request_size);
44   // Called when a request with keepalive set finishes.
45   void OnLoadFinished(const base::UnguessableToken& top_level_frame_id,
46                       int request_size);
47 
48   const std::map<base::UnguessableToken, PerTopLevelFrameStats>&
49   per_top_level_frame_records() const {
50     return per_top_level_frame_records_;
51   }
52   int NumInflightRequestsPerTopLevelFrame(
53       const base::UnguessableToken& top_level_frame_id) const;
54   int GetTotalRequestSizePerTopLevelFrame(
55       const base::UnguessableToken& top_level_frame_id) const;
56   int num_inflight_requests() const { return num_inflight_requests_; }
57   int peak_inflight_requests() const { return peak_inflight_requests_; }
58 
59  private:
60   std::map<base::UnguessableToken, PerTopLevelFrameStats>
61       per_top_level_frame_records_;
62   int num_inflight_requests_ = 0;
63   int peak_inflight_requests_ = 0;
64 
65   DISALLOW_COPY_AND_ASSIGN(KeepaliveStatisticsRecorder);
66 };
67 
68 }  // namespace network
69 
70 #endif  // SERVICES_NETWORK_KEEPALIVE_STATISTICS_RECORDER_H_
71