feat(SystemAsync): add async IO ProcessManager/communicate and shared WatcherService with WatchSubscription (M-SYSTEM-03, M-SYSTEM-04)

This commit is contained in:
faumaray committed 2026-11-24 14:46:46 +03:00
1 parent fcdbc063b2
commit 9a3c5d86ef
9 files changed
+2062

No files matched your search

+781
View File
@@ -0,0 +1,781 @@
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/System/AsyncProcess.hpp>
#include <signal.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstring>
#include <expected>
#include <format>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace Void::SystemAsync
{
namespace
{
struct PipeCommState {
std::mutex mu{};
Void::Process::CaptureLimits limits{};
std::stop_source stop_src{};
std::string out{};
std::string err{};
std::size_t out_cur_line{0};
std::size_t err_cur_line{0};
bool stdout_truncated{false};
bool stderr_truncated{false};
bool timed_out{false};
bool cancelled{false};
bool overflowed{false};
std::optional<Void::Result::Error> fatal_error{};
};
void record_fatal(PipeCommState& st, Void::Result::Error err)
{
std::lock_guard lk{st.mu};
if (!st.fatal_error.has_value()) {
st.fatal_error = std::move(err);
}
st.stop_src.request_stop();
}
void process_pipe_chunk(PipeCommState& st,
const std::byte* data,
std::size_t len,
bool is_stdout)
{
std::lock_guard lk{st.mu};
std::string& dst = is_stdout ? st.out : st.err;
const std::size_t max_bytes =
is_stdout ? st.limits.max_stdout_bytes : st.limits.max_stderr_bytes;
bool& truncated = is_stdout ? st.stdout_truncated : st.stderr_truncated;
std::size_t& cur_line = is_stdout ? st.out_cur_line : st.err_cur_line;
const auto* chars = reinterpret_cast<const char*>(data);
if (st.limits.max_line_bytes > 0) {
for (std::size_t i = 0; i < len; ++i) {
if (chars[i] == '\n') {
cur_line = 0;
} else {
++cur_line;
if (cur_line > st.limits.max_line_bytes) {
truncated = true;
st.overflowed = true;
if (st.limits.overflow_policy ==
Void::Process::OverflowPolicy::fail_and_terminate) {
if (!st.fatal_error.has_value()) {
st.fatal_error = Void::System::make_system_error(
Void::System::SystemErrorCode::line_limit,
std::format(
"Async process {} line exceeded max_line_bytes ({})",
is_stdout ? "stdout" : "stderr",
st.limits.max_line_bytes));
}
st.stop_src.request_stop();
return;
}
}
}
}
}
const std::size_t rem_cap =
(dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0;
const std::size_t to_store = std::min(len, rem_cap);
if (to_store > 0) {
dst.append(chars, to_store);
}
if (to_store < len) {
truncated = true;
st.overflowed = true;
if (st.limits.overflow_policy ==
Void::Process::OverflowPolicy::fail_and_terminate) {
if (!st.fatal_error.has_value()) {
st.fatal_error = Void::System::make_system_error(
Void::System::SystemErrorCode::output_limit,
std::format(
"Async process {} output exceeded limit ({} bytes)",
is_stdout ? "stdout" : "stderr",
max_bytes));
}
st.stop_src.request_stop();
}
}
}
[[nodiscard]] Void::Coro::Task<void> pump_stdin_task(
Void::IO::Driver* driver,
Void::IO::ByteStream stream,
std::shared_ptr<PipeCommState> st,
std::string stdin_data,
std::stop_token ext_stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline)
{
constexpr std::size_t kChunk = 16ULL * 1024ULL;
std::size_t offset = 0;
while (offset < stdin_data.size() && !st->stop_src.stop_requested()) {
const std::size_t n = std::min(kChunk, stdin_data.size() - offset);
auto lease_res = driver->allocate_buffer(n);
if (!lease_res.has_value()) {
record_fatal(*st, std::move(lease_res.error()));
break;
}
auto lease = std::move(*lease_res);
std::memcpy(lease.writable().data(), stdin_data.data() + offset, n);
lease.set_valid_bytes(n);
Void::Async::OperationOptions pipe_opts{
.stop = st->stop_src.get_token(), .deadline = deadline};
auto wr = co_await stream.write_some_owned(lease, pipe_opts);
if (!wr.has_value()) {
const auto& err = wr.error();
if (err.kind() == Void::Result::ErrorKind::timeout) {
std::lock_guard lk{st->mu};
st->timed_out = true;
st->stop_src.request_stop();
} else if (err.kind() == Void::Result::ErrorKind::cancelled &&
ext_stop.stop_requested()) {
std::lock_guard lk{st->mu};
st->cancelled = true;
st->stop_src.request_stop();
}
break;
}
offset += wr->bytes;
}
(void)co_await stream.close_and_join();
}
[[nodiscard]] Void::Coro::Task<void> pump_read_task(
Void::IO::Driver* driver,
Void::IO::ByteStream stream,
std::shared_ptr<PipeCommState> st,
bool is_stdout,
std::stop_token ext_stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline)
{
constexpr std::size_t kChunk = 16ULL * 1024ULL;
auto lease_res = driver->allocate_buffer(kChunk);
if (!lease_res.has_value()) {
record_fatal(*st, std::move(lease_res.error()));
(void)co_await stream.close_and_join();
co_return;
}
auto lease = std::move(*lease_res);
while (!st->stop_src.stop_requested()) {
Void::Async::OperationOptions pipe_opts{
.stop = st->stop_src.get_token(), .deadline = deadline};
auto rd = co_await stream.read_some_owned(lease, pipe_opts);
if (!rd.has_value()) {
const auto& err = rd.error();
if (err.kind() == Void::Result::ErrorKind::timeout) {
std::lock_guard lk{st->mu};
st->timed_out = true;
st->stop_src.request_stop();
} else if (err.kind() == Void::Result::ErrorKind::cancelled) {
if (ext_stop.stop_requested()) {
std::lock_guard lk{st->mu};
st->cancelled = true;
}
} else {
record_fatal(*st, err);
}
break;
}
if (rd->bytes > 0) {
process_pipe_chunk(
*st, lease.readable().data(), rd->bytes, is_stdout);
if (st->stop_src.stop_requested()) {
break;
}
}
if (rd->eof) {
break;
}
}
(void)co_await stream.close_and_join();
}
struct WaitOutcome {
Void::Process::ExitStatus status{};
bool timed_out{false};
bool cancelled{false};
};
struct ReaperEntry {
Void::Process::Child* child{nullptr};
std::shared_ptr<Void::Async::OperationState<WaitOutcome>> op{};
bool escalate_immediately{false};
int phase{0}; // 0 = waiting/running, 1 = SIGTERM sent
std::chrono::milliseconds grace{std::chrono::milliseconds{2000}};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
Void::Time::MonotonicClock::time_point kill_deadline{};
bool done{false};
};
} // namespace
struct ProcessManager::Impl : public std::enable_shared_from_this<ProcessManager::Impl> {
Void::IO::Driver& driver;
Void::Async::Executor& executor;
ProcessManagerOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::size_t active_slots{0};
bool closing{false};
bool stop_worker{false};
std::vector<ReaperEntry> waits{};
std::vector<std::shared_ptr<Void::Async::OperationState<void>>> close_waiters{};
std::thread reaper_thread{};
Impl(Void::IO::Driver& d,
Void::Async::Executor& ex,
ProcessManagerOptions opts,
const Void::Time::MonotonicClock& clk)
: driver(d), executor(ex), options(opts), clock(clk)
{
reaper_thread = std::thread([this] { run_reaper(); });
}
~Impl() noexcept
{
{
std::lock_guard lk{mu};
closing = true;
stop_worker = true;
cv.notify_all();
}
if (reaper_thread.joinable()) {
reaper_thread.join();
}
}
void release_slot() noexcept
{
std::lock_guard lk{mu};
if (active_slots > 0) {
--active_slots;
}
cv.notify_all();
}
void run_reaper()
{
for (;;) {
std::vector<Void::Async::ResumeTicket> tickets;
std::vector<std::shared_ptr<Void::Async::OperationState<void>>>
completed_closes;
{
std::unique_lock lk{mu};
if (waits.empty() && !stop_worker) {
cv.wait(lk, [this] {
return !waits.empty() || stop_worker;
});
}
if (stop_worker && waits.empty()) {
for (auto& cw : close_waiters) {
if (auto t = cw->try_commit_value(); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = cw->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
}
close_waiters.clear();
lk.unlock();
for (auto& t : tickets) {
t.dispatch();
}
return;
}
const auto now = clock.now();
for (auto& w : waits) {
if (w.done) {
continue;
}
auto polled = w.child->try_wait();
if (!polled.has_value()) {
if (auto t = w.op->try_commit_error(
std::move(polled.error()));
t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
continue;
}
if (polled->has_value()) {
WaitOutcome wo;
wo.status = **polled;
wo.timed_out =
(w.phase > 0 && w.deadline.has_value() &&
now >= *w.deadline) ||
w.escalate_immediately;
wo.cancelled = w.op->stop_requested() || stop_worker;
if (auto t = w.op->try_commit_value(wo); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
continue;
}
const bool expired =
w.deadline.has_value() && now >= *w.deadline;
const bool stopped = w.op->stop_requested() || stop_worker;
if (w.phase == 0 &&
(w.escalate_immediately || expired || stopped)) {
(void)w.child->send_signal(SIGTERM);
w.phase = 1;
w.kill_deadline = now + w.grace;
} else if (w.phase == 1 && now >= w.kill_deadline) {
(void)w.child->send_signal(SIGKILL);
auto term_res = w.child->wait_blocking(
std::chrono::milliseconds{1000});
if (term_res.has_value()) {
WaitOutcome wo;
wo.status = *term_res;
wo.timed_out = expired;
wo.cancelled = stopped;
if (auto t = w.op->try_commit_value(wo);
t.has_value()) {
tickets.push_back(std::move(*t));
}
} else {
if (auto t = w.op->try_commit_error(
std::move(term_res.error()));
t.has_value()) {
tickets.push_back(std::move(*t));
}
}
if (auto r = w.op->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
w.done = true;
}
}
std::erase_if(
waits, [](const ReaperEntry& e) { return e.done; });
if (closing && waits.empty() && !close_waiters.empty()) {
completed_closes = std::move(close_waiters);
close_waiters.clear();
}
}
for (auto& cw : completed_closes) {
if (auto t = cw->try_commit_value(); t.has_value()) {
tickets.push_back(std::move(*t));
}
if (auto r = cw->release_backend_ref(); r.has_value()) {
tickets.push_back(std::move(*r));
}
}
for (auto& t : tickets) {
t.dispatch();
}
std::unique_lock lk{mu};
if (!waits.empty()) {
cv.wait_for(lk, std::chrono::milliseconds{5}, [this] {
return stop_worker;
});
}
}
}
};
struct ManagedChild::SlotGuard {
std::weak_ptr<ProcessManager::Impl> mgr;
~SlotGuard() noexcept
{
if (auto p = mgr.lock()) {
p->release_slot();
}
}
};
ManagedChild::~ManagedChild() noexcept = default;
ManagedChild::ManagedChild(ManagedChild&&) noexcept = default;
ManagedChild& ManagedChild::operator=(ManagedChild&&) noexcept = default;
bool ManagedChild::valid() const noexcept { return child_.valid(); }
void ManagedChild::release_slot() noexcept
{
child_ = Void::Process::Child{};
slot_token_.reset();
}
ProcessManager::ProcessManager(Void::IO::Driver& driver,
Void::Async::Executor& executor,
ProcessManagerOptions options,
const Void::Time::MonotonicClock& clock)
: impl_(std::make_shared<Impl>(driver, executor, options, clock))
{
}
ProcessManager::~ProcessManager() noexcept = default;
Void::Result::Result<ManagedChild, Void::Result::Error>
ProcessManager::spawn(const Void::Process::SpawnOptions& options)
{
{
std::lock_guard lk{impl_->mu};
if (impl_->closing) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"ProcessManager::spawn: manager is closing")};
}
if (impl_->active_slots >= impl_->options.max_active_children) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"ProcessManager::spawn: active child limit ({}) reached",
impl_->options.max_active_children))};
}
++impl_->active_slots;
}
auto guard =
std::make_shared<ManagedChild::SlotGuard>(impl_);
auto child = Void::Process::spawn(options);
if (!child.has_value()) {
return std::unexpected{std::move(child.error())};
}
ManagedChild out;
out.child_ = std::move(*child);
out.slot_token_ = std::move(guard);
return out;
}
namespace
{
[[nodiscard]] Void::Coro::Task<Void::Result::Result<WaitOutcome, Void::Result::Error>>
wait_for_reap_async(
std::shared_ptr<ProcessManager::Impl> impl,
Void::Process::Child& child,
bool escalate_immediately,
std::chrono::milliseconds grace,
Void::Async::OperationOptions options)
{
if (!child.valid()) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"ProcessManager::wait: invalid child")};
}
if (auto polled = child.try_wait(); !polled.has_value()) {
co_return std::unexpected{std::move(polled.error())};
} else if (polled->has_value()) {
WaitOutcome wo;
wo.status = **polled;
co_return wo;
}
auto op = Void::Async::OperationState<WaitOutcome>::create(
options,
&impl->executor,
Void::Async::StopBehavior::notify_only);
op->acquire_backend_ref();
{
std::lock_guard lk{impl->mu};
if (impl->closing && !escalate_immediately) {
if (auto r = op->release_backend_ref(); r.has_value()) {
r->dispatch();
}
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"ProcessManager::wait: manager is closing")};
}
ReaperEntry entry;
entry.child = &child;
entry.op = op;
entry.escalate_immediately = escalate_immediately;
entry.grace = grace;
entry.deadline = options.deadline;
impl->waits.push_back(std::move(entry));
impl->cv.notify_all();
}
co_return co_await op->awaitable(&impl->executor);
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
ProcessManager::communicate(Void::Process::Child& child,
std::string stdin_data,
Void::Process::CaptureLimits limits,
Void::Async::OperationOptions options)
{
if (!child.valid()) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"ProcessManager::communicate: invalid child")};
}
if (stdin_data.size() > limits.max_stdin_bytes) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::limit_exceeded,
"ProcessManager::communicate: stdin exceeds max_stdin_bytes")};
}
if (Void::Async::is_deadline_expired(options, impl_->clock)) {
(void)child.terminate(impl_->options.default_kill_grace);
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"ProcessManager::communicate: deadline already expired")};
}
if (stdin_data.empty()) {
child.close_stdin();
}
Void::IO::ByteStream in_stream;
Void::IO::ByteStream out_stream;
Void::IO::ByteStream err_stream;
auto adopt_pipe =
[&](Void::System::OwnedFd owned,
Void::IO::ByteStream& target) -> Void::Result::Result<void, Void::Result::Error> {
if (!owned.valid()) {
return {};
}
auto adopted = impl_->driver.adopt_fd(owned.get());
if (!adopted.has_value()) {
return std::unexpected{std::move(adopted.error())};
}
(void)owned.release();
target = std::move(*adopted);
return {};
};
if (auto r = adopt_pipe(child.take_stdin_fd(), in_stream); !r.has_value()) {
co_return std::unexpected{std::move(r.error())};
}
if (auto r = adopt_pipe(child.take_stdout_fd(), out_stream); !r.has_value()) {
if (in_stream.valid()) {
(void)co_await in_stream.close_and_join();
}
co_return std::unexpected{std::move(r.error())};
}
if (auto r = adopt_pipe(child.take_stderr_fd(), err_stream); !r.has_value()) {
if (in_stream.valid()) {
(void)co_await in_stream.close_and_join();
}
if (out_stream.valid()) {
(void)co_await out_stream.close_and_join();
}
co_return std::unexpected{std::move(r.error())};
}
auto st = std::make_shared<PipeCommState>();
st->limits = limits;
struct ForwardStop {
std::shared_ptr<PipeCommState> state;
void operator()() const noexcept { state->stop_src.request_stop(); }
};
std::optional<std::stop_callback<ForwardStop>> ext_cb;
if (options.stop.stop_possible()) {
ext_cb.emplace(options.stop, ForwardStop{st});
}
Void::Async::TaskScope scope{
impl_->executor,
Void::Async::TaskScopeOptions::unlimited(st->stop_src.get_token(), false),
impl_->clock};
if (in_stream.valid()) {
auto sp = scope.spawn(pump_stdin_task(&impl_->driver,
std::move(in_stream),
st,
std::move(stdin_data),
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stdin pump"));
}
}
if (out_stream.valid()) {
auto sp = scope.spawn(pump_read_task(&impl_->driver,
std::move(out_stream),
st,
true,
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stdout pump"));
}
}
if (err_stream.valid()) {
auto sp = scope.spawn(pump_read_task(&impl_->driver,
std::move(err_stream),
st,
false,
options.stop,
options.deadline));
if (!sp.has_value()) {
record_fatal(*st,
Void::Async::make_async_error(
sp.error(), "Failed to spawn async stderr pump"));
}
}
(void)co_await scope.join();
bool need_terminate = false;
bool timed_out_flag = false;
bool cancelled_flag = options.stop.stop_requested();
std::optional<Void::Result::Error> fatal_err;
{
std::lock_guard lk{st->mu};
timed_out_flag = st->timed_out ||
Void::Async::is_deadline_expired(options, impl_->clock);
cancelled_flag = cancelled_flag || st->cancelled;
fatal_err = st->fatal_error;
need_terminate = timed_out_flag || cancelled_flag || fatal_err.has_value();
}
auto wait_res = co_await wait_for_reap_async(
impl_,
child,
need_terminate,
impl_->options.default_kill_grace,
need_terminate ? Void::Async::OperationOptions{} : options);
if (fatal_err.has_value()) {
co_return std::unexpected{std::move(*fatal_err)};
}
if (!wait_res.has_value()) {
co_return std::unexpected{std::move(wait_res.error())};
}
Void::Process::CommunicateResult out;
{
std::lock_guard lk{st->mu};
out.out = std::move(st->out);
out.err = std::move(st->err);
out.stdout_truncated = st->stdout_truncated;
out.stderr_truncated = st->stderr_truncated;
out.overflowed = st->overflowed;
}
out.status = wait_res->status;
out.timed_out = timed_out_flag || wait_res->timed_out;
out.cancelled = cancelled_flag || wait_res->cancelled;
co_return out;
}
Void::Coro::Task<Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
ProcessManager::communicate(ManagedChild& managed,
std::string stdin_data,
Void::Process::CaptureLimits limits,
Void::Async::OperationOptions options)
{
co_return co_await communicate(
managed.child(), std::move(stdin_data), limits, std::move(options));
}
Void::Coro::Task<Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
ProcessManager::wait(Void::Process::Child& child,
Void::Async::OperationOptions options)
{
auto wo = co_await wait_for_reap_async(
impl_,
child,
false,
impl_->options.default_kill_grace,
std::move(options));
if (!wo.has_value()) {
co_return std::unexpected{std::move(wo.error())};
}
if (wo->cancelled) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"ProcessManager::wait cancelled; child terminated")};
}
if (wo->timed_out) {
co_return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"ProcessManager::wait timed out; child terminated")};
}
co_return wo->status;
}
Void::Coro::Task<Void::Result::Result<Void::Process::ExitStatus, Void::Result::Error>>
ProcessManager::wait(ManagedChild& managed,
Void::Async::OperationOptions options)
{
co_return co_await wait(managed.child(), std::move(options));
}
Void::Coro::Task<Void::Result::Result<void, Void::Result::Error>>
ProcessManager::close_and_join(Void::Async::OperationOptions options)
{
std::shared_ptr<Void::Async::OperationState<void>> op;
{
std::lock_guard lk{impl_->mu};
impl_->closing = true;
if (impl_->waits.empty()) {
impl_->stop_worker = true;
impl_->cv.notify_all();
co_return {};
}
op = Void::Async::OperationState<void>::create(
options,
&impl_->executor,
Void::Async::StopBehavior::settle_cancelled);
op->acquire_backend_ref();
impl_->close_waiters.push_back(op);
impl_->cv.notify_all();
}
auto res = co_await op->awaitable(&impl_->executor);
std::lock_guard lk{impl_->mu};
impl_->stop_worker = true;
impl_->cv.notify_all();
co_return res;
}
std::size_t ProcessManager::active_children() const noexcept
{
std::lock_guard lk{impl_->mu};
return impl_->active_slots;
}
bool ProcessManager::closed() const noexcept
{
std::lock_guard lk{impl_->mu};
return impl_->closing;
}
} // namespace Void::SystemAsync
+648
View File
@@ -0,0 +1,648 @@
#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
+7
View File
@@ -0,0 +1,7 @@
void_add_module(SystemAsync
INTERNAL_DEPS System Async IO Time Functional LogState
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/System/AsyncProcess.hpp
Void/System/AsyncWatcher.hpp
)