xref: /aosp_15_r20/external/cronet/net/disk_cache/backend_cleanup_tracker.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2017 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 NET_DISK_CACHE_BACKEND_CLEANUP_TRACKER_H_
6 #define NET_DISK_CACHE_BACKEND_CLEANUP_TRACKER_H_
7 
8 #include <utility>
9 #include <vector>
10 
11 #include "base/files/file_path.h"
12 #include "base/functional/callback.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/sequence_checker.h"
15 #include "net/base/net_export.h"
16 
17 namespace base {
18 class SequencedTaskRunner;
19 }  // namespace base
20 
21 namespace disk_cache {
22 
23 // Internal helper used to sequence cleanup and reuse of cache directories.
24 // One of these is created before each backend, and is kept alive till both
25 // the backend is destroyed and all of its work is done by its refcount,
26 // which keeps track of outstanding work. That refcount is expected to only be
27 // updated from the I/O thread or its equivalent.
28 class NET_EXPORT_PRIVATE BackendCleanupTracker
29     : public base::RefCounted<BackendCleanupTracker> {
30  public:
31   // Either returns a fresh cleanup tracker for |path| if none exists, or
32   // will eventually post |retry_closure| to the calling thread,
33   // and return null.
34   static scoped_refptr<BackendCleanupTracker> TryCreate(
35       const base::FilePath& path,
36       base::OnceClosure retry_closure);
37 
38   BackendCleanupTracker(const BackendCleanupTracker&) = delete;
39   BackendCleanupTracker& operator=(const BackendCleanupTracker&) = delete;
40 
41   // Register a callback to be posted after all the work of associated
42   // context is complete (which will result in destruction of this context).
43   // Should only be called by owner, on its I/O-thread-like execution context,
44   // and will in turn eventually post |cb| there.
45   void AddPostCleanupCallback(base::OnceClosure cb);
46 
47  private:
48   friend class base::RefCounted<BackendCleanupTracker>;
49   explicit BackendCleanupTracker(const base::FilePath& path);
50   ~BackendCleanupTracker();
51 
52   void AddPostCleanupCallbackImpl(base::OnceClosure cb);
53 
54   base::FilePath path_;
55 
56   // Since it's possible that a different thread may want to create a
57   // cache for a reused path, we keep track of runners contexts of
58   // post-cleanup callbacks.
59   std::vector<
60       std::pair<scoped_refptr<base::SequencedTaskRunner>, base::OnceClosure>>
61       post_cleanup_cbs_;
62 
63   // We expect only TryMakeContext to be multithreaded, everything
64   // else should be sequenced.
65   SEQUENCE_CHECKER(seq_checker_);
66 };
67 
68 }  // namespace disk_cache
69 
70 #endif  // NET_DISK_CACHE_BACKEND_CLEANUP_TRACKER_H_
71