Merge issue-44-binary-session: binary subprocess session (closes #44)

This commit is contained in:
faumaray committed 2026-12-03 15:51:05 +03:00
commit 7cfd30e550
4 files changed
+1222

No files matched your search

+728
View File
@@ -92,6 +92,162 @@ Void::Result::Result<Child, Void::Result::Error> spawn(const SpawnOptions&)
"Process::spawn: not implemented on Windows")};
}
BinarySession::BinarySession(Child child, BinarySessionOptions options)
: child_(std::move(child)), options_(options)
{
}
BinarySession::~BinarySession() noexcept = default;
BinarySession::BinarySession(BinarySession&& other) noexcept
: child_(std::move(other.child_)),
stdin_(std::move(other.stdin_)),
stdout_(std::move(other.stdout_)),
stderr_(std::move(other.stderr_)),
stdout_buffer_(std::move(other.stdout_buffer_)),
stdout_offset_(std::exchange(other.stdout_offset_, 0)),
stderr_buffer_(std::move(other.stderr_buffer_)),
stderr_offset_(std::exchange(other.stderr_offset_, 0)),
stdout_eof_(other.stdout_eof_),
stderr_eof_(other.stderr_eof_),
stdin_closed_(other.stdin_closed_),
stdout_truncated_(other.stdout_truncated_),
stderr_truncated_(other.stderr_truncated_),
options_(other.options_),
cancelled_(other.cancelled_.exchange(false)),
status_(other.status_),
reaped_(other.reaped_)
{
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
BinarySession& BinarySession::operator=(BinarySession&& other) noexcept
{
if (this != &other) {
child_ = std::move(other.child_);
stdin_ = std::move(other.stdin_);
stdout_ = std::move(other.stdout_);
stderr_ = std::move(other.stderr_);
stdout_buffer_ = std::move(other.stdout_buffer_);
stdout_offset_ = std::exchange(other.stdout_offset_, 0);
stderr_buffer_ = std::move(other.stderr_buffer_);
stderr_offset_ = std::exchange(other.stderr_offset_, 0);
stdout_eof_ = other.stdout_eof_;
stderr_eof_ = other.stderr_eof_;
stdin_closed_ = other.stdin_closed_;
stdout_truncated_ = other.stdout_truncated_;
stderr_truncated_ = other.stderr_truncated_;
options_ = other.options_;
cancelled_.store(other.cancelled_.exchange(false));
status_ = other.status_;
reaped_ = other.reaped_;
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
return *this;
}
Void::Result::Result<BinarySession, Void::Result::Error>
BinarySession::spawn(const SpawnOptions&, BinarySessionOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession: not implemented on Windows")};
}
bool BinarySession::valid() const noexcept { return false; }
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::write_stdin(
std::span<const std::byte>, std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::io_error,
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::write_stdin: not implemented on Windows")}};
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stdout(
std::span<std::byte>, std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::io_error,
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::read_stdout: not implemented on Windows")}};
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stderr(
std::span<std::byte>, std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::io_error,
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::read_stderr: not implemented on Windows")}};
}
Void::Result::Result<void, Void::Result::Error> BinarySession::close_stdin()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::close_stdin: not implemented on Windows")};
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::wait(
std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::wait: not implemented on Windows")};
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::terminate(
std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession::terminate: not implemented on Windows")};
}
BinarySession::PollFill BinarySession::poll_fill(int,
std::span<const std::byte>,
std::size_t&,
bool)
{
PollFill result;
result.failure = BinaryFailureCode::io_error;
result.error = Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession: not implemented on Windows");
return result;
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stream(
bool, std::span<std::byte>, std::chrono::milliseconds, std::stop_token)
{
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::io_error,
Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::BinarySession: not implemented on Windows")}};
}
void BinarySession::note_exit() noexcept {}
Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child&,
std::string_view,
@@ -1327,6 +1483,578 @@ Void::Result::Result<Child, Void::Result::Error>
options.kill_grace};
}
BinarySession::BinarySession(Child child, BinarySessionOptions options)
: child_(std::move(child)),
stdin_(child_.take_stdin_fd()),
stdout_(child_.take_stdout_fd()),
stderr_(child_.take_stderr_fd()),
stdout_eof_(!stdout_.valid()),
stderr_eof_(!stderr_.valid()),
stdin_closed_(!stdin_.valid()),
options_(options)
{
options_.max_stdout_buffer = std::max<std::size_t>(1, options_.max_stdout_buffer);
options_.max_stderr_buffer = std::max<std::size_t>(1, options_.max_stderr_buffer);
if (stdin_.valid()) {
(void)set_nonblock(stdin_.get());
}
if (stdout_.valid()) {
(void)set_nonblock(stdout_.get());
}
if (stderr_.valid()) {
(void)set_nonblock(stderr_.get());
}
}
BinarySession::~BinarySession() noexcept = default;
BinarySession::BinarySession(BinarySession&& other) noexcept
: child_(std::move(other.child_)),
stdin_(std::move(other.stdin_)),
stdout_(std::move(other.stdout_)),
stderr_(std::move(other.stderr_)),
stdout_buffer_(std::move(other.stdout_buffer_)),
stdout_offset_(std::exchange(other.stdout_offset_, 0)),
stderr_buffer_(std::move(other.stderr_buffer_)),
stderr_offset_(std::exchange(other.stderr_offset_, 0)),
stdout_eof_(other.stdout_eof_),
stderr_eof_(other.stderr_eof_),
stdin_closed_(other.stdin_closed_),
stdout_truncated_(other.stdout_truncated_),
stderr_truncated_(other.stderr_truncated_),
options_(other.options_),
cancelled_(other.cancelled_.exchange(false)),
status_(other.status_),
reaped_(other.reaped_)
{
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
BinarySession& BinarySession::operator=(BinarySession&& other) noexcept
{
if (this != &other) {
child_ = std::move(other.child_);
stdin_ = std::move(other.stdin_);
stdout_ = std::move(other.stdout_);
stderr_ = std::move(other.stderr_);
stdout_buffer_ = std::move(other.stdout_buffer_);
stdout_offset_ = std::exchange(other.stdout_offset_, 0);
stderr_buffer_ = std::move(other.stderr_buffer_);
stderr_offset_ = std::exchange(other.stderr_offset_, 0);
stdout_eof_ = other.stdout_eof_;
stderr_eof_ = other.stderr_eof_;
stdin_closed_ = other.stdin_closed_;
stdout_truncated_ = other.stdout_truncated_;
stderr_truncated_ = other.stderr_truncated_;
options_ = other.options_;
cancelled_.store(other.cancelled_.exchange(false));
status_ = other.status_;
reaped_ = other.reaped_;
other.stdout_eof_ = true;
other.stderr_eof_ = true;
other.stdin_closed_ = true;
other.reaped_ = true;
}
return *this;
}
Void::Result::Result<BinarySession, Void::Result::Error>
BinarySession::spawn(const SpawnOptions& options, BinarySessionOptions session_options)
{
auto spawned = Process::spawn(options);
if (!spawned.has_value()) {
return std::unexpected{std::move(spawned.error())};
}
return BinarySession{std::move(*spawned), session_options};
}
bool BinarySession::valid() const noexcept { return child_.valid(); }
BinarySession::PollFill BinarySession::poll_fill(
int timeout_ms,
std::span<const std::byte> stdin_data,
std::size_t& stdin_written,
bool discard_on_full)
{
PollFill result;
std::array<struct pollfd, 3> pfds{};
nfds_t nfds = 0;
int stdin_index = -1;
int stdout_index = -1;
int stderr_index = -1;
if (!stdin_data.empty() && stdin_written < stdin_data.size() &&
!stdin_closed_ && stdin_.valid()) {
stdin_index = static_cast<int>(nfds);
pfds[nfds++] = {stdin_.get(), POLLOUT, 0};
}
const std::size_t stdout_used = stdout_buffer_.size() - stdout_offset_;
if (!stdout_eof_ && stdout_.valid() &&
(discard_on_full || stdout_used < options_.max_stdout_buffer)) {
stdout_index = static_cast<int>(nfds);
pfds[nfds++] = {stdout_.get(), POLLIN, 0};
}
const std::size_t stderr_used = stderr_buffer_.size() - stderr_offset_;
if (!stderr_eof_ && stderr_.valid() &&
(discard_on_full || stderr_used < options_.max_stderr_buffer)) {
stderr_index = static_cast<int>(nfds);
pfds[nfds++] = {stderr_.get(), POLLIN, 0};
}
if (nfds == 0) {
result.idle = true;
return result;
}
const int rc = ::poll(pfds.data(), nfds, timeout_ms);
if (rc < 0) {
if (errno == EINTR) {
return result;
}
const int err = errno;
result.failure = BinaryFailureCode::io_error;
result.error = Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::BinarySession: poll failed",
err);
return result;
}
if (rc == 0) {
return result;
}
if (stdin_index >= 0) {
const short revents = pfds[static_cast<std::size_t>(stdin_index)].revents;
if ((revents & POLLOUT) != 0) {
while (stdin_written < stdin_data.size()) {
int write_err = 0;
const ssize_t n = write_pipe_nosigpipe(stdin_.get(),
stdin_data.data() + stdin_written,
stdin_data.size() - stdin_written,
write_err);
if (n > 0) {
stdin_written += static_cast<std::size_t>(n);
continue;
}
if (n == 0) {
break;
}
if (n < 0 && (write_err == EAGAIN || write_err == EWOULDBLOCK)) {
break;
}
stdin_closed_ = true;
stdin_.reset();
result.stdin_broken = true;
break;
}
}
if (!result.stdin_broken &&
(revents & (POLLERR | POLLHUP | POLLNVAL)) != 0 &&
(revents & POLLOUT) == 0) {
stdin_closed_ = true;
stdin_.reset();
result.stdin_broken = true;
}
}
std::array<std::byte, 8192> chunk{};
auto service_read = [&](int index,
int fd,
std::vector<std::byte>& buffer,
std::size_t& offset,
bool& eof,
bool& truncated,
std::size_t cap) {
if (index < 0) {
return;
}
const short revents = pfds[static_cast<std::size_t>(index)].revents;
if ((revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)) == 0) {
return;
}
for (;;) {
const std::size_t used = buffer.size() - offset;
const std::size_t space = (cap > used) ? (cap - used) : 0;
if (space == 0 && !discard_on_full) {
break;
}
const std::size_t want =
discard_on_full ? chunk.size() : std::min(chunk.size(), space);
if (want == 0) {
break;
}
const ssize_t n = ::read(fd, chunk.data(), want);
if (n > 0) {
if (offset > 0 && offset == buffer.size()) {
buffer.clear();
offset = 0;
}
std::size_t take = static_cast<std::size_t>(n);
if (take > space) {
take = space;
truncated = true;
}
buffer.insert(buffer.end(), chunk.begin(), chunk.begin() + take);
continue;
}
if (n == 0) {
eof = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
eof = true;
result.failure = BinaryFailureCode::io_error;
result.error = Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::BinarySession: read failed",
err);
break;
}
if ((revents & (POLLHUP | POLLERR | POLLNVAL)) != 0 && !eof) {
eof = true;
}
};
service_read(stdout_index,
stdout_.get(),
stdout_buffer_,
stdout_offset_,
stdout_eof_,
stdout_truncated_,
options_.max_stdout_buffer);
service_read(stderr_index,
stderr_.get(),
stderr_buffer_,
stderr_offset_,
stderr_eof_,
stderr_truncated_,
options_.max_stderr_buffer);
return result;
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::write_stdin(
std::span<const std::byte> data,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::write_stdin: invalid session")}};
}
BinaryTransfer transfer;
if (data.empty()) {
return transfer;
}
if (stdin_closed_ || !stdin_.valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::BinarySession::write_stdin: stdin is closed")}};
}
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t written = 0;
while (written < data.size()) {
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::cancelled,
Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession::write_stdin: cancelled")}};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::timeout,
Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession::write_stdin: timed out")}};
}
int poll_timeout_ms = -1;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0) {
continue;
}
poll_timeout_ms =
static_cast<int>(std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
// Bound every wait so cancel() (which may come from another thread)
// and a stop request are observed promptly.
poll_timeout_ms =
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
auto filled = poll_fill(poll_timeout_ms, data, written, false);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{BinaryError{
written, false, filled.failure, std::move(filled.error)}};
}
if (filled.stdin_broken) {
return std::unexpected{BinaryError{
written,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::BinarySession::write_stdin: child closed stdin")}};
}
if (filled.idle) {
break;
}
}
transfer.bytes = written;
return transfer;
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stdout(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(true, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stderr(
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
return read_stream(false, out, timeout, stop);
}
Void::Result::Result<BinaryTransfer, BinaryError> BinarySession::read_stream(
bool is_stdout,
std::span<std::byte> out,
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!valid()) {
return std::unexpected{BinaryError{
0,
false,
BinaryFailureCode::closed,
Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession: invalid session")}};
}
BinaryTransfer transfer;
if (out.empty()) {
return transfer;
}
auto& buffer = is_stdout ? stdout_buffer_ : stderr_buffer_;
auto& offset = is_stdout ? stdout_offset_ : stderr_offset_;
bool& eof = is_stdout ? stdout_eof_ : stderr_eof_;
bool& truncated = is_stdout ? stdout_truncated_ : stderr_truncated_;
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
while ((buffer.size() - offset) == 0 && !eof) {
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{BinaryError{
0,
eof,
BinaryFailureCode::cancelled,
Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession: read cancelled")}};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{BinaryError{
0,
eof,
BinaryFailureCode::timeout,
Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession: read timed out")}};
}
int poll_timeout_ms = -1;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0) {
continue;
}
poll_timeout_ms =
static_cast<int>(std::min<long long>(remaining,
std::numeric_limits<int>::max()));
}
// Bound every wait so cancel() (which may come from another thread)
// and a stop request are observed promptly.
poll_timeout_ms =
(poll_timeout_ms < 0) ? 25 : std::min(poll_timeout_ms, 25);
std::span<const std::byte> no_stdin{};
std::size_t no_written = 0;
auto filled = poll_fill(poll_timeout_ms,
no_stdin,
no_written,
options_.truncate_output_on_overflow);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{BinaryError{
0, eof, filled.failure, std::move(filled.error)}};
}
if (filled.idle) {
break;
}
}
const std::size_t used = buffer.size() - offset;
if (used > 0) {
const std::size_t take = std::min(used, out.size());
std::copy_n(buffer.begin() + static_cast<std::ptrdiff_t>(offset),
take,
out.begin());
offset += take;
transfer.bytes = take;
if (offset == buffer.size()) {
buffer.clear();
offset = 0;
} else if (offset >= 65536 && offset * 2 >= buffer.size()) {
buffer.erase(buffer.begin(),
buffer.begin() + static_cast<std::ptrdiff_t>(offset));
offset = 0;
}
} else if (eof) {
transfer.eof = true;
note_exit();
transfer.exited = reaped_;
transfer.status = status_;
}
transfer.truncated = truncated;
return transfer;
}
void BinarySession::note_exit() noexcept
{
if (reaped_ || !child_.valid()) {
return;
}
auto waited = child_.try_wait();
if (waited.has_value() && waited->has_value()) {
status_ = **waited;
reaped_ = true;
}
}
Void::Result::Result<void, Void::Result::Error> BinarySession::close_stdin()
{
if (stdin_closed_) {
return {};
}
stdin_closed_ = true;
return stdin_.close();
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::wait(
std::chrono::milliseconds timeout,
std::stop_token stop)
{
if (!child_.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::wait: invalid session")};
}
if (reaped_) {
return status_;
}
const bool has_deadline = timeout.count() > 0;
const auto deadline = std::chrono::steady_clock::now() + timeout;
for (;;) {
auto waited = child_.try_wait();
if (!waited.has_value()) {
return std::unexpected{std::move(waited.error())};
}
if (waited->has_value()) {
status_ = **waited;
reaped_ = true;
return status_;
}
if (cancelled_.load(std::memory_order_acquire) || stop.stop_requested()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::cancelled,
"Process::BinarySession::wait: cancelled")};
}
if (has_deadline && std::chrono::steady_clock::now() >= deadline) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::BinarySession::wait: timed out")};
}
int poll_timeout_ms = 5;
if (has_deadline) {
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
poll_timeout_ms = static_cast<int>(std::clamp<long long>(
remaining, 1, static_cast<long long>(poll_timeout_ms)));
}
std::span<const std::byte> no_stdin{};
std::size_t no_written = 0;
auto filled = poll_fill(
poll_timeout_ms, no_stdin, no_written, options_.truncate_output_on_overflow);
if (filled.failure != BinaryFailureCode::none) {
return std::unexpected{std::move(filled.error)};
}
if (filled.idle) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
}
Void::Result::Result<ExitStatus, Void::Result::Error> BinarySession::terminate(
std::chrono::milliseconds grace)
{
if (!child_.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"Process::BinarySession::terminate: invalid session")};
}
auto terminated = child_.terminate(grace);
if (terminated.has_value()) {
status_ = *terminated;
reaped_ = true;
}
return terminated;
}
Void::Result::Result<CommunicateResult, Void::Result::Error>
communicate_blocking(Child& child,
std::string_view stdin_data,