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