feat(IO): add portable Driver/ByteStream/BufferLease, mock backend, and Linux epoll driver (S-IO-01, S-IO-02)

This commit is contained in:
faumaray committed 2026-11-24 09:31:13 +03:00
1 parent 9918ed4760
commit 673bb7e8b4
10 files changed
+3071

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace Void::IO
{
class ByteStream;
namespace detail
{
class StreamState;
enum class Direction {
read,
write
};
class DriverBackend : public std::enable_shared_from_this<DriverBackend>
{
public:
virtual ~DriverBackend() = default;
[[nodiscard]] virtual BackendPreference kind() const noexcept = 0;
[[nodiscard]] virtual const IoLimits& limits() const noexcept = 0;
[[nodiscard]] virtual const Void::Time::MonotonicClock& clock() const noexcept = 0;
[[nodiscard]] virtual Async::Executor& executor() noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<StreamState>>
create_mock_stream() = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<StreamState>>
adopt_fd(int fd) = 0;
[[nodiscard]] virtual Void::Result::Result<
std::pair<std::shared_ptr<StreamState>, std::shared_ptr<StreamState>>>
create_socket_pair() = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_read(const std::shared_ptr<StreamState>& stream,
std::span<std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_write(const std::shared_ptr<StreamState>& stream,
std::span<const std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_close(const std::shared_ptr<StreamState>& stream,
Async::OperationOptions options) = 0;
virtual void on_stream_destroyed(const DescriptorId& id) noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<std::size_t>
poll_once(std::optional<std::chrono::nanoseconds> max_wait) = 0;
virtual void wake() noexcept = 0;
virtual void request_stop() noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<void> shutdown_and_join() = 0;
[[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0;
// Mock inspection / test-only control hooks (returns nullptr on non-mock backends).
[[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; }
};
class StreamState
{
public:
StreamState(std::weak_ptr<DriverBackend> backend, DescriptorId id) noexcept
: backend_(std::move(backend))
, id_(id)
{
}
~StreamState()
{
if (!explicitly_closed_.load(std::memory_order_acquire)) {
if (auto b = backend_.lock()) {
b->on_stream_destroyed(id_);
}
}
}
StreamState(const StreamState&) = delete;
StreamState& operator=(const StreamState&) = delete;
[[nodiscard]] DescriptorId id() const noexcept { return id_; }
[[nodiscard]] std::shared_ptr<DriverBackend> lock_backend() const noexcept
{
return backend_.lock();
}
void mark_explicit_closed() noexcept
{
explicitly_closed_.store(true, std::memory_order_release);
}
private:
std::weak_ptr<DriverBackend> backend_{};
DescriptorId id_{};
std::atomic<bool> explicitly_closed_{false};
};
} // namespace detail
} // namespace Void::IO
+107
View File
@@ -0,0 +1,107 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <optional>
#include <span>
#include <string>
#include <utility>
namespace Void::IO
{
class MockController
{
public:
explicit MockController(detail::MockBackend* backend) noexcept
: backend_(backend)
{
}
[[nodiscard]] std::size_t pending_read_count(const ByteStream& stream) const noexcept;
[[nodiscard]] std::size_t pending_write_count(const ByteStream& stream) const noexcept;
[[nodiscard]] std::optional<std::uint64_t>
try_acquire_read(const ByteStream& stream);
[[nodiscard]] std::optional<std::uint64_t>
try_acquire_write(const ByteStream& stream);
[[nodiscard]] bool is_stop_requested(std::uint64_t token) const noexcept;
[[nodiscard]] std::size_t requested_size(std::uint64_t token) const noexcept;
bool finish_read_data(std::uint64_t token,
std::span<const std::byte> data,
bool eof = false);
bool finish_write_bytes(std::uint64_t token, std::size_t bytes);
bool finish_error(std::uint64_t token, Void::Result::Error err);
bool finish_cancelled(std::uint64_t token, std::string msg = "Operation cancelled");
bool complete_read(const ByteStream& stream,
std::span<const std::byte> data,
bool eof = false);
bool complete_write(const ByteStream& stream, std::size_t bytes);
bool fail_read(const ByteStream& stream, Void::Result::Error err);
bool fail_write(const ByteStream& stream, Void::Result::Error err);
private:
detail::MockBackend* backend_{nullptr};
};
class Driver
{
public:
~Driver();
Driver(const Driver&) = delete;
Driver& operator=(const Driver&) = delete;
Driver(Driver&&) = delete;
Driver& operator=(Driver&&) = delete;
[[nodiscard]] static Void::Result::Result<std::unique_ptr<Driver>> create(
Async::Executor& executor,
BackendOptions options = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
std::pmr::memory_resource* resource = std::pmr::get_default_resource());
[[nodiscard]] BackendPreference active_backend() const noexcept;
[[nodiscard]] const IoLimits& limits() const noexcept;
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
[[nodiscard]] Async::Executor& executor() noexcept;
[[nodiscard]] DriverTelemetry telemetry() const noexcept;
[[nodiscard]] Void::Result::Result<BufferLease> allocate_buffer(std::size_t bytes);
[[nodiscard]] Void::Result::Result<ByteStream> create_mock_stream();
[[nodiscard]] MockController* mock_controller() noexcept;
[[nodiscard]] Void::Result::Result<ByteStream> adopt_fd(int fd);
[[nodiscard]] Void::Result::Result<std::pair<ByteStream, ByteStream>>
create_socket_pair();
[[nodiscard]] Void::Result::Result<std::size_t> poll_once(
std::optional<std::chrono::nanoseconds> max_wait = std::chrono::nanoseconds{0});
void wake() noexcept;
void request_stop() noexcept;
[[nodiscard]] Void::Result::Result<void> shutdown_and_join();
private:
Driver(std::shared_ptr<detail::DriverBackend> backend,
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker) noexcept;
std::shared_ptr<detail::DriverBackend> backend_{};
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker_{};
std::unique_ptr<MockController> mock_controller_{};
};
} // namespace Void::IO
+182
View File
@@ -0,0 +1,182 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/Types.hpp>
#include <cstddef>
#include <expected>
#include <memory>
#include <span>
#include <utility>
namespace Void::IO
{
class ByteStream
{
public:
ByteStream() noexcept = default;
explicit ByteStream(std::shared_ptr<detail::StreamState> state) noexcept
: state_(std::move(state))
{
}
ByteStream(ByteStream&&) noexcept = default;
ByteStream& operator=(ByteStream&&) noexcept = default;
ByteStream(const ByteStream&) = delete;
ByteStream& operator=(const ByteStream&) = delete;
[[nodiscard]] bool valid() const noexcept { return state_ != nullptr; }
[[nodiscard]] DescriptorId id() const noexcept
{
return state_ ? state_->id() : DescriptorId{};
}
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_some(
std::span<std::byte> buf, Async::OperationOptions options = {})
{
if (buf.empty()) {
co_return Transfer{0, false};
}
auto state = state_;
if (!state) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "ByteStream is closed or moved-from")};
}
auto backend = state->lock_backend();
if (!backend) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver no longer alive")};
}
auto submitted = backend->submit_read(state, buf, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_some(
std::span<const std::byte> buf, Async::OperationOptions options = {})
{
if (buf.empty()) {
co_return Transfer{0, false};
}
auto state = state_;
if (!state) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "ByteStream is closed or moved-from")};
}
auto backend = state->lock_backend();
if (!backend) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver no longer alive")};
}
auto submitted = backend->submit_write(state, buf, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_some_owned(
BufferLease& lease, Async::OperationOptions options = {})
{
auto res = co_await read_some(lease.writable(), std::move(options));
if (res.has_value()) {
lease.set_valid_bytes(res->bytes);
}
co_return res;
}
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_some_owned(
const BufferLease& lease, Async::OperationOptions options = {})
{
co_return co_await write_some(lease.readable(), std::move(options));
}
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(
Async::OperationOptions options = {})
{
auto state = std::move(state_);
if (!state) {
co_return {};
}
state->mark_explicit_closed();
auto backend = state->lock_backend();
if (!backend) {
co_return {};
}
auto submitted = backend->submit_close(state, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
private:
std::shared_ptr<detail::StreamState> state_{};
};
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
read_exact(ByteStream& stream,
std::span<std::byte> buf,
Async::OperationOptions options = {})
{
std::size_t total = 0;
while (total < buf.size()) {
if (options.stop.stop_requested()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::cancelled, "read_exact stopped before completion")}};
}
const auto chunk = co_await stream.read_some(buf.subspan(total), options);
if (!chunk.has_value()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
chunk.error()}};
}
total += chunk->bytes;
if (total < buf.size() && chunk->eof) {
co_return std::unexpected{ComposedTransferError{
total,
true,
make_io_error(IoErrorCode::eof, "Unexpected EOF before read_exact finished")}};
}
}
co_return total;
}
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
write_all(ByteStream& stream,
std::span<const std::byte> buf,
Async::OperationOptions options = {})
{
std::size_t total = 0;
while (total < buf.size()) {
if (options.stop.stop_requested()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::cancelled, "write_all stopped before completion")}};
}
const auto chunk = co_await stream.write_some(buf.subspan(total), options);
if (!chunk.has_value()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
chunk.error()}};
}
total += chunk->bytes;
}
co_return total;
}
} // namespace Void::IO
+292
View File
@@ -0,0 +1,292 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <new>
#include <span>
#include <string>
#include <system_error>
#include <utility>
namespace Void::IO
{
enum class IoErrorCode : std::int32_t {
none = 0,
busy = 1,
closed = 2,
cancelled = 3,
timeout = 4,
overloaded = 5,
unsupported = 6,
eof = 7,
invalid_argument = 8,
os_error = 9,
incomplete_shutdown = 10,
exhausted = 11
};
[[nodiscard]] inline Void::Result::Error make_io_error(
IoErrorCode code,
std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::io;
switch (code) {
case IoErrorCode::none:
kind = ErrorKind::internal;
break;
case IoErrorCode::busy:
case IoErrorCode::incomplete_shutdown:
kind = ErrorKind::conflict;
break;
case IoErrorCode::closed:
case IoErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case IoErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case IoErrorCode::overloaded:
kind = ErrorKind::overloaded;
break;
case IoErrorCode::unsupported:
kind = ErrorKind::unsupported;
break;
case IoErrorCode::eof:
case IoErrorCode::os_error:
kind = ErrorKind::io;
break;
case IoErrorCode::invalid_argument:
kind = ErrorKind::invalid_argument;
break;
case IoErrorCode::exhausted:
kind = ErrorKind::exhausted;
break;
}
const ErrorCode domain_code{
Void::Result::kIoErrorDomain,
static_cast<std::int32_t>(code)};
return Error{kind, std::move(message), domain_code, sys_err};
}
struct Transfer {
std::size_t bytes{0};
bool eof{false};
[[nodiscard]] constexpr bool operator==(const Transfer&) const noexcept = default;
};
struct ComposedTransferError {
std::size_t bytes_transferred{0};
bool eof{false};
Void::Result::Error error{};
};
struct IoLimits {
std::size_t max_descriptors{4096};
std::size_t max_operations{8192};
std::size_t max_timers{4096};
std::size_t max_owned_buffer_bytes{16ULL * 1024ULL * 1024ULL};
std::size_t max_control_submissions{1024};
std::size_t max_ready_per_turn{64};
std::size_t max_bytes_per_turn{65536};
std::size_t file_workers{4};
std::size_t max_file_queue{256};
};
[[nodiscard]] inline Void::Result::Result<void> validate_limits(const IoLimits& limits)
{
if (limits.max_descriptors == 0 ||
limits.max_operations == 0 ||
limits.max_control_submissions == 0 ||
limits.max_ready_per_turn == 0 ||
limits.max_bytes_per_turn == 0) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument,
"IoLimits descriptor, operation, control, and turn bounds must be non-zero")};
}
return {};
}
enum class BackendPreference {
auto_native,
epoll,
mock
};
struct BackendOptions {
IoLimits limits{};
BackendPreference preference{BackendPreference::auto_native};
};
struct DescriptorId {
std::uint32_t slot{0};
std::uint32_t generation{0};
[[nodiscard]] constexpr bool valid() const noexcept { return generation != 0; }
[[nodiscard]] constexpr bool operator==(const DescriptorId&) const noexcept = default;
};
struct DriverTelemetry {
std::size_t active_descriptors{0};
std::size_t active_operations{0};
std::size_t owned_buffer_bytes{0};
std::size_t borrowed_buffer_bytes{0};
std::uint64_t turns{0};
std::uint64_t wakeups{0};
std::uint64_t stale_events_ignored{0};
};
namespace detail
{
struct OwnedBufferTracker {
explicit OwnedBufferTracker(std::pmr::memory_resource* res,
std::size_t byte_limit) noexcept
: resource(res ? res : std::pmr::get_default_resource())
, limit(byte_limit)
{
}
std::pmr::memory_resource* resource{nullptr};
std::size_t limit{0};
std::atomic<std::size_t> live_bytes{0};
};
} // namespace detail
// Move-only PMR-backed buffer lease carrying shared quota accounting. Safe to
// outlive the Driver as long as the backing memory_resource remains valid.
class BufferLease
{
public:
BufferLease() noexcept = default;
~BufferLease()
{
reset();
}
BufferLease(BufferLease&& other) noexcept
: tracker_(std::move(other.tracker_))
, data_(std::exchange(other.data_, nullptr))
, capacity_(std::exchange(other.capacity_, 0))
, valid_bytes_(std::exchange(other.valid_bytes_, 0))
{
}
BufferLease& operator=(BufferLease&& other) noexcept
{
if (this != &other) {
reset();
tracker_ = std::move(other.tracker_);
data_ = std::exchange(other.data_, nullptr);
capacity_ = std::exchange(other.capacity_, 0);
valid_bytes_ = std::exchange(other.valid_bytes_, 0);
}
return *this;
}
BufferLease(const BufferLease&) = delete;
BufferLease& operator=(const BufferLease&) = delete;
[[nodiscard]] static Void::Result::Result<BufferLease> allocate(
const std::shared_ptr<detail::OwnedBufferTracker>& tracker,
std::size_t bytes)
{
if (!tracker) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument, "Null OwnedBufferTracker")};
}
if (bytes == 0) {
BufferLease lease;
lease.tracker_ = tracker;
return lease;
}
std::size_t cur = tracker->live_bytes.load(std::memory_order_acquire);
for (;;) {
if (bytes > tracker->limit || cur > tracker->limit - bytes) {
return std::unexpected{make_io_error(
IoErrorCode::exhausted,
"Owned IO buffer lease quota exhausted")};
}
if (tracker->live_bytes.compare_exchange_weak(
cur,
cur + bytes,
std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
void* raw = nullptr;
try {
raw = tracker->resource->allocate(bytes, alignof(std::max_align_t));
} catch (...) {
tracker->live_bytes.fetch_sub(bytes, std::memory_order_acq_rel);
return std::unexpected{make_io_error(
IoErrorCode::exhausted,
"PMR allocation failed for IO BufferLease")};
}
BufferLease lease;
lease.tracker_ = tracker;
lease.data_ = static_cast<std::byte*>(raw);
lease.capacity_ = bytes;
lease.valid_bytes_ = bytes;
return lease;
}
void reset() noexcept
{
if (data_ != nullptr && tracker_) {
tracker_->resource->deallocate(data_, capacity_, alignof(std::max_align_t));
tracker_->live_bytes.fetch_sub(capacity_, std::memory_order_acq_rel);
}
data_ = nullptr;
capacity_ = 0;
valid_bytes_ = 0;
tracker_.reset();
}
[[nodiscard]] explicit operator bool() const noexcept { return tracker_ != nullptr; }
[[nodiscard]] std::size_t size() const noexcept { return capacity_; }
[[nodiscard]] std::size_t valid_bytes() const noexcept { return valid_bytes_; }
[[nodiscard]] bool empty() const noexcept { return capacity_ == 0; }
void set_valid_bytes(std::size_t n) noexcept
{
valid_bytes_ = std::min(n, capacity_);
}
[[nodiscard]] std::span<std::byte> writable() noexcept
{
return (data_ != nullptr) ? std::span<std::byte>{data_, capacity_} : std::span<std::byte>{};
}
[[nodiscard]] std::span<const std::byte> readable() const noexcept
{
return (data_ != nullptr) ? std::span<const std::byte>{data_, valid_bytes_}
: std::span<const std::byte>{};
}
private:
std::shared_ptr<detail::OwnedBufferTracker> tracker_{};
std::byte* data_{nullptr};
std::size_t capacity_{0};
std::size_t valid_bytes_{0};
};
} // namespace Void::IO