feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter

This commit is contained in:
faumaray committed 2026-11-25 06:28:50 +03:00
1 parent 8a1c15f9c0
commit eb42228604
14 files changed
+2448 -90

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
#include <Void/Crypto/AsyncHash.hpp>
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <format>
#include <fstream>
#include <functional>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>
namespace Void::CryptoAsync
{
namespace
{
[[nodiscard]] Void::Result::Error
map_io_error(const Void::Result::Error& err)
{
if (err.kind() == Void::Result::ErrorKind::cancelled) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::cancelled, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::timeout) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::exhausted) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::resource_exhausted,
err.message(), err.system_code());
}
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::io_error, err.message(),
err.system_code());
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options,
StreamHashOptions hash_options)
{
using namespace Void::Crypto;
if (hash_options.chunk_bytes == 0 ||
hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")};
}
if (!stream.valid()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::hash_stream: stream is invalid or closed")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: operation stopped before start")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired before start")};
}
auto hasher = Hasher::create(algorithm, hash_options.provider);
if (!hasher.has_value()) {
co_return std::unexpected{std::move(hasher.error())};
}
auto lease = driver.allocate_buffer(hash_options.chunk_bytes);
if (!lease.has_value()) {
co_return std::unexpected{map_io_error(lease.error())};
}
for (;;) {
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped between chunks")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired between chunks")};
}
auto transfer = co_await stream.read_some_owned(*lease, options);
if (!transfer.has_value()) {
co_return std::unexpected{map_io_error(transfer.error())};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped during stream read")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired after read")};
}
if (transfer->bytes > 0) {
if (auto upd = hasher->update(lease->readable());
!upd.has_value()) {
co_return std::unexpected{std::move(upd.error())};
}
}
if (transfer->eof) {
break;
}
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped before finalize")};
}
co_return hasher->finalize();
}
struct AsyncFileHasher::State : std::enable_shared_from_this<State> {
struct Job {
Job(Void::Crypto::HashAlgorithm alg,
std::filesystem::path p,
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
o)
: algorithm(alg), path(std::move(p)), op(std::move(o))
{
}
Void::Crypto::HashAlgorithm algorithm;
std::filesystem::path path;
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
op;
std::optional<std::stop_callback<std::function<void()>>>
cancel_cb{};
};
State(Void::Async::Executor& exec, FileHasherOptions opts,
const Void::Time::MonotonicClock& clk)
: executor(exec), options(std::move(opts)), clock(clk)
{
}
void start_workers_locked()
{
if (workers_started || options.max_concurrent == 0) {
return;
}
workers_started = true;
const std::size_t count =
std::max<std::size_t>(1, options.max_concurrent);
workers.reserve(count);
auto self = shared_from_this();
for (std::size_t i = 0; i < count; ++i) {
workers.emplace_back([self] { self->worker_loop(); });
}
}
void worker_loop()
{
for (;;) {
std::shared_ptr<Job> job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this] {
if (closing) {
return true;
}
if (queue.empty()) {
return false;
}
if (active < options.max_concurrent &&
reserved_bytes + options.chunk_bytes <=
options.buffer_budget_bytes) {
return true;
}
return std::any_of(
queue.begin(), queue.end(),
[this](const auto& j) {
return j->op->stop_requested() ||
j->op->is_deadline_expired(clock);
});
});
// Purge any already-cancelled or expired jobs in queue.
std::vector<std::pair<std::shared_ptr<Job>,
Void::Result::Error>>
dropped_jobs;
for (auto it = queue.begin(); it != queue.end();) {
auto& item = *it;
if (closing || item->op->stop_requested()) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
closing
? Void::Crypto::CryptoErrorCode::closed
: Void::Crypto::CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: job cancelled while queued"));
it = queue.erase(it);
} else if (item->op->is_deadline_expired(clock)) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired while queued"));
it = queue.erase(it);
} else {
++it;
}
}
if (!dropped_jobs.empty()) {
lk.unlock();
for (auto& [dropped, err] : dropped_jobs) {
dropped->cancel_cb.reset();
const auto kind =
(err.kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
auto ticket = dropped->op->try_commit_error(
std::move(err), kind);
if (ticket.has_value()) {
ticket->dispatch();
}
dropped->op->release_backend_ref_and_dispatch();
}
lk.lock();
}
if (closing && queue.empty()) {
return;
}
if (queue.empty() || active >= options.max_concurrent ||
reserved_bytes + options.chunk_bytes >
options.buffer_budget_bytes) {
continue;
}
job = std::move(queue.front());
queue.pop_front();
++active;
reserved_bytes += options.chunk_bytes;
in_flight.push_back(job->op);
}
job->cancel_cb.reset();
auto result = run_job(*job);
{
std::lock_guard lk{mu};
--active;
reserved_bytes -= options.chunk_bytes;
++completed;
std::erase_if(in_flight, [&](const auto& weak_op) {
auto sp = weak_op.lock();
return !sp || sp == job->op;
});
}
cv.notify_all();
std::optional<Void::Async::ResumeTicket> ticket;
if (result.has_value()) {
ticket = job->op->try_commit_value(std::move(*result));
} else {
const auto kind =
(result.error().kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
ticket = job->op->try_commit_error(
std::move(result.error()), kind);
}
if (ticket.has_value()) {
ticket->dispatch();
}
job->op->release_backend_ref_and_dispatch();
}
}
[[nodiscard]] Void::Result::Result<Void::Crypto::Digest>
run_job(const Job& job) const
{
using namespace Void::Crypto;
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: cancelled before open")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before open")};
}
std::ifstream input{job.path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: cannot open '{}'",
job.path.string()))};
}
auto hasher = Hasher::create(job.algorithm, options.provider);
if (!hasher.has_value()) {
return std::unexpected{std::move(hasher.error())};
}
std::vector<char> buffer(options.chunk_bytes);
while (input) {
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped during file read")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired during read")};
}
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(std::span{
buffer.data(), static_cast<std::size_t>(count)});
if (auto upd = hasher->update(bytes);
!upd.has_value()) {
return std::unexpected{std::move(upd.error())};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: I/O error reading '{}'",
job.path.string()))};
}
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before finalize")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before finalize")};
}
return hasher->finalize();
}
Void::Async::Executor& executor;
FileHasherOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<std::shared_ptr<Job>> queue{};
std::vector<std::weak_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>>
in_flight{};
std::vector<std::thread> workers{};
bool workers_started{false};
bool closing{false};
bool joined{false};
std::size_t active{0};
std::size_t reserved_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
};
AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor,
FileHasherOptions options,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>(executor, std::move(options), clock))
{
}
AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); }
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options)
{
using namespace Void::Crypto;
auto state = m_state;
if (state->options.max_concurrent == 0 ||
state->options.chunk_bytes == 0 ||
state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::AsyncFileHasher: invalid options")};
}
if (state->options.chunk_bytes > state->options.buffer_budget_bytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::resource_exhausted,
"CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before admission")};
}
if (Void::Async::is_deadline_expired(options, state->clock)) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before admission")};
}
auto op = Void::Async::OperationState<Digest>::create(
options, &state->executor, Void::Async::StopBehavior::notify_only);
auto job = std::make_shared<State::Job>(algorithm, std::move(path), op);
{
std::lock_guard lk{state->mu};
if (state->closing) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::AsyncFileHasher: service is closing")};
}
const std::size_t max_effective_concurrent = std::min(
state->options.max_concurrent,
state->options.buffer_budget_bytes / state->options.chunk_bytes);
const std::size_t capacity =
max_effective_concurrent + state->options.max_waiting;
if (state->active + state->queue.size() >= capacity) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::overloaded,
"CryptoAsync::AsyncFileHasher: wait queue is full")};
}
op->acquire_backend_ref();
state->start_workers_locked();
if (options.stop.stop_possible()) {
std::weak_ptr<State> weak_state = state;
job->cancel_cb.emplace(options.stop, [weak_state]() {
if (auto s = weak_state.lock()) {
s->cv.notify_all();
}
});
}
state->queue.push_back(std::move(job));
}
state->cv.notify_one();
co_return co_await op->awaitable(&state->executor);
}
void AsyncFileHasher::request_stop() noexcept
{
std::vector<
std::shared_ptr<Void::Async::OperationState<Void::Crypto::Digest>>>
ops;
{
std::lock_guard lk{m_state->mu};
m_state->closing = true;
for (const auto& j : m_state->queue) {
ops.push_back(j->op);
}
for (const auto& weak_op : m_state->in_flight) {
if (auto sp = weak_op.lock()) {
ops.push_back(std::move(sp));
}
}
}
for (auto& op : ops) {
op->request_stop();
}
m_state->cv.notify_all();
}
Void::Result::Result<void> AsyncFileHasher::close_and_join()
{
request_stop();
std::vector<std::thread> threads;
{
std::lock_guard lk{m_state->mu};
if (m_state->joined) {
return {};
}
m_state->joined = true;
threads.swap(m_state->workers);
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return {};
}
FileHasherStats AsyncFileHasher::stats() const noexcept
{
std::lock_guard lk{m_state->mu};
return FileHasherStats{
.active = m_state->active,
.waiting = m_state->queue.size(),
.reserved_buffer_bytes = m_state->reserved_bytes,
.completed = m_state->completed,
.rejected = m_state->rejected,
.closing = m_state->closing,
};
}
} // namespace Void::CryptoAsync
+6
View File
@@ -0,0 +1,6 @@
void_add_module(CryptoAsync
INTERNAL_DEPS Crypto IO Async Time Functional
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/Crypto/AsyncHash.hpp
)