diff --git a/docs/targets.md b/docs/targets.md index 3f037f7..c1fc13e 100644 --- a/docs/targets.md +++ b/docs/targets.md @@ -126,6 +126,9 @@ Notes from the runtime run: there, and runtime verification under Wine is still pending. - Tests that only exercise POSIX APIs carry `// @requires-posix` and are skipped on Windows; the POSIX process helper is not built there. +- `DirectoryWatcher` has a Windows backend based on + `ReadDirectoryChangesW` (recursive handle, events delivered by a watcher + thread); `IO`'s native backend is still Linux-only (IOCP is a separate task). - `Observability` links after replacing the namespace-scope `inline thread_local` hook stack with a function-local `thread_local` accessor (MinGW emitted duplicate TLS init functions). diff --git a/src/System/DirectoryWatcher.cpp b/src/System/DirectoryWatcher.cpp index e59bece..7c34335 100644 --- a/src/System/DirectoryWatcher.cpp +++ b/src/System/DirectoryWatcher.cpp @@ -19,6 +19,19 @@ #include #include #include +#elif defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +#include +#include +#include #endif namespace Void::FileSystem @@ -776,6 +789,334 @@ int DirectoryWatcher::native_handle() const noexcept return impl_ ? impl_->inotify_fd.get() : -1; } +#elif defined(_WIN32) + +namespace +{ + +constexpr DWORD kNotifyFilter = + FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | + FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | + FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION; +constexpr std::size_t kWatchBufferBytes = 64U * 1024U; + +} // namespace + +// ReadDirectoryChangesW is blocking on a dedicated thread; poll() drains the +// queue and waits on a condition variable. This avoids the overlapped-event +// races and is portable across Windows and Wine. +struct DirectoryWatcher::Impl { + HANDLE directory{INVALID_HANDLE_VALUE}; + std::filesystem::path root{}; + DirectoryWatcherOptions options{}; + + std::thread worker{}; + std::atomic stop{false}; + std::atomic rescan_requested{false}; + + mutable std::mutex mutex{}; + std::condition_variable changed{}; + std::deque queue{}; + bool rescan_emitted{false}; + bool wake_requested{false}; + + ~Impl() noexcept + { + stop.store(true); + if (worker.joinable()) { + if (directory != INVALID_HANDLE_VALUE) { + (void)::CancelIoEx(directory, nullptr); + } + worker.join(); + } + if (directory != INVALID_HANDLE_VALUE) { + (void)::CloseHandle(directory); + } + } + + [[nodiscard]] bool should_ignore(const std::filesystem::path& path, + const bool is_directory) const + { + if (options.ignore) { + return options.ignore(path, is_directory); + } + return false; + } + + void push_event_locked(DirectoryEvent event) + { + if (event.kind == DirectoryEventKind::RescanRequired) { + if (rescan_emitted) { + return; + } + rescan_emitted = true; + queue.push_back(std::move(event)); + return; + } + if (queue.size() >= options.max_queued_events) { + if (!rescan_emitted) { + rescan_emitted = true; + queue.push_back(DirectoryEvent{ + .kind = DirectoryEventKind::RescanRequired, + .path = root, + .old_path = {}, + .is_directory = true, + .detail = "DirectoryWatcher event queue full", + }); + } + return; + } + queue.push_back(std::move(event)); + } + + void push_filtered_locked(DirectoryEvent event) + { + if (should_ignore(event.path, event.is_directory)) { + return; + } + push_event_locked(std::move(event)); + } + + [[nodiscard]] std::vector drain_locked() + { + std::vector out; + out.reserve(queue.size()); + while (!queue.empty()) { + out.push_back(std::move(queue.front())); + queue.pop_front(); + } + return out; + } + + void parse_buffer_locked(const std::byte* data, const std::size_t size) + { + std::optional renamed_from; + bool renamed_from_is_dir = false; + std::size_t offset = 0; + while (offset + sizeof(FILE_NOTIFY_INFORMATION) <= size) { + const auto* info = reinterpret_cast( + data + offset); + const std::wstring name{info->FileName, + info->FileNameLength / sizeof(WCHAR)}; + const std::filesystem::path path = root / std::filesystem::path{name}; + std::error_code ec; + const bool is_directory = std::filesystem::is_directory(path, ec); + + switch (info->Action) { + case FILE_ACTION_ADDED: + push_filtered_locked( + DirectoryEvent{.kind = DirectoryEventKind::Created, + .path = path, + .is_directory = is_directory}); + break; + case FILE_ACTION_REMOVED: + push_filtered_locked( + DirectoryEvent{.kind = DirectoryEventKind::Deleted, + .path = path, + .is_directory = is_directory}); + break; + case FILE_ACTION_MODIFIED: + push_filtered_locked( + DirectoryEvent{.kind = DirectoryEventKind::Modified, + .path = path, + .is_directory = is_directory}); + break; + case FILE_ACTION_RENAMED_OLD_NAME: + renamed_from = path; + renamed_from_is_dir = is_directory; + break; + case FILE_ACTION_RENAMED_NEW_NAME: { + DirectoryEvent event{.kind = DirectoryEventKind::Renamed, + .path = path, + .old_path = renamed_from.value_or(path), + .is_directory = is_directory || + renamed_from_is_dir}; + push_filtered_locked(std::move(event)); + renamed_from.reset(); + break; + } + default: + break; + } + if (info->NextEntryOffset == 0) { + break; + } + offset += info->NextEntryOffset; + } + } + + void run() + { + std::vector buffer(kWatchBufferBytes); + while (!stop.load(std::memory_order_acquire)) { + if (rescan_requested.exchange(false)) { + std::lock_guard lock{mutex}; + queue.clear(); + rescan_emitted = false; + } + DWORD transferred = 0; + const BOOL ok = ::ReadDirectoryChangesW( + directory, buffer.data(), static_cast(buffer.size()), + TRUE, kNotifyFilter, &transferred, nullptr, nullptr); + if (stop.load(std::memory_order_acquire)) { + break; + } + if (ok == 0) { + const DWORD error = ::GetLastError(); + if (error == ERROR_OPERATION_ABORTED) { + continue; + } + { + std::lock_guard lock{mutex}; + push_event_locked(DirectoryEvent{ + .kind = DirectoryEventKind::RescanRequired, + .path = root, + .old_path = {}, + .is_directory = true, + .detail = std::format( + "DirectoryWatcher read failed ({})", error), + }); + } + changed.notify_all(); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); + continue; + } + if (transferred == 0) { + continue; + } + { + std::lock_guard lock{mutex}; + parse_buffer_locked(buffer.data(), transferred); + } + changed.notify_all(); + } + } +}; + +DirectoryWatcher::DirectoryWatcher(std::unique_ptr impl) noexcept + : impl_(std::move(impl)) +{ +} + +DirectoryWatcher::~DirectoryWatcher() noexcept = default; +DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default; +DirectoryWatcher& + DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default; + +Void::Result::Result + DirectoryWatcher::create(const std::filesystem::path& root, + DirectoryWatcherOptions options) +{ + std::error_code ec; + if (!std::filesystem::is_directory(root, ec)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("FileSystem::DirectoryWatcher::create: '{}' is not a " + "directory", + root.string()))}; + } + + auto impl = std::make_unique(); + impl->root = root; + impl->options = std::move(options); + impl->directory = ::CreateFileW( + root.c_str(), FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + if (impl->directory == INVALID_HANDLE_VALUE) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::io_error, + std::format("FileSystem::DirectoryWatcher::create: cannot open " + "'{}'", + root.string()))}; + } + impl->worker = std::thread{[raw = impl.get()] { raw->run(); }}; + return DirectoryWatcher{std::move(impl)}; +} + +Void::Result::Result, Void::Result::Error> + DirectoryWatcher::poll(std::chrono::milliseconds timeout) +{ + if (!impl_) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::DirectoryWatcher::poll: moved-from watcher")}; + } + std::unique_lock lock{impl_->mutex}; + impl_->changed.wait_for( + lock, std::max(std::chrono::milliseconds{0}, timeout), [&] { + return !impl_->queue.empty() || impl_->wake_requested; + }); + impl_->wake_requested = false; + return impl_->drain_locked(); +} + +Void::Result::Result DirectoryWatcher::rescan() +{ + if (!impl_) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::DirectoryWatcher::rescan: moved-from watcher")}; + } + impl_->rescan_requested.store(true); + // Unblock the blocking ReadDirectoryChangesW; the worker re-arms and + // clears the queue on the next iteration. + (void)::CancelIoEx(impl_->directory, nullptr); + return {}; +} + +void DirectoryWatcher::wake() noexcept +{ + if (!impl_) { + return; + } + { + std::lock_guard lock{impl_->mutex}; + impl_->wake_requested = true; + } + impl_->changed.notify_all(); +} + +void DirectoryWatcher::simulate_overflow_for_test() +{ + if (!impl_) { + return; + } + { + std::lock_guard lock{impl_->mutex}; + impl_->push_event_locked(DirectoryEvent{ + .kind = DirectoryEventKind::RescanRequired, + .path = impl_->root, + .old_path = {}, + .is_directory = true, + .detail = "simulated buffer overflow", + }); + } + impl_->changed.notify_all(); +} + +const std::filesystem::path& DirectoryWatcher::root() const noexcept +{ + static const std::filesystem::path kEmpty{}; + return impl_ ? impl_->root : kEmpty; +} + +std::size_t DirectoryWatcher::watch_count() const noexcept +{ + if (!impl_) { + return 0; + } + // One recursive handle covers the whole subtree. + return impl_->directory == INVALID_HANDLE_VALUE ? 0 : 1; +} + +int DirectoryWatcher::native_handle() const noexcept +{ + return impl_ ? static_cast( + reinterpret_cast(impl_->directory)) + : -1; +} + #else struct DirectoryWatcher::Impl { diff --git a/tests/standalone/System/DirectoryWatcher.cpp b/tests/standalone/System/DirectoryWatcher.cpp index db08c85..bd9d06d 100644 --- a/tests/standalone/System/DirectoryWatcher.cpp +++ b/tests/standalone/System/DirectoryWatcher.cpp @@ -36,9 +36,6 @@ namespace Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames() { -#ifdef _WIN32 - Void::Testing::skip("DirectoryWatcher has no Windows backend (inotify-only)"); -#endif Void::FileSystem::TempDir tmp{"void_dir_watch_"}; const auto ignored_dir = tmp / ".git"; Void::Testing::require( @@ -83,7 +80,12 @@ Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames ev.kind == Void::FileSystem::DirectoryEventKind::Modified); }); Void::Testing::expect(saw_file_create_or_mod); +#ifdef _WIN32 + // One recursive ReadDirectoryChangesW handle covers the whole subtree. + Void::Testing::expect(watcher.watch_count() >= 1U); +#else Void::Testing::expect(watcher.watch_count() >= 3U); +#endif // Modify inside auto-watched nested directory Void::Testing::require( @@ -124,8 +126,17 @@ Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames Void::Testing::expect(std::any_of( post_move_events.begin(), post_move_events.end(), [&](const Void::FileSystem::DirectoryEvent& ev) { - return ev.kind == Void::FileSystem::DirectoryEventKind::Modified && - ev.path == (watcher.root() / "src/engine/entry.cpp"); + if (ev.kind != Void::FileSystem::DirectoryEventKind::Modified || + ev.path.filename() != "entry.cpp") { + return false; + } +#ifdef _WIN32 + // ReadDirectoryChangesW may report the pre-rename path for a + // modification shortly after a directory rename. + return true; +#else + return ev.path == (watcher.root() / "src/engine/entry.cpp"); +#endif })); // Directory replacement / deletion storm @@ -141,9 +152,6 @@ Void::Testing::Test directory_watcher_tracks_recursive_trees_ignores_and_renames Void::Testing::Test directory_watcher_signals_rescan_on_overflow_and_limit() { -#ifdef _WIN32 - Void::Testing::skip("DirectoryWatcher has no Windows backend (inotify-only)"); -#endif Void::FileSystem::TempDir tmp{"void_dir_ovf_"}; // 1. Simulated queue overflow emits RescanRequired and wake recovers @@ -171,12 +179,29 @@ Void::Testing::Test directory_watcher_signals_rescan_on_overflow_and_limit() Void::Testing::require(w_res.has_value()); Void::Testing::require( Void::FileSystem::ensure_directory(tmp / "extra_dir").has_value()); +#ifdef _WIN32 + // ReadDirectoryChangesW delivery can lag under load. + const auto evs = collect_events(*w_res, std::chrono::milliseconds{2000}); +#else const auto evs = collect_events(*w_res, std::chrono::milliseconds{400}); +#endif +#ifdef _WIN32 + // Windows watches recursively with a single handle, so max_watches + // cannot be exhausted; the new directory is simply reported. + Void::Testing::expect(std::any_of( + evs.begin(), evs.end(), + [](const Void::FileSystem::DirectoryEvent& ev) { + return ev.path.filename() == "extra_dir" && + ev.kind != + Void::FileSystem::DirectoryEventKind::RescanRequired; + })); +#else Void::Testing::expect(std::any_of( evs.begin(), evs.end(), [](const Void::FileSystem::DirectoryEvent& ev) { return ev.kind == Void::FileSystem::DirectoryEventKind::RescanRequired; })); +#endif } } \ No newline at end of file