#include #include #include #include #include namespace Void::FileSystem { FileWatcher::FileWatcher(Options options) : m_options(options) { m_thread = std::thread([this] { run(); }); } FileWatcher::~FileWatcher() { { std::lock_guard lock(m_mutex); m_stop = true; } m_cv.notify_all(); if (m_thread.joinable()) { m_thread.join(); } } void FileWatcher::watch(std::filesystem::path path, Callback callback) { Entry entry; entry.callback = std::move(callback); entry.accepted = stat(path); std::lock_guard lock(m_mutex); Void::Log::debug("System.FileWatcher", "watching '{}'", path.string()); m_watches.insert_or_assign(std::move(path), std::move(entry)); } void FileWatcher::unwatch(const std::filesystem::path& path) { std::lock_guard lock(m_mutex); m_watches.erase(path); } std::size_t FileWatcher::watch_count() const { std::lock_guard lock(m_mutex); return m_watches.size(); } void FileWatcher::poll_now() { poll_round(); } FileWatcher::Signature FileWatcher::stat(const std::filesystem::path& path) { Signature sig; std::error_code ec; sig.exists = std::filesystem::exists(path, ec) && !ec; if (sig.exists) { sig.mtime = std::filesystem::last_write_time(path, ec); sig.size = std::filesystem::file_size(path, ec); if (ec) { sig = Signature{}; // treat stat failure as absent } } return sig; } void FileWatcher::poll_round() { // Collect ripe callbacks under the lock, invoke them outside it so // a callback may call watch()/unwatch() without deadlocking. std::vector> ripe; { std::lock_guard lock(m_mutex); for (auto& [path, entry] : m_watches) { const Signature now = stat(path); if (!entry.dirty) { if (now != entry.accepted) { entry.dirty = true; entry.pending = now; entry.stable_polls = 1; } continue; } if (now != entry.pending) { // Still changing — restart the stability count. entry.pending = now; entry.stable_polls = 1; continue; } if (++entry.stable_polls >= m_options.debounce_polls) { entry.accepted = now; entry.dirty = false; entry.stable_polls = 0; ripe.emplace_back(entry.callback, Event{path, now.exists}); } } } for (auto& [callback, event] : ripe) { Void::Log::debug("System.FileWatcher", "change on '{}'", event.path.string()); if (callback) { callback(event); } } } void FileWatcher::run() { // Wait first, poll after: nothing is watched at startup, and an // eager first round would race callers that add watches right // after construction. std::unique_lock lock(m_mutex); while (!m_stop) { if (m_cv.wait_for(lock, m_options.poll_interval, [this] { return m_stop; })) { return; } lock.unlock(); poll_round(); lock.lock(); } } } // namespace Void::FileSystem