feat(io): add positional File workers, sync, bounded shutdown core, and epoll D1 fixes (S-IO-03)

This commit is contained in:
faumaray committed 2026-12-01 10:15:03 +03:00
1 parent b2c84114fe
commit 1e752da590
8 files changed
+5000 -325

No files matched your search

+51
View File
@@ -3,15 +3,19 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <vector>
namespace Void::IO
@@ -23,6 +27,7 @@ namespace detail
{
class StreamState;
class FileState;
enum class Direction {
read,
@@ -73,6 +78,52 @@ public:
[[nodiscard]] virtual Void::Result::Result<void> shutdown_and_join() = 0;
[[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0;
// ── Positional files (bounded worker pool shared by every backend) ──────
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
open_file(const std::filesystem::path& path, const FileOpenOptions& options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
adopt_file_fd(int fd) = 0;
[[nodiscard]] virtual Void::Result::Result<void> start_file_workers() = 0;
[[nodiscard]] virtual Void::Result::Result<std::size_t>
run_file_work(std::size_t max_requests) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_file_read(const std::shared_ptr<FileState>& file,
std::uint64_t offset,
std::span<std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_file_write(const std::shared_ptr<FileState>& file,
std::uint64_t offset,
std::span<const std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_file_sync(const std::shared_ptr<FileState>& file,
SyncMode mode,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_file_close(const std::shared_ptr<FileState>& file,
Async::OperationOptions options) = 0;
// ── Bounded shutdown core ────────────────────────────────────────────────
// Idempotent: closes admission, cancels queued requests and records stop
// intent for active ones, then wakes the poller. Never completes,
// dispatches or frees anything itself.
virtual void begin_shutdown() noexcept = 0;
// Drives shutdown until complete, the injected-clock deadline passes or
// `stop` fires; the latter two return the current report with
// complete == false (not an error). Returns
// Async::make_async_error(AdmissionError::self_join) on one of this
// backend's file workers or inside one of its poll turns.
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
std::optional<Void::Time::MonotonicClock::time_point> deadline,
std::stop_token stop) = 0;
[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0;
// No owned operations, file requests or in-flight syscalls remain.
[[nodiscard]] virtual bool quiescent() const noexcept = 0;
// Driver::~Driver only: begin + advance to completion (blocking).
virtual void teardown_blocking() noexcept = 0;
// Mock inspection / test-only control hooks (returns nullptr on non-mock backends).
[[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; }
};
+53
View File
@@ -2,6 +2,7 @@
#include <Void/Async/Executor.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
@@ -9,10 +10,12 @@
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <memory_resource>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <utility>
@@ -56,6 +59,22 @@ private:
detail::MockBackend* backend_{nullptr};
};
// True on any Driver's file-worker thread (never on poll or executor threads).
[[nodiscard]] bool is_io_worker_thread() noexcept;
// The Driver owns no thread except its optional file workers. One thread at a
// time runs a poll_once turn (the poll owner); a concurrent or reentrant
// poll_once returns IoErrorCode::busy without touching any descriptor.
//
// Lifetime rules:
// - The executor must outlive the Driver. Resume tickets produced by
// shutdown/teardown are dispatched to it after poll ownership is released,
// so an owned executor must not be joined before Driver teardown.
// - ~Driver is the only blocking teardown: it begins shutdown, waits for
// in-flight syscalls and file requests, joins file workers, closes file and
// operation descriptors and delivers every pending result exactly once.
// Destroying a Driver on one of its file workers or inside one of its poll
// turns is a programmer error: it prints a diagnostic and terminates.
class Driver
{
public:
@@ -92,9 +111,43 @@ public:
std::optional<std::chrono::nanoseconds> max_wait = std::chrono::nanoseconds{0});
void wake() noexcept;
// Equivalent to begin_shutdown().
void request_stop() noexcept;
// Blocks until shutdown is complete (shutdown with no deadline or stop).
// Returns self_join on a file worker or inside a poll turn of this Driver.
[[nodiscard]] Void::Result::Result<void> shutdown_and_join();
// ── Positional files ─────────────────────────────────────────────────────
[[nodiscard]] Void::Result::Result<File> open_file(
const std::filesystem::path& path, FileOpenOptions options = {});
// Takes ownership of `fd` only on success.
[[nodiscard]] Void::Result::Result<File> adopt_file_fd(int fd);
// Starts IoLimits::file_workers threads once (0 = none, manual stepping).
// A second call is invalid_argument; after shutdown begins it is closed; a
// failed start joins the workers already started and may be retried.
[[nodiscard]] Void::Result::Result<void> start_file_workers();
// Runs up to `max_requests` queued file syscalls on the calling thread and
// queues their results for the next poll turn; busy while workers run.
[[nodiscard]] Void::Result::Result<std::size_t> run_file_work(std::size_t max_requests = 1);
// ── Bounded shutdown ─────────────────────────────────────────────────────
// Idempotent; closes admission, cancels queued requests, records stop
// intent for active ones and wakes the poller. Never blocks or frees.
void begin_shutdown() noexcept { backend_->begin_shutdown(); }
// Advances shutdown until complete, or until options.deadline (judged by
// clock()) or options.stop, which return complete == false with every
// listed resource retained. Repeatable.
[[nodiscard]] Void::Result::Result<DriverShutdownReport> shutdown(
Async::OperationOptions options)
{
return backend_->advance_shutdown(options.deadline, std::move(options.stop));
}
[[nodiscard]] bool quiescent() const noexcept { return backend_->quiescent(); }
[[nodiscard]] bool shutdown_complete() const noexcept
{
return backend_->shutdown_complete();
}
private:
Driver(std::shared_ptr<detail::DriverBackend> backend,
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker) noexcept;
+198
View File
@@ -0,0 +1,198 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/IO/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <span>
#include <utility>
namespace Void::IO
{
// Flags for Driver::open_file. read+write maps to O_RDWR, write-only to
// O_WRONLY and read-only to O_RDONLY; neither read nor write, truncate without
// write, or exclusive without create is invalid_argument. O_CLOEXEC is always
// set and open(2) runs on the calling thread with ordinary path semantics.
struct FileOpenOptions {
bool read{true};
bool write{false};
bool create{false};
bool truncate{false};
bool exclusive{false};
std::uint32_t mode{0600};
};
enum class SyncMode : std::uint8_t {
data, // fdatasync
full // fsync
};
// Result of one positional-file syscall: on success `error == 0` and `value`
// holds the byte count (0 for sync/close); on failure `error` is the errno.
struct FileSyscallResult {
std::int64_t value{0};
int error{0};
};
// Injectable syscall shim used by the Driver's file workers. The base class
// is the native implementation (one syscall per call, no EINTR retry; the
// Driver retries EINTR). An override runs on file workers or inside
// Driver::run_file_work(); it must not call Driver, Executor or File APIs, and
// it must outlive Driver teardown (teardown closes remaining fds through it).
class FileSyscalls
{
public:
virtual ~FileSyscalls() = default;
[[nodiscard]] virtual FileSyscallResult pread(
int fd, std::span<std::byte> buf, std::uint64_t offset) noexcept;
[[nodiscard]] virtual FileSyscallResult pwrite(
int fd, std::span<const std::byte> buf, std::uint64_t offset) noexcept;
[[nodiscard]] virtual FileSyscallResult sync(int fd, SyncMode mode) noexcept;
[[nodiscard]] virtual FileSyscallResult close(int fd) noexcept;
[[nodiscard]] static FileSyscalls& native() noexcept;
};
namespace detail
{
class FileState;
} // namespace detail
// Move-only handle to a positional file owned by a Driver. Requests run on
// the Driver's bounded file workers (or Driver::run_file_work) and are
// delivered only by a poll turn.
//
// - Writes and syncs on one File run in admission order, one at a time; reads
// may run concurrently and are unordered relative to writes.
// - A queued request that is stopped or expires completes cancelled/timeout
// without a syscall. An active request keeps its buffer and reports the
// syscall's actual outcome even after stop or expiry.
// - Dropping a File with requests in flight defers the close until they have
// been delivered; the close never blocks the dropping thread.
// - Unlike ByteStream::close_and_join (which consumes the stream at once),
// File::close_and_join waits for the file's queued and active requests,
// never cancels them, and invalidates the File only on success. On deadline
// or stop it returns incomplete_shutdown and the File stays valid but
// closing (new requests fail with closed; a repeated call waits again).
// - After Driver teardown every request fails with closed without a syscall
// and close_and_join succeeds immediately.
class File
{
public:
File() noexcept;
File(File&& other) noexcept;
File& operator=(File&& other) noexcept;
~File();
File(const File&) = delete;
File& operator=(const File&) = delete;
[[nodiscard]] bool valid() const noexcept { return state_ != nullptr; }
[[nodiscard]] DescriptorId id() const noexcept;
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(
std::uint64_t offset, std::span<std::byte> buf, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(
std::uint64_t offset, std::span<const std::byte> buf, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(
std::uint64_t offset, BufferLease& lease, Async::OperationOptions options = {})
{
auto res = co_await read_at(offset, 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_at_owned(
std::uint64_t offset, const BufferLease& lease, Async::OperationOptions options = {})
{
co_return co_await write_at(offset, lease.readable(), std::move(options));
}
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(
SyncMode mode = SyncMode::full, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(
Async::OperationOptions options = {});
private:
friend class Driver; // the only producer of open Files
explicit File(std::shared_ptr<detail::FileState> state) noexcept;
void release_handle() noexcept;
std::shared_ptr<detail::FileState> state_{};
};
// Composed positional transfers mirroring read_exact/write_all: the offset
// advances with each chunk and one deadline/stop applies to the whole call.
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
read_exact_at(File& file,
std::uint64_t offset,
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_at stopped before completion")}};
}
const auto chunk = co_await file.read_at(offset + total, 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_at finished")}};
}
}
co_return total;
}
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
write_all_at(File& file,
std::uint64_t offset,
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_at stopped before completion")}};
}
const auto chunk = co_await file.write_at(offset + total, buf.subspan(total), options);
if (!chunk.has_value()) {
co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}};
}
if (chunk->bytes == 0) {
// A zero-byte pwrite with bytes remaining makes no progress; report
// it instead of looping.
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::os_error, "pwrite made no progress in write_all_at")}};
}
total += chunk->bytes;
}
co_return total;
}
} // namespace Void::IO
+30
View File
@@ -7,6 +7,7 @@
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <memory_resource>
#include <new>
@@ -120,6 +121,11 @@ struct IoLimits {
IoErrorCode::invalid_argument,
"IoLimits descriptor, operation, control, and turn bounds must be non-zero")};
}
if (limits.max_file_queue == 0) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument,
"IoLimits max_file_queue must be non-zero")};
}
return {};
}
@@ -129,9 +135,18 @@ enum class BackendPreference {
mock
};
class FileSyscalls;
struct BackendOptions {
IoLimits limits{};
BackendPreference preference{BackendPreference::auto_native};
// Borrowed positional-file syscall shim (nullptr = FileSyscalls::native()).
// It runs on file workers or in run_file_work(), must not call Driver,
// Executor or File APIs, and must outlive Driver teardown.
FileSyscalls* file_syscalls{nullptr};
// Called before each file worker thread is created with its index; an
// error aborts start_file_workers() exactly like a thread-creation failure.
std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
};
struct DescriptorId {
@@ -150,6 +165,21 @@ struct DriverTelemetry {
std::uint64_t turns{0};
std::uint64_t wakeups{0};
std::uint64_t stale_events_ignored{0};
std::size_t queued_file_requests{0};
std::size_t active_file_requests{0};
std::size_t file_workers_running{0};
// Cancel/expiry/shutdown paths that met an already-retired op and skipped it.
std::uint64_t duplicate_completions_ignored{0};
};
// Snapshot returned by Driver::shutdown(). `complete == false` means the
// bounded call expired (deadline or stop) and everything listed is retained.
struct DriverShutdownReport {
bool complete{false};
std::size_t pending_operations{0};
std::size_t active_file_requests{0};
std::size_t open_descriptors{0};
std::size_t retained_buffer_bytes{0};
};
namespace detail