649 lines
19 KiB
C++
649 lines
19 KiB
C++
#include <Void/Async/TaskScope.hpp>
|
|
#include <Void/System/AsyncWatcher.hpp>
|
|
|
|
#include <fcntl.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cerrno>
|
|
#include <condition_variable>
|
|
#include <cstdint>
|
|
#include <deque>
|
|
#include <expected>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <unordered_map>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::SystemAsync
|
|
{
|
|
|
|
namespace
|
|
{
|
|
|
|
thread_local const void* t_active_subscription_token = nullptr;
|
|
|
|
struct DispatchGuard {
|
|
const void* prev{nullptr};
|
|
explicit DispatchGuard(const void* cur) noexcept
|
|
: prev(t_active_subscription_token)
|
|
{
|
|
t_active_subscription_token = cur;
|
|
}
|
|
~DispatchGuard() noexcept { t_active_subscription_token = prev; }
|
|
};
|
|
|
|
struct PathSnapshot {
|
|
bool exists{false};
|
|
bool is_symlink{false};
|
|
bool permission_denied{false};
|
|
int sys_errno{0};
|
|
std::uint64_t dev{0};
|
|
std::uint64_t ino{0};
|
|
std::uint32_t mode{0};
|
|
std::uint64_t size{0};
|
|
std::int64_t mtime_ns{0};
|
|
std::string symlink_target{};
|
|
|
|
[[nodiscard]] bool operator==(const PathSnapshot&) const = default;
|
|
};
|
|
|
|
[[nodiscard]] PathSnapshot probe_path(const std::filesystem::path& path)
|
|
{
|
|
PathSnapshot snap;
|
|
#ifndef _WIN32
|
|
struct stat st {};
|
|
if (::lstat(path.c_str(), &st) != 0) {
|
|
const int err = errno;
|
|
snap.sys_errno = err;
|
|
if (err == EACCES || err == EPERM) {
|
|
snap.permission_denied = true;
|
|
}
|
|
return snap;
|
|
}
|
|
snap.exists = true;
|
|
snap.is_symlink = S_ISLNK(st.st_mode);
|
|
snap.dev = static_cast<std::uint64_t>(st.st_dev);
|
|
snap.ino = static_cast<std::uint64_t>(st.st_ino);
|
|
snap.mode = static_cast<std::uint32_t>(st.st_mode);
|
|
snap.size = static_cast<std::uint64_t>(st.st_size);
|
|
snap.mtime_ns =
|
|
static_cast<std::int64_t>(st.st_mtim.tv_sec) * 1000000000LL +
|
|
static_cast<std::int64_t>(st.st_mtim.tv_nsec);
|
|
|
|
if (snap.is_symlink) {
|
|
std::array<char, 4096> link_buf{};
|
|
const ssize_t len =
|
|
::readlink(path.c_str(), link_buf.data(), link_buf.size());
|
|
if (len > 0) {
|
|
snap.symlink_target.assign(
|
|
link_buf.data(), static_cast<std::size_t>(len));
|
|
}
|
|
}
|
|
#else
|
|
(void)path;
|
|
#endif
|
|
return snap;
|
|
}
|
|
|
|
[[nodiscard]] bool path_within_root(const std::filesystem::path& candidate,
|
|
const std::filesystem::path& root,
|
|
std::filesystem::path& out_normalized)
|
|
{
|
|
std::error_code ec;
|
|
const auto canon_root = std::filesystem::weakly_canonical(root, ec);
|
|
if (ec) {
|
|
return false;
|
|
}
|
|
const auto lex_cand = candidate.lexically_normal();
|
|
for (const auto& comp : lex_cand) {
|
|
if (comp == "..") {
|
|
return false;
|
|
}
|
|
}
|
|
const auto parent = lex_cand.parent_path();
|
|
std::filesystem::path norm_cand;
|
|
if (!parent.empty()) {
|
|
const auto canon_parent = std::filesystem::weakly_canonical(parent, ec);
|
|
if (ec) {
|
|
return false;
|
|
}
|
|
norm_cand = canon_parent / lex_cand.filename();
|
|
} else {
|
|
norm_cand = std::filesystem::weakly_canonical(lex_cand, ec);
|
|
if (ec) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
auto rel = norm_cand.lexically_relative(canon_root);
|
|
if (rel.empty()) {
|
|
return false;
|
|
}
|
|
for (const auto& comp : rel) {
|
|
if (comp == "..") {
|
|
return false;
|
|
}
|
|
break;
|
|
}
|
|
out_normalized = std::move(norm_cand);
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] WatchEvent classify_transition(const std::filesystem::path& path,
|
|
const PathSnapshot& prev,
|
|
const PathSnapshot& cur,
|
|
bool allow_symlink)
|
|
{
|
|
WatchEvent ev;
|
|
ev.path = path;
|
|
ev.exists = cur.exists;
|
|
ev.dev = cur.dev;
|
|
ev.ino = cur.ino;
|
|
ev.size = cur.size;
|
|
ev.sys_errno = cur.sys_errno;
|
|
|
|
if (cur.permission_denied) {
|
|
ev.kind = WatchEventKind::permission_denied;
|
|
return ev;
|
|
}
|
|
if (cur.is_symlink && !allow_symlink) {
|
|
ev.kind = WatchEventKind::permission_denied;
|
|
return ev;
|
|
}
|
|
if (!prev.exists && cur.exists) {
|
|
ev.kind = WatchEventKind::created;
|
|
return ev;
|
|
}
|
|
if (prev.exists && !cur.exists) {
|
|
ev.kind = WatchEventKind::deleted;
|
|
return ev;
|
|
}
|
|
if (prev.is_symlink || cur.is_symlink) {
|
|
ev.kind = WatchEventKind::symlink_changed;
|
|
return ev;
|
|
}
|
|
if (prev.dev != cur.dev || prev.ino != cur.ino) {
|
|
ev.kind = WatchEventKind::replaced_inode;
|
|
return ev;
|
|
}
|
|
ev.kind = WatchEventKind::modified;
|
|
return ev;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
struct WatchSubscription::Token {
|
|
std::uint64_t id{0};
|
|
std::filesystem::path path{};
|
|
WatchCallback callback{};
|
|
WatchPathOptions options{};
|
|
std::weak_ptr<WatcherService::Impl> service{};
|
|
|
|
PathSnapshot accepted{};
|
|
PathSnapshot pending{};
|
|
int stable_polls{0};
|
|
bool dirty{false};
|
|
|
|
bool active{true};
|
|
bool delivery_scheduled{false};
|
|
bool dispatching{false};
|
|
std::deque<WatchEvent> queue{};
|
|
std::mutex mu{};
|
|
std::condition_variable cv{};
|
|
|
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
|
close_and_join();
|
|
};
|
|
|
|
struct WatcherService::Impl
|
|
: public std::enable_shared_from_this<WatcherService::Impl> {
|
|
using Token = WatchSubscription::Token;
|
|
|
|
Void::Async::Executor& executor;
|
|
WatcherLimits limits;
|
|
const Void::Time::MonotonicClock& clock;
|
|
ErrorSink error_sink{};
|
|
|
|
Void::Async::TaskScope scope;
|
|
std::mutex poll_mu{};
|
|
mutable std::mutex state_mu{};
|
|
std::condition_variable stop_cv{};
|
|
std::uint64_t next_id{1};
|
|
bool closed{false};
|
|
std::size_t total_queued{0};
|
|
std::unordered_map<std::uint64_t, std::shared_ptr<Token>> subs{};
|
|
std::thread bg_thread{};
|
|
|
|
Impl(Void::Async::Executor& ex,
|
|
WatcherLimits lim,
|
|
const Void::Time::MonotonicClock& clk,
|
|
ErrorSink sink)
|
|
: executor(ex),
|
|
limits(lim),
|
|
clock(clk),
|
|
error_sink(std::move(sink)),
|
|
scope(ex, Void::Async::TaskScopeOptions::unlimited(), clk)
|
|
{
|
|
}
|
|
|
|
static void enqueue_event_locked(Impl& impl, Token& tok, WatchEvent ev)
|
|
{
|
|
std::lock_guard tlk{tok.mu};
|
|
if (!tok.active) {
|
|
return;
|
|
}
|
|
|
|
for (auto& existing : tok.queue) {
|
|
if (existing.path == ev.path) {
|
|
if (existing.kind != WatchEventKind::rescan_required) {
|
|
existing = std::move(ev);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (impl.total_queued >= impl.limits.max_queued_events) {
|
|
if (!tok.queue.empty()) {
|
|
tok.queue.back().kind = WatchEventKind::rescan_required;
|
|
return;
|
|
}
|
|
ev.kind = WatchEventKind::rescan_required;
|
|
}
|
|
|
|
tok.queue.push_back(std::move(ev));
|
|
++impl.total_queued;
|
|
}
|
|
|
|
[[nodiscard]] static Void::Coro::Task<void> deliver_subscription_events(
|
|
std::shared_ptr<Impl> impl,
|
|
std::shared_ptr<Token> tok)
|
|
{
|
|
for (;;) {
|
|
WatchEvent ev;
|
|
{
|
|
std::lock_guard lk{impl->state_mu};
|
|
std::lock_guard tlk{tok->mu};
|
|
if (!tok->active || tok->queue.empty()) {
|
|
tok->delivery_scheduled = false;
|
|
tok->dispatching = false;
|
|
tok->cv.notify_all();
|
|
co_return;
|
|
}
|
|
ev = std::move(tok->queue.front());
|
|
tok->queue.pop_front();
|
|
if (impl->total_queued > 0) {
|
|
--impl->total_queued;
|
|
}
|
|
tok->dispatching = true;
|
|
}
|
|
|
|
try {
|
|
DispatchGuard dg{tok.get()};
|
|
tok->callback(ev);
|
|
} catch (const std::exception& ex) {
|
|
if (impl->error_sink) {
|
|
impl->error_sink(Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::internal,
|
|
std::format(
|
|
"Watcher callback exception: {}", ex.what())));
|
|
}
|
|
} catch (...) {
|
|
if (impl->error_sink) {
|
|
impl->error_sink(Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::internal,
|
|
"Watcher callback threw non-std exception"));
|
|
}
|
|
}
|
|
|
|
{
|
|
std::lock_guard tlk{tok->mu};
|
|
tok->dispatching = false;
|
|
tok->cv.notify_all();
|
|
if (!tok->active) {
|
|
tok->delivery_scheduled = false;
|
|
co_return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void poll_once()
|
|
{
|
|
std::lock_guard poll_lk{poll_mu};
|
|
|
|
std::vector<std::shared_ptr<Token>> active_subs;
|
|
{
|
|
std::lock_guard lk{state_mu};
|
|
if (closed) {
|
|
return;
|
|
}
|
|
active_subs.reserve(subs.size());
|
|
for (const auto& [id, tok] : subs) {
|
|
(void)id;
|
|
active_subs.push_back(tok);
|
|
}
|
|
}
|
|
|
|
std::vector<std::shared_ptr<Token>> to_schedule;
|
|
const int required_debounce = std::max(1, limits.debounce_polls);
|
|
|
|
for (const auto& tok : active_subs) {
|
|
std::filesystem::path p;
|
|
bool allow_sym = false;
|
|
{
|
|
std::lock_guard tlk{tok->mu};
|
|
if (!tok->active) {
|
|
continue;
|
|
}
|
|
p = tok->path;
|
|
allow_sym = tok->options.allow_symlink;
|
|
}
|
|
|
|
const PathSnapshot cur = probe_path(p);
|
|
|
|
std::lock_guard lk{state_mu};
|
|
if (closed) {
|
|
break;
|
|
}
|
|
std::optional<WatchEvent> ready_event;
|
|
{
|
|
std::lock_guard tlk{tok->mu};
|
|
if (!tok->active) {
|
|
continue;
|
|
}
|
|
if (!tok->dirty) {
|
|
if (!(cur == tok->accepted)) {
|
|
tok->pending = cur;
|
|
tok->stable_polls = 1;
|
|
tok->dirty = true;
|
|
}
|
|
} else {
|
|
if (cur == tok->pending) {
|
|
++tok->stable_polls;
|
|
} else if (cur == tok->accepted) {
|
|
tok->dirty = false;
|
|
tok->stable_polls = 0;
|
|
} else {
|
|
tok->pending = cur;
|
|
tok->stable_polls = 1;
|
|
}
|
|
}
|
|
|
|
if (tok->dirty && tok->stable_polls >= required_debounce) {
|
|
WatchEvent ev = classify_transition(
|
|
tok->path, tok->accepted, tok->pending, allow_sym);
|
|
tok->accepted = tok->pending;
|
|
tok->dirty = false;
|
|
tok->stable_polls = 0;
|
|
ready_event = std::move(ev);
|
|
}
|
|
}
|
|
|
|
if (ready_event.has_value()) {
|
|
enqueue_event_locked(*this, *tok, std::move(*ready_event));
|
|
std::lock_guard tlk{tok->mu};
|
|
if (tok->active && !tok->delivery_scheduled &&
|
|
!tok->queue.empty()) {
|
|
tok->delivery_scheduled = true;
|
|
to_schedule.push_back(tok);
|
|
}
|
|
}
|
|
}
|
|
|
|
auto self = this->shared_from_this();
|
|
for (const auto& tok : to_schedule) {
|
|
(void)scope.spawn(deliver_subscription_events(self, tok));
|
|
}
|
|
}
|
|
};
|
|
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
WatchSubscription::Token::close_and_join()
|
|
{
|
|
auto svc = service.lock();
|
|
if (t_active_subscription_token == this) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::self_join,
|
|
"WatchSubscription::close_and_join cannot be called from its own callback")};
|
|
}
|
|
|
|
if (svc != nullptr && svc->executor.is_executor_thread()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::self_join,
|
|
"WatchSubscription::close_and_join cannot block on executor thread")};
|
|
}
|
|
|
|
if (svc != nullptr) {
|
|
std::lock_guard lk{svc->state_mu};
|
|
std::lock_guard tlk{mu};
|
|
if (svc->total_queued >= queue.size()) {
|
|
svc->total_queued -= queue.size();
|
|
} else {
|
|
svc->total_queued = 0;
|
|
}
|
|
queue.clear();
|
|
active = false;
|
|
svc->subs.erase(id);
|
|
} else {
|
|
std::lock_guard tlk{mu};
|
|
queue.clear();
|
|
active = false;
|
|
}
|
|
|
|
std::unique_lock tlk{mu};
|
|
cv.wait(tlk, [this] { return !dispatching; });
|
|
return {};
|
|
}
|
|
|
|
WatchSubscription::~WatchSubscription() noexcept
|
|
{
|
|
if (token_) {
|
|
(void)token_->close_and_join();
|
|
}
|
|
}
|
|
|
|
WatchSubscription::WatchSubscription(WatchSubscription&&) noexcept = default;
|
|
WatchSubscription&
|
|
WatchSubscription::operator=(WatchSubscription&& other) noexcept
|
|
{
|
|
if (this != &other) {
|
|
if (token_) {
|
|
(void)token_->close_and_join();
|
|
}
|
|
token_ = std::move(other.token_);
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
bool WatchSubscription::active() const noexcept
|
|
{
|
|
if (!token_) {
|
|
return false;
|
|
}
|
|
std::lock_guard lk{token_->mu};
|
|
return token_->active;
|
|
}
|
|
|
|
Void::Result::Result<void, Void::Result::Error>
|
|
WatchSubscription::close_and_join()
|
|
{
|
|
if (!token_) {
|
|
return {};
|
|
}
|
|
auto res = token_->close_and_join();
|
|
if (res.has_value()) {
|
|
token_.reset();
|
|
}
|
|
return res;
|
|
}
|
|
|
|
WatcherService::WatcherService(Void::Async::Executor& executor,
|
|
WatcherLimits limits,
|
|
const Void::Time::MonotonicClock& clock,
|
|
ErrorSink error_sink,
|
|
bool start_background_thread)
|
|
: impl_(std::make_shared<Impl>(
|
|
executor, limits, clock, std::move(error_sink)))
|
|
{
|
|
if (start_background_thread) {
|
|
std::weak_ptr<Impl> weak_impl = impl_;
|
|
impl_->bg_thread = std::thread([weak_impl] {
|
|
for (;;) {
|
|
auto p = weak_impl.lock();
|
|
if (!p) {
|
|
return;
|
|
}
|
|
std::chrono::milliseconds interval{250};
|
|
{
|
|
std::unique_lock lk{p->state_mu};
|
|
if (p->closed) {
|
|
return;
|
|
}
|
|
interval = std::max(std::chrono::milliseconds{10},
|
|
p->limits.poll_interval);
|
|
p->stop_cv.wait_for(lk, interval, [&p] {
|
|
return p->closed;
|
|
});
|
|
if (p->closed) {
|
|
return;
|
|
}
|
|
}
|
|
p->poll_once();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
WatcherService::~WatcherService() noexcept { (void)shutdown(); }
|
|
|
|
Void::Result::Result<WatchSubscription, Void::Result::Error>
|
|
WatcherService::watch(const std::filesystem::path& path,
|
|
WatchCallback callback,
|
|
WatchPathOptions options)
|
|
{
|
|
if (path.empty() || !callback) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::invalid_argument,
|
|
"WatcherService::watch requires non-empty path and callback")};
|
|
}
|
|
|
|
std::filesystem::path target_path = path;
|
|
if (options.allowed_root.has_value()) {
|
|
std::filesystem::path normalized;
|
|
if (!path_within_root(path, *options.allowed_root, normalized)) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::permission_denied,
|
|
std::format(
|
|
"WatcherService::watch: '{}' escapes allowed_root",
|
|
path.string()))};
|
|
}
|
|
target_path = std::move(normalized);
|
|
}
|
|
|
|
const PathSnapshot initial = probe_path(target_path);
|
|
if (initial.is_symlink && !options.allow_symlink) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::permission_denied,
|
|
std::format(
|
|
"WatcherService::watch: '{}' is a symlink and allow_symlink is false",
|
|
target_path.string()))};
|
|
}
|
|
|
|
auto tok = std::make_shared<WatchSubscription::Token>();
|
|
tok->path = std::move(target_path);
|
|
tok->callback = std::move(callback);
|
|
tok->options = std::move(options);
|
|
tok->service = impl_;
|
|
tok->accepted = initial;
|
|
tok->pending = initial;
|
|
|
|
{
|
|
std::lock_guard lk{impl_->state_mu};
|
|
if (impl_->closed) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::busy,
|
|
"WatcherService::watch: service is shut down")};
|
|
}
|
|
if (impl_->subs.size() >= impl_->limits.max_watched_paths) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::limit_exceeded,
|
|
std::format(
|
|
"WatcherService::watch: max_watched_paths ({}) reached",
|
|
impl_->limits.max_watched_paths))};
|
|
}
|
|
tok->id = impl_->next_id++;
|
|
impl_->subs.emplace(tok->id, tok);
|
|
}
|
|
|
|
WatchSubscription sub;
|
|
sub.token_ = std::move(tok);
|
|
return sub;
|
|
}
|
|
|
|
void WatcherService::poll_once() { impl_->poll_once(); }
|
|
|
|
std::size_t WatcherService::watch_count() const noexcept
|
|
{
|
|
std::lock_guard lk{impl_->state_mu};
|
|
return impl_->subs.size();
|
|
}
|
|
|
|
std::size_t WatcherService::queued_event_count() const noexcept
|
|
{
|
|
std::lock_guard lk{impl_->state_mu};
|
|
return impl_->total_queued;
|
|
}
|
|
|
|
Void::Result::Result<void, Void::Result::Error> WatcherService::shutdown()
|
|
{
|
|
if (impl_->executor.is_executor_thread()) {
|
|
return std::unexpected{Void::System::make_system_error(
|
|
Void::System::SystemErrorCode::self_join,
|
|
"WatcherService::shutdown cannot be called on executor thread")};
|
|
}
|
|
|
|
std::thread bg;
|
|
{
|
|
std::lock_guard lk{impl_->state_mu};
|
|
if (impl_->closed) {
|
|
return {};
|
|
}
|
|
impl_->closed = true;
|
|
impl_->total_queued = 0;
|
|
for (const auto& [id, tok] : impl_->subs) {
|
|
(void)id;
|
|
std::lock_guard tlk{tok->mu};
|
|
tok->active = false;
|
|
tok->queue.clear();
|
|
}
|
|
impl_->subs.clear();
|
|
impl_->stop_cv.notify_all();
|
|
bg = std::move(impl_->bg_thread);
|
|
}
|
|
|
|
if (bg.joinable()) {
|
|
bg.join();
|
|
}
|
|
|
|
impl_->scope.request_stop();
|
|
if (impl_->executor.has_background_workers()) {
|
|
(void)impl_->scope.join_blocking();
|
|
} else if (auto* manual =
|
|
dynamic_cast<Void::Async::ManualExecutor*>(&impl_->executor)) {
|
|
(void)impl_->scope.join_pumping(*manual);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
} // namespace Void::SystemAsync
|