Files
Library/include/Void/IO/Driver.hpp
T

240 lines
10 KiB
C++

#pragma once
#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>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <memory_resource>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#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};
};
// 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:
~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;
// 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();
}
/// Runs the poll loop until `stop` is requested, `shutdown_complete()` becomes
/// true, or an unrecoverable error occurs. Retries `IoErrorCode::busy` and
/// idle mock turns with short stop-aware waits so the loop never busy-spins.
[[nodiscard]] Void::Result::Result<std::size_t> run(
std::stop_token stop,
std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5})
{
if (max_wait < std::chrono::nanoseconds{0}) {
max_wait = std::chrono::nanoseconds{0};
}
auto wait_stop_aware = [&](std::chrono::nanoseconds budget) {
if (budget <= std::chrono::nanoseconds{0} ||
stop.stop_requested() || shutdown_complete()) {
return;
}
std::mutex mu;
std::condition_variable cv;
std::stop_callback cb(stop, [&]() noexcept {
std::lock_guard lk{mu};
cv.notify_all();
});
std::unique_lock lk{mu};
auto remaining = budget;
constexpr auto kSlice =
std::chrono::nanoseconds{std::chrono::milliseconds{1}};
while (remaining > std::chrono::nanoseconds{0} &&
!stop.stop_requested() && !shutdown_complete()) {
const auto step = std::min(remaining, kSlice);
cv.wait_for(lk, step, [&]() {
return stop.stop_requested() || shutdown_complete();
});
remaining -= step;
}
};
std::size_t total = 0;
std::size_t consecutive_fast_zero = 0;
while (!stop.stop_requested() && !shutdown_complete()) {
const auto poll_start = std::chrono::steady_clock::now();
auto res = poll_once(max_wait);
const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start;
if (!res.has_value()) {
if (res.error().code().domain == Void::Result::kIoErrorDomain &&
res.error().code().value ==
static_cast<std::int32_t>(IoErrorCode::busy)) {
consecutive_fast_zero = 0;
const auto busy_slice =
max_wait > std::chrono::nanoseconds{0}
? std::min(max_wait,
std::chrono::nanoseconds{
std::chrono::milliseconds{1}})
: std::chrono::nanoseconds{
std::chrono::microseconds{200}};
wait_stop_aware(busy_slice);
continue;
}
return std::unexpected{std::move(res.error())};
}
total += *res;
if (*res == 0 && max_wait > std::chrono::nanoseconds{0} &&
poll_elapsed < max_wait) {
const auto remain = std::chrono::duration_cast<std::chrono::nanoseconds>(
max_wait - poll_elapsed);
if (active_backend() == BackendPreference::mock) {
wait_stop_aware(remain);
} else if (++consecutive_fast_zero >= 2) {
wait_stop_aware(std::min(
remain,
std::chrono::nanoseconds{std::chrono::milliseconds{1}}));
}
} else {
consecutive_fast_zero = 0;
}
}
return total;
}
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