diff --git a/include/Void/System/AsyncProcess.hpp b/include/Void/System/AsyncProcess.hpp new file mode 100644 index 0000000..592a4cc --- /dev/null +++ b/include/Void/System/AsyncProcess.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +struct ProcessManagerOptions { + std::size_t max_active_children{64}; + std::size_t max_pending_spawns{128}; + std::chrono::milliseconds default_kill_grace{std::chrono::milliseconds{2000}}; +}; + +class ProcessManager; + +class ManagedChild +{ +public: + ManagedChild() noexcept = default; + ~ManagedChild() noexcept; + + ManagedChild(const ManagedChild&) = delete; + ManagedChild& operator=(const ManagedChild&) = delete; + ManagedChild(ManagedChild&&) noexcept; + ManagedChild& operator=(ManagedChild&&) noexcept; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] Void::Process::Child& child() noexcept { return child_; } + [[nodiscard]] const Void::Process::Child& child() const noexcept + { + return child_; + } + + void release_slot() noexcept; + +private: + friend class ProcessManager; + struct SlotGuard; + + Void::Process::Child child_{}; + std::shared_ptr slot_token_{}; +}; + +class ProcessManager +{ +public: + struct Impl; + + explicit ProcessManager( + Void::IO::Driver& driver, + Void::Async::Executor& executor, + ProcessManagerOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + ~ProcessManager() noexcept; + + ProcessManager(const ProcessManager&) = delete; + ProcessManager& operator=(const ProcessManager&) = delete; + ProcessManager(ProcessManager&&) = delete; + ProcessManager& operator=(ProcessManager&&) = delete; + + [[nodiscard]] Void::Result::Result + spawn(const Void::Process::SpawnOptions& options); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + communicate(Void::Process::Child& child, + std::string stdin_data = {}, + Void::Process::CaptureLimits limits = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + communicate(ManagedChild& managed, + std::string stdin_data = {}, + Void::Process::CaptureLimits limits = {}, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + wait(Void::Process::Child& child, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + wait(ManagedChild& managed, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task> + close_and_join(Void::Async::OperationOptions options = {}); + + [[nodiscard]] std::size_t active_children() const noexcept; + [[nodiscard]] bool closed() const noexcept; + +private: + std::shared_ptr impl_; +}; + +} // namespace Void::SystemAsync diff --git a/include/Void/System/AsyncWatcher.hpp b/include/Void/System/AsyncWatcher.hpp new file mode 100644 index 0000000..92895c0 --- /dev/null +++ b/include/Void/System/AsyncWatcher.hpp @@ -0,0 +1,116 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SystemAsync +{ + +enum class WatchEventKind { + created, + modified, + deleted, + replaced_inode, + symlink_changed, + permission_denied, + rescan_required, +}; + +struct WatchEvent { + WatchEventKind kind{WatchEventKind::modified}; + std::filesystem::path path{}; + bool exists{false}; + std::uint64_t dev{0}; + std::uint64_t ino{0}; + std::uint64_t size{0}; + int sys_errno{0}; +}; + +struct WatcherLimits { + std::size_t max_watched_paths{1024}; + std::size_t max_queued_events{256}; + std::chrono::milliseconds poll_interval{std::chrono::milliseconds{250}}; + int debounce_polls{1}; +}; + +struct WatchPathOptions { + std::optional allowed_root{}; + bool allow_symlink{false}; +}; + +using WatchCallback = std::function; +using ErrorSink = std::function; + +class WatcherService; + +class WatchSubscription +{ +public: + WatchSubscription() noexcept = default; + ~WatchSubscription() noexcept; + + WatchSubscription(const WatchSubscription&) = delete; + WatchSubscription& operator=(const WatchSubscription&) = delete; + WatchSubscription(WatchSubscription&&) noexcept; + WatchSubscription& operator=(WatchSubscription&&) noexcept; + + [[nodiscard]] bool active() const noexcept; + [[nodiscard]] Void::Result::Result + close_and_join(); + +private: + friend class WatcherService; + + struct Token; + std::shared_ptr token_; +}; + +class WatcherService +{ +public: + struct Impl; + + explicit WatcherService( + Void::Async::Executor& executor, + WatcherLimits limits = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + ErrorSink error_sink = {}, + bool start_background_thread = false); + + ~WatcherService() noexcept; + + WatcherService(const WatcherService&) = delete; + WatcherService& operator=(const WatcherService&) = delete; + WatcherService(WatcherService&&) = delete; + WatcherService& operator=(WatcherService&&) = delete; + + [[nodiscard]] Void::Result::Result + watch(const std::filesystem::path& path, + WatchCallback callback, + WatchPathOptions options = {}); + + void poll_once(); + + [[nodiscard]] std::size_t watch_count() const noexcept; + [[nodiscard]] std::size_t queued_event_count() const noexcept; + + [[nodiscard]] Void::Result::Result shutdown(); + +private: + std::shared_ptr impl_; +}; + +} // namespace Void::SystemAsync diff --git a/src/SystemAsync/AsyncProcess.cpp b/src/SystemAsync/AsyncProcess.cpp new file mode 100644 index 0000000..7ff29e0 --- /dev/null +++ b/src/SystemAsync/AsyncProcess.cpp @@ -0,0 +1,781 @@ +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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(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 pump_stdin_task( + Void::IO::Driver* driver, + Void::IO::ByteStream stream, + std::shared_ptr st, + std::string stdin_data, + std::stop_token ext_stop, + std::optional 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 pump_read_task( + Void::IO::Driver* driver, + Void::IO::ByteStream stream, + std::shared_ptr st, + bool is_stdout, + std::stop_token ext_stop, + std::optional 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> op{}; + bool escalate_immediately{false}; + int phase{0}; // 0 = waiting/running, 1 = SIGTERM sent + std::chrono::milliseconds grace{std::chrono::milliseconds{2000}}; + std::optional deadline{}; + Void::Time::MonotonicClock::time_point kill_deadline{}; + bool done{false}; +}; + +} // namespace + +struct ProcessManager::Impl : public std::enable_shared_from_this { + 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 waits{}; + std::vector>> 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 tickets; + std::vector>> + 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 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(driver, executor, options, clock)) +{ +} + +ProcessManager::~ProcessManager() noexcept = default; + +Void::Result::Result + 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(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> + wait_for_reap_async( + std::shared_ptr 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::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> + 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 { + 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(); + st->limits = limits; + + struct ForwardStop { + std::shared_ptr state; + void operator()() const noexcept { state->stop_src.request_stop(); } + }; + std::optional> 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 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> + 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> + 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> + ProcessManager::wait(ManagedChild& managed, + Void::Async::OperationOptions options) +{ + co_return co_await wait(managed.child(), std::move(options)); +} + +Void::Coro::Task> + ProcessManager::close_and_join(Void::Async::OperationOptions options) +{ + std::shared_ptr> 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::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 diff --git a/src/SystemAsync/AsyncWatcher.cpp b/src/SystemAsync/AsyncWatcher.cpp new file mode 100644 index 0000000..66a78f5 --- /dev/null +++ b/src/SystemAsync/AsyncWatcher.cpp @@ -0,0 +1,648 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(st.st_dev); + snap.ino = static_cast(st.st_ino); + snap.mode = static_cast(st.st_mode); + snap.size = static_cast(st.st_size); + snap.mtime_ns = + static_cast(st.st_mtim.tv_sec) * 1000000000LL + + static_cast(st.st_mtim.tv_nsec); + + if (snap.is_symlink) { + std::array 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(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 service{}; + + PathSnapshot accepted{}; + PathSnapshot pending{}; + int stable_polls{0}; + bool dirty{false}; + + bool active{true}; + bool delivery_scheduled{false}; + bool dispatching{false}; + std::deque queue{}; + std::mutex mu{}; + std::condition_variable cv{}; + + [[nodiscard]] Void::Result::Result + close_and_join(); +}; + +struct WatcherService::Impl + : public std::enable_shared_from_this { + 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> 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 deliver_subscription_events( + std::shared_ptr impl, + std::shared_ptr 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> 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> 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 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 + 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 + 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( + executor, limits, clock, std::move(error_sink))) +{ + if (start_background_thread) { + std::weak_ptr 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 + 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(); + 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 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(&impl_->executor)) { + (void)impl_->scope.join_pumping(*manual); + } + return {}; +} + +} // namespace Void::SystemAsync diff --git a/src/SystemAsync/module.cmake b/src/SystemAsync/module.cmake new file mode 100644 index 0000000..75d7068 --- /dev/null +++ b/src/SystemAsync/module.cmake @@ -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 +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 52da158..a8e4735 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -126,6 +126,16 @@ if(_has_system) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_system_async SystemAsync System Async IO Time Functional LogState) +if(_has_system_async) + run_consumer(SystemAsyncOnly "${install_prefix}" "SystemAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + has_modules(_has_obs_hooks ObservabilityHooks) if(_has_obs_hooks) run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps}) diff --git a/tests/package/SystemAsyncOnly/CMakeLists.txt b/tests/package/SystemAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..10ab475 --- /dev/null +++ b/tests/package/SystemAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSystemAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS SystemAsync) + +add_executable(void_system_async_only_consumer main.cpp) +target_link_libraries(void_system_async_only_consumer PRIVATE Void::SystemAsync) +target_compile_features(void_system_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SystemAsyncOnlyConsumer COMMAND void_system_async_only_consumer) diff --git a/tests/package/SystemAsyncOnly/main.cpp b/tests/package/SystemAsyncOnly/main.cpp new file mode 100644 index 0000000..ee9377a --- /dev/null +++ b/tests/package/SystemAsyncOnly/main.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +int main() +{ + Void::Async::ManualExecutor exec; + auto drv = Void::IO::Driver::create(exec); + if (!drv.has_value()) { + return 1; + } + Void::SystemAsync::ProcessManager mgr{**drv, exec}; + Void::SystemAsync::WatcherService watcher{exec}; + if (mgr.active_children() != 0 || watcher.watch_count() != 0) { + return 2; + } + (void)watcher.shutdown(); + (void)(*drv)->shutdown_and_join(); + return 0; +} diff --git a/tests/standalone/SystemAsync/SystemAsync.cpp b/tests/standalone/SystemAsync/SystemAsync.cpp new file mode 100644 index 0000000..ad5179c --- /dev/null +++ b/tests/standalone/SystemAsync/SystemAsync.cpp @@ -0,0 +1,357 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +void pump_loop(Void::IO::Driver& driver, + Void::Async::ManualExecutor& exec, + Void::Async::TaskScope& scope) +{ + for (int iter = 0; iter < 5000 && scope.active_count() > 0; ++iter) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + if (scope.active_count() > 0) { + (void)scope.join_pumping(exec); + } +} + +[[nodiscard]] Void::Coro::Task run_communicate_task( + Void::SystemAsync::ProcessManager* mgr, + Void::SystemAsync::ManagedChild* child, + std::string stdin_data, + Void::Process::CaptureLimits limits, + Void::Async::OperationOptions opts, + Void::Result::Result* + out) +{ + *out = co_await mgr->communicate( + *child, std::move(stdin_data), limits, std::move(opts)); +} + +[[nodiscard]] Void::Coro::Task run_close_join_task( + Void::SystemAsync::ProcessManager* mgr, + Void::Result::Result* out) +{ + *out = co_await mgr->close_and_join(); +} + +} // namespace + +Void::Testing::Test system_async_process_manager_duplex_overflow_escalation_and_close() +{ + Void::Async::ManualExecutor exec; + auto drv_res = Void::IO::Driver::create(exec); + require(drv_res.has_value()); + auto& driver = **drv_res; + + Void::SystemAsync::ProcessManager mgr{ + driver, + exec, + Void::SystemAsync::ProcessManagerOptions{ + .max_active_children = 2, + .default_kill_grace = std::chrono::milliseconds{40}, + }}; + + // 1. max_active_children slot cap enforced cleanly. + { + Void::Process::SpawnOptions sleep_opts; + sleep_opts.executable = VOID_PROCESS_HELPER_PATH; + sleep_opts.arguments = {"ignore-sigterm", "2000"}; + sleep_opts.kill_grace = std::chrono::milliseconds{20}; + auto c1 = mgr.spawn(sleep_opts); + auto c2 = mgr.spawn(sleep_opts); + require(c1.has_value() && c2.has_value()); + auto c3 = mgr.spawn(sleep_opts); + require(!c3.has_value()); + expect_eq(c3.error().code().value, + static_cast( + Void::System::SystemErrorCode::limit_exceeded)); + expect_eq(mgr.active_children(), std::size_t{2}); + } + expect_eq(mgr.active_children(), std::size_t{0}); + + // 2. Full-duplex 256 KiB async communicate via Void::IO without deadlock. + { + const std::size_t payload_bytes = 256ULL * 1024ULL; + Void::Process::SpawnOptions sim_opts; + sim_opts.executable = VOID_PROCESS_HELPER_PATH; + sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)}; + auto ch = mgr.spawn(sim_opts); + require(ch.has_value()); + + Void::Process::CaptureLimits lim; + lim.max_line_bytes = 512ULL * 1024ULL; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task( + &mgr, + &*ch, + std::string(payload_bytes, 'i'), + lim, + {}, + &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(out.has_value()); + expect(!out->timed_out); + expect_eq(out->status.code, 0); + expect_eq(out->out.size(), payload_bytes); + expect_eq(out->err.size(), payload_bytes); + } + + // 3. Overflow limit terminates child and returns output_limit. + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "0"}; + auto ch = mgr.spawn(flood_opts); + require(ch.has_value()); + + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 256; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task(&mgr, &*ch, {}, lim, {}, &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(!out.has_value()); + expect_eq(out.error().code().value, + static_cast( + Void::System::SystemErrorCode::output_limit)); + } + + // 4. SIGTERM-ignoring child escalates on OperationOptions deadline -> SIGKILL. + { + Void::Process::SpawnOptions sig_opts; + sig_opts.executable = VOID_PROCESS_HELPER_PATH; + sig_opts.arguments = {"ignore-sigterm", "10000"}; + sig_opts.kill_grace = std::chrono::milliseconds{30}; + auto ch = mgr.spawn(sig_opts); + require(ch.has_value()); + + Void::Async::OperationOptions opts{ + .deadline = Void::Time::SystemMonotonicClock::instance().now() + + std::chrono::milliseconds{60}}; + Void::Result::Result + out{std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::internal, "unset")}}; + Void::Async::TaskScope scope{exec}; + require(scope + .spawn(run_communicate_task( + &mgr, &*ch, {}, Void::Process::CaptureLimits{}, opts, &out)) + .has_value()); + pump_loop(driver, exec, scope); + require(out.has_value()); + expect(out->timed_out); + expect_eq(out->status.signal, SIGKILL); + } + + // 5. close_and_join closes admission and drains cleanly. + { + Void::Result::Result close_res; + Void::Async::TaskScope scope{exec}; + require(scope.spawn(run_close_join_task(&mgr, &close_res)).has_value()); + pump_loop(driver, exec, scope); + require(close_res.has_value()); + expect(mgr.closed()); + + Void::Process::SpawnOptions blocked_opts; + blocked_opts.executable = VOID_PROCESS_HELPER_PATH; + blocked_opts.arguments = {"exit", "0"}; + auto late = mgr.spawn(blocked_opts); + require(!late.has_value()); + expect_eq(late.error().code().value, + static_cast(Void::System::SystemErrorCode::busy)); + } + + (void)driver.shutdown_and_join(); +} + +Void::Testing::Test system_async_watcher_deterministic_events_overflow_and_join() +{ + Void::FileSystem::TempDir tmp{"void_w6a_watch_"}; + Void::FileSystem::TempDir outside{"void_w6a_out_"}; + Void::Time::ManualClock clock; + Void::Async::ManualExecutor exec; + + std::vector errors; + Void::SystemAsync::WatcherService svc{ + exec, + Void::SystemAsync::WatcherLimits{ + .max_watched_paths = 32, + .max_queued_events = 2, + .debounce_polls = 1, + }, + clock, + [&](const Void::Result::Error& err) { + errors.push_back(err.message()); + }, + /*start_background_thread=*/false}; + + // 1. Rejects path outside allowed_root and rejects forbidden symlinks. + const auto outside_file = outside / "secret.txt"; + require(Void::FileSystem::write_file(outside_file, "x").has_value()); + { + auto esc = svc.watch( + tmp.path() / ".." / outside.path().filename() / "secret.txt", + [](const Void::SystemAsync::WatchEvent&) {}, + Void::SystemAsync::WatchPathOptions{.allowed_root = tmp.path()}); + expect(!esc.has_value()); + expect_eq(esc.error().code().value, + static_cast( + Void::System::SystemErrorCode::permission_denied)); + } + + const auto sym_path = tmp / "forbidden_link"; + std::filesystem::create_symlink(outside_file, sym_path); + { + auto sym_rej = svc.watch( + sym_path, + [](const Void::SystemAsync::WatchEvent&) {}, + Void::SystemAsync::WatchPathOptions{.allow_symlink = false}); + expect(!sym_rej.has_value()); + expect_eq(sym_rej.error().code().value, + static_cast( + Void::System::SystemErrorCode::permission_denied)); + } + + // 2. Detects created -> replaced_inode -> deleted -> self_join -> close_and_join. + const auto target = tmp / "watched.cfg"; + std::vector kinds; + Void::SystemAsync::WatchSubscription* sub_ptr = nullptr; + std::optional self_join_err; + bool throw_on_next = false; + + auto sub_res = svc.watch( + target, + [&](const Void::SystemAsync::WatchEvent& ev) { + kinds.push_back(ev.kind); + if (throw_on_next) { + throw std::runtime_error("intentional watcher callback throw"); + } + if (sub_ptr != nullptr && + ev.kind == Void::SystemAsync::WatchEventKind::deleted) { + auto sj = sub_ptr->close_and_join(); + if (!sj.has_value()) { + self_join_err = sj.error(); + } + } + }, + Void::SystemAsync::WatchPathOptions{.allowed_root = tmp.path()}); + require(sub_res.has_value()); + sub_ptr = &*sub_res; + + require(Void::FileSystem::replace_file(target, "v1").has_value()); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 1); + expect(kinds[0] == Void::SystemAsync::WatchEventKind::created); + + require(Void::FileSystem::replace_file(target, "v2_longer").has_value()); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 2); + expect(kinds[1] == Void::SystemAsync::WatchEventKind::replaced_inode); + + std::filesystem::remove(target); + svc.poll_once(); + (void)exec.drain(); + require(kinds.size() == 3); + expect(kinds[2] == Void::SystemAsync::WatchEventKind::deleted); + require(self_join_err.has_value()); + expect_eq(self_join_err->code().value, + static_cast( + Void::System::SystemErrorCode::self_join)); + + // Callback exceptions are caught and routed to ErrorSink without crashing. + throw_on_next = true; + require(Void::FileSystem::replace_file(target, "v3").has_value()); + svc.poll_once(); + (void)exec.drain(); + expect_eq(errors.size(), std::size_t{1}); + throw_on_next = false; + + sub_ptr = nullptr; + expect(sub_res->close_and_join().has_value()); + expect_eq(svc.watch_count(), std::size_t{0}); + + // 3. Allowed symlink target change detected + queue overflow rescan_required. + std::vector sym_kinds; + const auto sym_ok = tmp / "allowed_link"; + std::filesystem::create_symlink("target_a", sym_ok); + auto sym_sub = svc.watch( + sym_ok, + [&](const Void::SystemAsync::WatchEvent& ev) { + sym_kinds.push_back(ev.kind); + }, + Void::SystemAsync::WatchPathOptions{.allow_symlink = true}); + require(sym_sub.has_value()); + + std::filesystem::remove(sym_ok); + std::filesystem::create_symlink("target_b", sym_ok); + svc.poll_once(); + (void)exec.drain(); + require(sym_kinds.size() == 1); + expect(sym_kinds[0] == Void::SystemAsync::WatchEventKind::symlink_changed); + + // Queue overflow across 3 watched paths when max_queued_events == 2 triggers rescan_required. + std::vector ov_kinds; + const auto f1 = tmp / "ov1"; + const auto f2 = tmp / "ov2"; + const auto f3 = tmp / "ov3"; + auto s1 = svc.watch(f1, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + auto s2 = svc.watch(f2, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + auto s3 = svc.watch(f3, [&](const auto& ev) { ov_kinds.push_back(ev.kind); }); + require(s1.has_value() && s2.has_value() && s3.has_value()); + + require(Void::FileSystem::write_file(f1, "1").has_value()); + require(Void::FileSystem::write_file(f2, "2").has_value()); + require(Void::FileSystem::write_file(f3, "3").has_value()); + svc.poll_once(); + (void)exec.drain(); + bool saw_rescan = false; + for (auto k : ov_kinds) { + if (k == Void::SystemAsync::WatchEventKind::rescan_required) { + saw_rescan = true; + } + } + expect(saw_rescan); + + expect(svc.shutdown().has_value()); +}