xref: /aosp_15_r20/external/cronet/base/files/file_path_watcher.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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 // This module provides a way to monitor a file or directory for changes.
6 
7 #ifndef BASE_FILES_FILE_PATH_WATCHER_H_
8 #define BASE_FILES_FILE_PATH_WATCHER_H_
9 
10 #include <memory>
11 #include <optional>
12 #include <string>
13 #include <utility>
14 
15 #include "base/base_export.h"
16 #include "base/containers/enum_set.h"
17 #include "base/files/file_path.h"
18 #include "base/functional/callback_forward.h"
19 #include "base/memory/scoped_refptr.h"
20 #include "base/sequence_checker.h"
21 #include "base/task/sequenced_task_runner.h"
22 #include "build/build_config.h"
23 
24 namespace base {
25 
26 // This class lets you register interest in changes on a FilePath.
27 // The callback will get called whenever the file or directory referenced by the
28 // FilePath is changed, including created or deleted. Due to limitations in the
29 // underlying OS APIs, FilePathWatcher has slightly different semantics on OS X
30 // than on Windows or Linux. FilePathWatcher on Linux and Windows will detect
31 // modifications to files in a watched directory. FilePathWatcher on Mac will
32 // detect the creation and deletion of files in a watched directory, but will
33 // not detect modifications to those files. See file_path_watcher_kqueue.cc for
34 // details.
35 //
36 // Must be destroyed on the sequence that invokes Watch().
37 class BASE_EXPORT FilePathWatcher {
38  public:
39   // Type of change which occurred on the affected. Note that this may differ
40   // from the watched path, e.g. in the case of recursive watches.
41   enum class ChangeType {
42     kUnsupported,  // The implementation does not support change types.
43     kCreated,
44     kDeleted,
45     kModified,  // Includes modifications to either file contents or attributes.
46     kMoved
47   };
48 
49   // Path type of the affected path. Note that this may differ from the watched
50   // path, e.g. in the case of recursive watches.
51   enum class FilePathType {
52     kUnknown,  // The implementation could not determine the path type or does
53                // not support path types.
54     kDirectory,
55     kFile,
56   };
57 
58   // Information about the file system change. This information should be as
59   // specific as the underlying platform allows. For example, when watching
60   // directory foo/, creating file foo/bar.txt should be reported as a change
61   // with a `kCreated` change type and a `kFile` path type rather than as a
62   // modification to directory foo/. Due to limitations on some platforms, this
63   // is not always possible. Callers should treat this information a strong
64   // hint, but still be capable of handling events where this information is not
65   // known given the limitations on some platforms.
66   struct ChangeInfo {
67     FilePathType file_path_type = FilePathType::kUnknown;
68     ChangeType change_type = ChangeType::kUnsupported;
69     // Can be used to associate related events. For example, renaming a file may
70     // trigger separate "moved from" and "moved to" events with the same
71     // `cookie` value.
72     //
73     // TODO(https://crbug.com/1425601): This is currently only used to associate
74     // `kMoved` events, and requires all consumers to implement the same logic
75     // to coalesce these events. Consider upstreaming this event coalesing logic
76     // to the platform-specific implementations and then replacing `cookie` with
77     // the file path that the file was moved from, if this is known.
78     std::optional<uint32_t> cookie;
79   };
80 
81   // TODO(https://crbug.com/1425601): Rename this now that this class declares
82   // other types of Types.
83   enum class Type {
84     // Indicates that the watcher should watch the given path and its
85     // ancestors for changes. If the path does not exist, its ancestors will
86     // be watched in anticipation of it appearing later. If the path names a
87     // directory, changes within the directory are not watched.
88     kNonRecursive,
89 
90     // Indicates that the watcher should watch the given path, its ancestors,
91     // and its descendants for changes. If the path names a directory, changes
92     // within the directory are watched.
93     kRecursive,
94 
95 #if BUILDFLAG(IS_APPLE)
96     // Indicates that the watcher should watch the given path only (neither
97     // ancestors nor descendants). The watch fails if the path does not exist.
98     kTrivial,
99 #endif  // BUILDFLAG(IS_APPLE)
100   };
101 
102   // WatchOptions are a generalization of |Type|. They are used in the new
103   // PlatformDelegate::WatchWithOptions.
104   struct WatchOptions {
105     Type type = Type::kNonRecursive;
106 
107 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
108     BUILDFLAG(IS_FUCHSIA)
109     // The callback will return the full path to a changed file instead of
110     // the watched path supplied as |path| when Watch is called.
111     // So the full path can be different from the watched path when a folder is
112     // watched. In case of any error, it behaves as the original Watch.
113     bool report_modified_path = false;
114 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
115         // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
116   };
117 
118   // Callback type for Watch(). |path| points to the file that was updated,
119   // and |error| is true if the platform specific code detected an error. In
120   // that case, the callback won't be invoked again.
121   using Callback =
122       base::RepeatingCallback<void(const FilePath& path, bool error)>;
123   // Same as above, but includes more information about the change, if known.
124   using CallbackWithChangeInfo = RepeatingCallback<
125       void(const ChangeInfo&, const FilePath& path, bool error)>;
126 
127   // Used internally to encapsulate different members on different platforms.
128   class PlatformDelegate {
129    public:
130     using Type = FilePathWatcher::Type;
131     using WatchOptions = FilePathWatcher::WatchOptions;
132 
133     PlatformDelegate();
134     PlatformDelegate(const PlatformDelegate&) = delete;
135     PlatformDelegate& operator=(const PlatformDelegate&) = delete;
136     virtual ~PlatformDelegate();
137 
138     // Start watching for the given |path| and notify |delegate| about changes.
139     [[nodiscard]] virtual bool Watch(const FilePath& path,
140                                      Type type,
141                                      const Callback& callback) = 0;
142 
143     // A more general API which can deal with multiple options.
144     [[nodiscard]] virtual bool WatchWithOptions(const FilePath& path,
145                                                 const WatchOptions& options,
146                                                 const Callback& callback);
147 
148     // Watches the specified `path` according to the given `options`.
149     // `callback` is invoked for each subsequent modification, with a
150     // `ChangeInfo` populated with the fields supported by the implementation.
151     [[nodiscard]] virtual bool WatchWithChangeInfo(
152         const FilePath& path,
153         const WatchOptions& options,
154         const CallbackWithChangeInfo& callback);
155 
156     // Stop watching. This is called from FilePathWatcher's dtor in order to
157     // allow to shut down properly while the object is still alive.
158     virtual void Cancel() = 0;
159 
160    protected:
161     friend class FilePathWatcher;
162 
task_runner()163     scoped_refptr<SequencedTaskRunner> task_runner() const {
164       return task_runner_;
165     }
166 
set_task_runner(scoped_refptr<SequencedTaskRunner> runner)167     void set_task_runner(scoped_refptr<SequencedTaskRunner> runner) {
168       task_runner_ = std::move(runner);
169     }
170 
171     // Must be called before the PlatformDelegate is deleted.
set_cancelled()172     void set_cancelled() { cancelled_ = true; }
173 
is_cancelled()174     bool is_cancelled() const { return cancelled_; }
175 
176    private:
177     scoped_refptr<SequencedTaskRunner> task_runner_;
178     bool cancelled_ = false;
179   };
180 
181   FilePathWatcher();
182   FilePathWatcher(const FilePathWatcher&) = delete;
183   FilePathWatcher& operator=(const FilePathWatcher&) = delete;
184   ~FilePathWatcher();
185 
186   // Returns true if the platform and OS version support recursive watches.
187   static bool RecursiveWatchAvailable();
188 
189 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
190   // Whether there are outstanding inotify watches.
191   static bool HasWatchesForTest();
192 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
193 
194   // Starts watching |path| (and its descendants if |type| is kRecursive) for
195   // changes. |callback| will be run on the caller's sequence to report such
196   // changes. Returns true if the watch was started successfully and |callback|
197   // may one day be run, or false in case of failure (e.g., a recursive watch on
198   // platforms that do not support such).
199   //
200   // On POSIX, this must be called from a thread that supports
201   // FileDescriptorWatcher.
202   bool Watch(const FilePath& path, Type type, const Callback& callback);
203 
204   // A more general API which can deal with multiple options.
205   bool WatchWithOptions(const FilePath& path,
206                         const WatchOptions& options,
207                         const Callback& callback);
208 
209   // Same as above, but `callback` includes more information about the change,
210   // if known. On platforms for which change information is not supported,
211   // `callback` is called with a dummy `ChangeInfo`.
212   bool WatchWithChangeInfo(const FilePath& path,
213                            const WatchOptions& options,
214                            const CallbackWithChangeInfo& callback);
215 
216  private:
217   explicit FilePathWatcher(std::unique_ptr<PlatformDelegate> delegate);
218 
219   std::unique_ptr<PlatformDelegate> impl_;
220 
221   SEQUENCE_CHECKER(sequence_checker_);
222 };
223 
224 }  // namespace base
225 
226 #endif  // BASE_FILES_FILE_PATH_WATCHER_H_
227