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_HTTP_CACHE_DATA_COUNTER_H_
6 #define SERVICES_NETWORK_HTTP_CACHE_DATA_COUNTER_H_
7 
8 #include <memory>
9 
10 #include "base/callback.h"
11 #include "base/component_export.h"
12 #include "base/macros.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/time/time.h"
15 
16 namespace disk_cache {
17 class Backend;
18 }
19 
20 namespace net {
21 class URLRequestContext;
22 }
23 
24 namespace network {
25 
26 // Helper to count data in HTTP cache.
27 // Export is for testing only.
COMPONENT_EXPORT(NETWORK_SERVICE)28 class COMPONENT_EXPORT(NETWORK_SERVICE) HttpCacheDataCounter {
29  public:
30   using HttpCacheDataCounterCallback = base::OnceCallback<
31       void(HttpCacheDataCounter*, bool upper_bound, int64_t size_or_error)>;
32 
33   // Computes the amount of disk space taken up by entries last used between
34   // [start_time, end_time), and return it, or error.  Note that there may be
35   // some approximation with respect to both bytes and dates.
36   //
37   // Furthermore, if there is no efficient way of computing this information,
38   // a very loose upper bound (e.g. total disk space used by the cache) may be
39   // returned; in that case |upper_bound| will be set to true.
40   //
41   // Once complete, invokes |callback|, passing |this| and result.
42   //
43   // If either |this| or |url_request_context| get destroyed, |callback|
44   // will not be invoked.
45   static std::unique_ptr<HttpCacheDataCounter> CreateAndStart(
46       net::URLRequestContext* url_request_context,
47       base::Time start_time,
48       base::Time end_time,
49       HttpCacheDataCounterCallback callback);
50 
51   ~HttpCacheDataCounter();
52 
53  private:
54   HttpCacheDataCounter(base::Time start_time,
55                        base::Time end_time,
56                        HttpCacheDataCounterCallback callback);
57 
58   void GotBackend(std::unique_ptr<disk_cache::Backend*> backend,
59                   int error_code);
60   void PostResult(bool is_upper_limit, int64_t result_or_error);
61 
62   base::WeakPtr<HttpCacheDataCounter> GetWeakPtr() {
63     return weak_factory_.GetWeakPtr();
64   }
65 
66   base::Time start_time_;
67   base::Time end_time_;
68   HttpCacheDataCounterCallback callback_;
69 
70   base::WeakPtrFactory<HttpCacheDataCounter> weak_factory_{this};
71 
72   DISALLOW_COPY_AND_ASSIGN(HttpCacheDataCounter);
73 };
74 
75 }  // namespace network
76 
77 #endif  // SERVICES_NETWORK_HTTP_CACHE_DATA_COUNTER_H_
78