feat(IO): add portable Driver/ByteStream/BufferLease, mock backend, and Linux epoll driver (S-IO-01, S-IO-02)
This commit is contained in:
1 parent
9918ed4760
commit
673bb7e8b4
10 files changed
+3071
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(IO
|
||||
INTERNAL_DEPS Core Functional Time Memory Async
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidIOOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS IO)
|
||||
|
||||
add_executable(void_io_only_consumer main.cpp)
|
||||
target_link_libraries(void_io_only_consumer PRIVATE Void::IO)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME VoidIOOnlyConsumer COMMAND void_io_only_consumer)
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/IO/Driver.hpp>
|
||||
#include <Void/IO/Stream.hpp>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Async::ManualExecutor exec;
|
||||
auto drv_res = Void::IO::Driver::create(
|
||||
exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock});
|
||||
if (!drv_res.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
auto& driver = **drv_res;
|
||||
auto buf = driver.allocate_buffer(32);
|
||||
auto stream = driver.create_mock_stream();
|
||||
if (!buf.has_value() || !stream.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
std::memset(buf->writable().data(), 'x', buf->size());
|
||||
#ifdef __linux__
|
||||
auto ep = Void::IO::Driver::create(
|
||||
exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::epoll});
|
||||
if (!ep.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
auto pair_res = (*ep)->create_socket_pair();
|
||||
if (!pair_res.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
@@ -106,6 +106,11 @@ if(_has_unicode)
|
||||
run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_io IO Async Memory Time Functional Core)
|
||||
if(_has_io)
|
||||
run_consumer(IOOnly "${install_prefix}" "IOOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,509 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/IO/Driver.hpp>
|
||||
#include <Void/IO/Stream.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <memory_resource>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using Void::Async::ManualExecutor;
|
||||
using Void::Async::OperationOptions;
|
||||
using Void::Async::TaskScope;
|
||||
using Void::IO::BackendOptions;
|
||||
using Void::IO::BackendPreference;
|
||||
using Void::IO::BufferLease;
|
||||
using Void::IO::ByteStream;
|
||||
using Void::IO::ComposedTransferError;
|
||||
using Void::IO::Driver;
|
||||
using Void::IO::IoErrorCode;
|
||||
using Void::IO::IoLimits;
|
||||
using Void::IO::Transfer;
|
||||
using Void::IO::read_exact;
|
||||
using Void::IO::write_all;
|
||||
|
||||
[[nodiscard]] std::span<const std::byte> as_bytes(std::string_view sv) noexcept
|
||||
{
|
||||
return std::as_bytes(std::span<const char>{sv.data(), sv.size()});
|
||||
}
|
||||
|
||||
void pump_driver_and_exec(Driver& driver, ManualExecutor& exec, TaskScope& scope)
|
||||
{
|
||||
for (int iter = 0; iter < 512 && 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);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test io_mock_limits_zero_len_busy_and_buffer_leases()
|
||||
{
|
||||
ManualExecutor exec;
|
||||
Void::Time::ManualClock clock{
|
||||
Void::Time::MonotonicClock::time_point{std::chrono::seconds{100}}};
|
||||
|
||||
// Invalid limits rejected cleanly before creating Driver
|
||||
{
|
||||
auto bad = Driver::create(
|
||||
exec,
|
||||
BackendOptions{
|
||||
.limits = IoLimits{.max_descriptors = 0},
|
||||
.preference = BackendPreference::mock,
|
||||
},
|
||||
clock);
|
||||
Void::Testing::expect(!bad.has_value());
|
||||
Void::Testing::expect(
|
||||
bad.error().code().value ==
|
||||
static_cast<std::int32_t>(IoErrorCode::invalid_argument));
|
||||
}
|
||||
|
||||
BufferLease outliving_lease;
|
||||
{
|
||||
auto drv_res = Driver::create(
|
||||
exec,
|
||||
BackendOptions{
|
||||
.limits = IoLimits{
|
||||
.max_descriptors = 1,
|
||||
.max_operations = 2,
|
||||
.max_owned_buffer_bytes = 64,
|
||||
},
|
||||
.preference = BackendPreference::mock,
|
||||
},
|
||||
clock);
|
||||
Void::Testing::require(drv_res.has_value());
|
||||
Driver& driver = **drv_res;
|
||||
Void::Testing::expect(driver.active_backend() == BackendPreference::mock);
|
||||
|
||||
// Descriptor quota enforced
|
||||
auto s1_res = driver.create_mock_stream();
|
||||
Void::Testing::require(s1_res.has_value());
|
||||
ByteStream s1 = std::move(*s1_res);
|
||||
|
||||
auto s2_res = driver.create_mock_stream();
|
||||
Void::Testing::expect(!s2_res.has_value());
|
||||
Void::Testing::expect(
|
||||
s2_res.error().code().value ==
|
||||
static_cast<std::int32_t>(IoErrorCode::overloaded));
|
||||
|
||||
// BufferLease quota enforced & safely returned on release
|
||||
auto b1 = driver.allocate_buffer(48);
|
||||
Void::Testing::require(b1.has_value());
|
||||
Void::Testing::expect_eq(driver.telemetry().owned_buffer_bytes, std::size_t{48});
|
||||
|
||||
auto b2 = driver.allocate_buffer(32);
|
||||
Void::Testing::expect(!b2.has_value());
|
||||
Void::Testing::expect(
|
||||
b2.error().code().value ==
|
||||
static_cast<std::int32_t>(IoErrorCode::exhausted));
|
||||
|
||||
outliving_lease = std::move(*b1);
|
||||
std::memset(outliving_lease.writable().data(), 0x5A, outliving_lease.size());
|
||||
Void::Testing::expect_eq(driver.telemetry().owned_buffer_bytes, std::size_t{48});
|
||||
|
||||
// Zero-length read & write succeed immediately without hitting mock controller
|
||||
TaskScope scope{exec};
|
||||
Void::Result::Result<Transfer> zero_r{};
|
||||
Void::Result::Result<Transfer> zero_w{};
|
||||
auto run_zero = [](ByteStream* st,
|
||||
Void::Result::Result<Transfer>* r_out,
|
||||
Void::Result::Result<Transfer>* w_out) -> Void::Coro::Task<void> {
|
||||
*r_out = co_await st->read_some({});
|
||||
*w_out = co_await st->write_some({});
|
||||
};
|
||||
Void::Testing::require(scope.spawn(run_zero(&s1, &zero_r, &zero_w)).has_value());
|
||||
Void::Testing::require(scope.join_pumping().has_value());
|
||||
Void::Testing::require(zero_r.has_value());
|
||||
Void::Testing::require(zero_w.has_value());
|
||||
Void::Testing::expect_eq(zero_r->bytes, std::size_t{0});
|
||||
Void::Testing::expect(!zero_r->eof);
|
||||
Void::Testing::expect_eq(zero_w->bytes, std::size_t{0});
|
||||
|
||||
// Opposite-direction read+write allowed concurrently; second read returns busy!
|
||||
std::array<std::byte, 8> rbuf1{};
|
||||
std::array<std::byte, 8> rbuf2{};
|
||||
const std::string payload = "hello!";
|
||||
Void::Result::Result<Transfer> r1_res{};
|
||||
Void::Result::Result<Transfer> r2_res{};
|
||||
Void::Result::Result<Transfer> w1_res{};
|
||||
|
||||
auto do_read = [](ByteStream* st,
|
||||
std::span<std::byte> buf,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(buf);
|
||||
};
|
||||
auto do_write = [](ByteStream* st,
|
||||
std::span<const std::byte> buf,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->write_some(buf);
|
||||
};
|
||||
|
||||
TaskScope dir_scope{exec};
|
||||
Void::Testing::require(dir_scope.spawn(do_read(&s1, rbuf1, &r1_res)).has_value());
|
||||
Void::Testing::require(dir_scope.spawn(do_write(&s1, as_bytes(payload), &w1_res)).has_value());
|
||||
Void::Testing::require(dir_scope.spawn(do_read(&s1, rbuf2, &r2_res)).has_value());
|
||||
(void)exec.drain();
|
||||
|
||||
// Second read must have settled with busy while first read and first write remain pending!
|
||||
Void::Testing::expect(!r2_res.has_value());
|
||||
Void::Testing::expect(
|
||||
r2_res.error().code().value == static_cast<std::int32_t>(IoErrorCode::busy));
|
||||
auto* ctrl = driver.mock_controller();
|
||||
Void::Testing::require(ctrl != nullptr);
|
||||
Void::Testing::expect_eq(ctrl->pending_read_count(s1), std::size_t{1});
|
||||
Void::Testing::expect_eq(ctrl->pending_write_count(s1), std::size_t{1});
|
||||
Void::Testing::expect_eq(driver.telemetry().active_operations, std::size_t{2});
|
||||
|
||||
Void::Testing::expect(ctrl->complete_read(s1, as_bytes("abc"), false));
|
||||
Void::Testing::expect(ctrl->complete_write(s1, payload.size()));
|
||||
Void::Testing::require(dir_scope.join_pumping().has_value());
|
||||
|
||||
Void::Testing::require(r1_res.has_value());
|
||||
Void::Testing::expect_eq(r1_res->bytes, std::size_t{3});
|
||||
Void::Testing::require(w1_res.has_value());
|
||||
Void::Testing::expect_eq(w1_res->bytes, payload.size());
|
||||
Void::Testing::expect_eq(driver.telemetry().active_operations, std::size_t{0});
|
||||
Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{0});
|
||||
|
||||
// Pre-expired deadline rejects cleanly
|
||||
Void::Result::Result<Transfer> exp_res{};
|
||||
auto expired_read = [](ByteStream* st,
|
||||
std::span<std::byte> buf,
|
||||
Void::Time::MonotonicClock::time_point dl,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(buf, OperationOptions{.deadline = dl});
|
||||
};
|
||||
TaskScope exp_scope{exec};
|
||||
Void::Testing::require(
|
||||
exp_scope.spawn(expired_read(&s1, rbuf1, clock.now(), &exp_res)).has_value());
|
||||
Void::Testing::require(exp_scope.join_pumping().has_value());
|
||||
Void::Testing::expect(!exp_res.has_value());
|
||||
Void::Testing::expect(
|
||||
exp_res.error().code().value == static_cast<std::int32_t>(IoErrorCode::timeout));
|
||||
}
|
||||
|
||||
// `outliving_lease` still valid and safely destructs after Driver was destroyed!
|
||||
Void::Testing::expect_eq(outliving_lease.size(), std::size_t{48});
|
||||
Void::Testing::expect_eq(static_cast<std::uint8_t>(outliving_lease.readable()[0]), std::uint8_t{0x5A});
|
||||
outliving_lease.reset();
|
||||
}
|
||||
|
||||
Void::Testing::Test io_mock_stop_completion_races_and_clock_timeout()
|
||||
{
|
||||
ManualExecutor exec;
|
||||
Void::Time::ManualClock clock{
|
||||
Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}};
|
||||
auto drv_res = Driver::create(
|
||||
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
|
||||
Void::Testing::require(drv_res.has_value());
|
||||
Driver& driver = **drv_res;
|
||||
auto* ctrl = driver.mock_controller();
|
||||
Void::Testing::require(ctrl != nullptr);
|
||||
|
||||
auto s_res = driver.create_mock_stream();
|
||||
Void::Testing::require(s_res.has_value());
|
||||
ByteStream stream = std::move(*s_res);
|
||||
|
||||
// 1. Stop arrives BEFORE backend begins executing -> cancelled cleanly on poll_once
|
||||
{
|
||||
std::stop_source ssrc;
|
||||
std::array<std::byte, 16> buf{};
|
||||
int resumes = 0;
|
||||
Void::Result::Result<Transfer> res{};
|
||||
auto task = [](ByteStream* st,
|
||||
std::span<std::byte> b,
|
||||
std::stop_token tok,
|
||||
int* cnt,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(b, OperationOptions{.stop = tok});
|
||||
++(*cnt);
|
||||
};
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope.spawn(task(&stream, buf, ssrc.get_token(), &resumes, &res)).has_value());
|
||||
(void)exec.drain();
|
||||
Void::Testing::expect_eq(resumes, 0);
|
||||
|
||||
ssrc.request_stop();
|
||||
Void::Testing::require(driver.poll_once().has_value());
|
||||
Void::Testing::require(scope.join_pumping().has_value());
|
||||
Void::Testing::expect_eq(resumes, 1);
|
||||
Void::Testing::expect(!res.has_value());
|
||||
Void::Testing::expect(
|
||||
res.error().code().value == static_cast<std::int32_t>(IoErrorCode::cancelled));
|
||||
}
|
||||
|
||||
// 2. Stop arrives WHILE mock backend holds ref (mid-flight) -> MUST NOT resume or
|
||||
// release borrowed buffer until backend explicitly finishes!
|
||||
{
|
||||
std::stop_source ssrc;
|
||||
std::array<std::byte, 16> buf{};
|
||||
int resumes = 0;
|
||||
Void::Result::Result<Transfer> res{};
|
||||
auto task = [](ByteStream* st,
|
||||
std::span<std::byte> b,
|
||||
std::stop_token tok,
|
||||
int* cnt,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(b, OperationOptions{.stop = tok});
|
||||
++(*cnt);
|
||||
};
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope.spawn(task(&stream, buf, ssrc.get_token(), &resumes, &res)).has_value());
|
||||
(void)exec.drain();
|
||||
|
||||
const auto tok = ctrl->try_acquire_read(stream);
|
||||
Void::Testing::require(tok.has_value());
|
||||
Void::Testing::expect_eq(ctrl->requested_size(*tok), std::size_t{16});
|
||||
|
||||
// Fire stop + poll_once + exec.drain while backend still owns buffer!
|
||||
ssrc.request_stop();
|
||||
Void::Testing::require(driver.poll_once().has_value());
|
||||
(void)exec.drain();
|
||||
Void::Testing::expect_eq(resumes, 0);
|
||||
Void::Testing::expect(ctrl->is_stop_requested(*tok));
|
||||
Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{16});
|
||||
|
||||
// Backend actually finished transferring 5 bytes despite stop intent!
|
||||
Void::Testing::expect(ctrl->finish_read_data(*tok, as_bytes("hello"), false));
|
||||
Void::Testing::require(scope.join_pumping().has_value());
|
||||
Void::Testing::expect_eq(resumes, 1);
|
||||
Void::Testing::require(res.has_value());
|
||||
Void::Testing::expect_eq(res->bytes, std::size_t{5});
|
||||
Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{0});
|
||||
}
|
||||
|
||||
// 3. Armed operation deadline expires solely on ManualClock::advance + poll_once
|
||||
{
|
||||
std::array<std::byte, 8> buf{};
|
||||
Void::Result::Result<Transfer> res{};
|
||||
const auto dl = clock.now() + std::chrono::seconds{5};
|
||||
auto task = [](ByteStream* st,
|
||||
std::span<std::byte> b,
|
||||
Void::Time::MonotonicClock::time_point d,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(b, OperationOptions{.deadline = d});
|
||||
};
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(scope.spawn(task(&stream, buf, dl, &res)).has_value());
|
||||
(void)exec.drain();
|
||||
Void::Testing::require(clock.advance(std::chrono::seconds{5}).has_value());
|
||||
Void::Testing::require(driver.poll_once().has_value());
|
||||
Void::Testing::require(scope.join_pumping().has_value());
|
||||
Void::Testing::expect(!res.has_value());
|
||||
Void::Testing::expect(
|
||||
res.error().code().value == static_cast<std::int32_t>(IoErrorCode::timeout));
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
Void::Testing::Test io_epoll_socketpair_fragmented_half_close_and_fd_reuse()
|
||||
{
|
||||
ManualExecutor exec;
|
||||
auto drv_res = Driver::create(
|
||||
exec,
|
||||
BackendOptions{
|
||||
.limits = IoLimits{.max_descriptors = 8, .max_bytes_per_turn = 16},
|
||||
.preference = BackendPreference::epoll,
|
||||
});
|
||||
Void::Testing::require(drv_res.has_value());
|
||||
Driver& driver = **drv_res;
|
||||
Void::Testing::expect(driver.active_backend() == BackendPreference::epoll);
|
||||
|
||||
// Idle driver with no pending write must not spin
|
||||
const auto idle_work = driver.poll_once(std::chrono::milliseconds{0});
|
||||
Void::Testing::require(idle_work.has_value());
|
||||
Void::Testing::expect_eq(*idle_work, std::size_t{0});
|
||||
|
||||
// 1. Fragmented multi-turn transfer with max_bytes_per_turn == 16 & BufferLease roundtrip
|
||||
auto pair_res = driver.create_socket_pair();
|
||||
Void::Testing::require(pair_res.has_value());
|
||||
ByteStream a = std::move(pair_res->first);
|
||||
ByteStream b = std::move(pair_res->second);
|
||||
const auto a_orig_id = a.id();
|
||||
|
||||
const std::string expected_msg(73, 'V'); // Forces >= 5 turns at 16B/turn
|
||||
std::string recv_msg(expected_msg.size(), '\0');
|
||||
std::expected<std::size_t, ComposedTransferError> write_res{0};
|
||||
std::expected<std::size_t, ComposedTransferError> read_res{0};
|
||||
|
||||
auto writer_coro = [](ByteStream* st,
|
||||
std::span<const std::byte> data,
|
||||
std::expected<std::size_t, ComposedTransferError>* out)
|
||||
-> Void::Coro::Task<void> {
|
||||
*out = co_await write_all(*st, data);
|
||||
};
|
||||
auto reader_coro = [](ByteStream* st,
|
||||
std::span<std::byte> data,
|
||||
std::expected<std::size_t, ComposedTransferError>* out)
|
||||
-> Void::Coro::Task<void> {
|
||||
*out = co_await read_exact(*st, data);
|
||||
};
|
||||
|
||||
{
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope.spawn(writer_coro(&a, as_bytes(expected_msg), &write_res)).has_value());
|
||||
Void::Testing::require(
|
||||
scope.spawn(reader_coro(
|
||||
&b,
|
||||
std::as_writable_bytes(std::span{recv_msg.data(), recv_msg.size()}),
|
||||
&read_res))
|
||||
.has_value());
|
||||
pump_driver_and_exec(driver, exec, scope);
|
||||
}
|
||||
Void::Testing::require(write_res.has_value());
|
||||
Void::Testing::require(read_res.has_value());
|
||||
Void::Testing::expect_eq(*write_res, expected_msg.size());
|
||||
Void::Testing::expect_eq(*read_res, expected_msg.size());
|
||||
Void::Testing::expect_eq(recv_msg, expected_msg);
|
||||
|
||||
// 2. Half-close / peer close drains already-buffered bytes BEFORE reporting EOF!
|
||||
auto lease_w = driver.allocate_buffer(10);
|
||||
auto lease_r = driver.allocate_buffer(16);
|
||||
Void::Testing::require(lease_w.has_value());
|
||||
Void::Testing::require(lease_r.has_value());
|
||||
std::memcpy(lease_w->writable().data(), "buffered!!", 10);
|
||||
|
||||
Void::Result::Result<Transfer> owned_w{};
|
||||
Void::Result::Result<Transfer> owned_r1{};
|
||||
Void::Result::Result<Transfer> owned_r2{};
|
||||
Void::Result::Result<void> close_a{};
|
||||
|
||||
auto write_then_close = [](ByteStream* st,
|
||||
BufferLease* lw,
|
||||
Void::Result::Result<Transfer>* w_out,
|
||||
Void::Result::Result<void>* c_out) -> Void::Coro::Task<void> {
|
||||
*w_out = co_await st->write_some_owned(*lw);
|
||||
*c_out = co_await st->close_and_join();
|
||||
};
|
||||
auto drain_then_eof = [](ByteStream* st,
|
||||
BufferLease* lr,
|
||||
Void::Result::Result<Transfer>* r1_out,
|
||||
Void::Result::Result<Transfer>* r2_out) -> Void::Coro::Task<void> {
|
||||
*r1_out = co_await st->read_some_owned(*lr);
|
||||
*r2_out = co_await st->read_some(lr->writable());
|
||||
};
|
||||
|
||||
{
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope.spawn(write_then_close(&a, &(*lease_w), &owned_w, &close_a)).has_value());
|
||||
// Wait for write+close to push data into kernel buffer before reading from b
|
||||
for (int i = 0; i < 64 && !close_a.has_value(); ++i) {
|
||||
(void)exec.drain();
|
||||
(void)driver.poll_once(std::chrono::milliseconds{1});
|
||||
(void)exec.drain();
|
||||
}
|
||||
Void::Testing::require(
|
||||
scope.spawn(drain_then_eof(&b, &(*lease_r), &owned_r1, &owned_r2)).has_value());
|
||||
pump_driver_and_exec(driver, exec, scope);
|
||||
}
|
||||
|
||||
Void::Testing::require(owned_w.has_value());
|
||||
Void::Testing::expect(close_a.has_value());
|
||||
Void::Testing::require(owned_r1.has_value());
|
||||
Void::Testing::expect_eq(owned_r1->bytes, std::size_t{10});
|
||||
Void::Testing::expect(!owned_r1->eof);
|
||||
Void::Testing::expect_eq(
|
||||
std::string_view{
|
||||
reinterpret_cast<const char*>(lease_r->readable().data()),
|
||||
lease_r->readable().size()},
|
||||
std::string_view{"buffered!!"});
|
||||
Void::Testing::require(owned_r2.has_value());
|
||||
Void::Testing::expect_eq(owned_r2->bytes, std::size_t{0});
|
||||
Void::Testing::expect(owned_r2->eof);
|
||||
|
||||
// 3. Closing `b` frees slots and reusing a new socketpair bumps descriptor generation!
|
||||
{
|
||||
TaskScope scope{exec};
|
||||
Void::Result::Result<void> close_b{};
|
||||
auto closer = [](ByteStream* st, Void::Result::Result<void>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->close_and_join();
|
||||
};
|
||||
Void::Testing::require(scope.spawn(closer(&b, &close_b)).has_value());
|
||||
pump_driver_and_exec(driver, exec, scope);
|
||||
Void::Testing::expect(close_b.has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(driver.telemetry().active_descriptors, std::size_t{0});
|
||||
|
||||
auto reused = driver.create_socket_pair();
|
||||
Void::Testing::require(reused.has_value());
|
||||
// At least one endpoint reuses slot index with strictly bumped generation > 1!
|
||||
const bool bumped =
|
||||
(reused->first.id().generation > a_orig_id.generation) ||
|
||||
(reused->second.id().generation > a_orig_id.generation);
|
||||
Void::Testing::expect(bumped);
|
||||
}
|
||||
|
||||
Void::Testing::Test io_epoll_cross_thread_wake_poll_and_stop_tsan()
|
||||
{
|
||||
ManualExecutor exec;
|
||||
auto drv_res = Driver::create(exec, BackendOptions{.preference = BackendPreference::epoll});
|
||||
Void::Testing::require(drv_res.has_value());
|
||||
Driver& driver = **drv_res;
|
||||
|
||||
auto pair_res = driver.create_socket_pair();
|
||||
Void::Testing::require(pair_res.has_value());
|
||||
ByteStream a = std::move(pair_res->first);
|
||||
ByteStream b = std::move(pair_res->second);
|
||||
|
||||
std::atomic<bool> stop_poller{false};
|
||||
std::thread poller([&] {
|
||||
while (!stop_poller.load(std::memory_order_acquire)) {
|
||||
(void)driver.poll_once(std::chrono::milliseconds{2});
|
||||
}
|
||||
});
|
||||
|
||||
std::stop_source stop_src;
|
||||
std::array<std::byte, 32> buf{};
|
||||
Void::Result::Result<Transfer> cancelled_r{};
|
||||
auto wait_read = [](ByteStream* st,
|
||||
std::span<std::byte> b_span,
|
||||
std::stop_token tok,
|
||||
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
|
||||
*out = co_await st->read_some(b_span, OperationOptions{.stop = tok});
|
||||
};
|
||||
|
||||
TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope.spawn(wait_read(&a, buf, stop_src.get_token(), &cancelled_r)).has_value());
|
||||
while (exec.drain() > 0) {
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
stop_src.request_stop();
|
||||
while (scope.active_count() > 0) {
|
||||
if (exec.drain() == 0) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
}
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::expect(!cancelled_r.has_value());
|
||||
Void::Testing::expect(
|
||||
cancelled_r.error().code().value == static_cast<std::int32_t>(IoErrorCode::cancelled));
|
||||
|
||||
stop_poller.store(true, std::memory_order_release);
|
||||
driver.wake();
|
||||
poller.join();
|
||||
(void)b.valid();
|
||||
}
|
||||
#endif // __linux__
|
||||
Reference in new issue
Block a user