#pragma once #include #include #include #include #include #include #include #include namespace Void::FileSystem { /// Polling file watcher with debounce. /// /// One background thread polls every watched path's (mtime, size) at /// `poll_interval`. After a change is observed, the callback fires only /// once the metadata has been stable for `debounce_polls` consecutive /// polls — this avoids reacting to half-written files (e.g. a .so or /// config file still being copied). /// /// Callbacks run on the watcher thread; keep them short or hand off. /// A path that disappears is reported once with `exists == false` and /// again when it reappears (after debounce). struct FileWatcherOptions { std::chrono::milliseconds poll_interval{500}; int debounce_polls = 2; }; class FileWatcher { public: using Options = FileWatcherOptions; struct Event { std::filesystem::path path; bool exists; // false when the file vanished }; using Callback = std::function; explicit FileWatcher(Options options = {}); ~FileWatcher(); FileWatcher(const FileWatcher&) = delete; FileWatcher& operator=(const FileWatcher&) = delete; FileWatcher(FileWatcher&&) = delete; FileWatcher& operator=(FileWatcher&&) = delete; /// Watch a path. Replaces any existing callback for it. /// Thread-safe. void watch(std::filesystem::path path, Callback callback); /// Stop watching a path. Thread-safe. void unwatch(const std::filesystem::path& path); [[nodiscard]] std::size_t watch_count() const; /// Run one poll round immediately (test hook; also usable to /// force a check without waiting out the interval). void poll_now(); private: struct Signature { bool exists = false; std::filesystem::file_time_type mtime{}; std::uintmax_t size = 0; bool operator==(const Signature&) const = default; }; struct Entry { Callback callback; Signature accepted; // last state we reported (or initial) Signature pending; // candidate new state being debounced int stable_polls = 0; bool dirty = false; // pending differs from accepted }; static Signature stat(const std::filesystem::path& path); void poll_round(); void run(); Options m_options; mutable std::mutex m_mutex; std::condition_variable m_cv; std::map m_watches; bool m_stop = false; std::thread m_thread; }; } // namespace Void::FileSystem