feat(system,config,sqlite): implement VL-001, VL-003, VL-010, VL-011

This commit is contained in:
faumaray committed 2026-11-26 20:45:52 +03:00
1 parent adfc8548dc
commit b50131f52e
14 files changed
+2660 -139

No files matched your search

+276 -77
View File
@@ -7,108 +7,284 @@ namespace Void::Argparse
Parser::Parser(std::string program, std::string description)
: program_{std::move(program)}, description_{std::move(description)}
{}
Parser& Parser::flag(std::string_view lng, std::string_view sht,
std::string_view desc, bool& out)
{
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out});
}
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& out)
{
flags_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, &out});
return *this;
}
Parser& Parser::option(std::string_view lng, std::string_view sht,
std::string_view desc, std::optional<std::string>& out)
Parser& Parser::option(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr});
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr});
return *this;
}
Parser& Parser::option_default(std::string_view lng, std::string_view sht,
std::string_view desc, std::string& out,
std::string_view default_value)
Parser& Parser::option_many(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{
out = std::string{default_value};
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc},
std::string{default_value}, nullptr, &out});
options_.push_back({std::string{lng},
std::string{sht},
std::string{desc},
std::string{default_value},
nullptr,
&out,
nullptr});
return *this;
}
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out)
Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& out)
{
positionals_.push_back({std::string{name}, std::string{desc}, &out});
return *this;
}
std::expected<void, std::string>
Parser::parse(int argc, const char* const* argv) const
Parser& Parser::positional_many(std::string_view name,
std::string_view desc,
std::vector<std::string>& out,
bool required)
{
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
auto match_flag_or_opt = [&](const Parser* p,
std::string_view arg,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched = true;
return true;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
if (opt.out_many) opt.out_many->push_back(val_str);
matched = true;
return true;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
// Help
if (arg == "--help" || arg == "-h") {
return std::unexpected{help()};
}
if (!after_double_dash) {
if (arg == "--") {
after_double_dash = true;
continue;
}
// Flag check
bool matched_flag = false;
for (const auto& f : flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched_flag = true;
break;
if (arg == "--help" || arg == "-h") {
return ParseResult{
.outcome = ParseOutcome::Help,
.message = active->help(),
.matched_command_path = std::move(matched_path),
};
}
bool matched = false;
std::string err;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
if (arg.size() > 1 && arg[0] == '-') {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown option: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
}
}
if (matched_flag) continue;
// Option check: --key=value or --key value or -k value
bool matched_opt = false;
for (const auto& opt : options_) {
std::string_view value;
bool found = false;
// --key=value
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=')
{
value = arg.substr(opt.lng.size() + 1);
found = true;
}
// --key value or -k value
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc)
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
matched_opt = true;
break;
}
if (pos_idx < active->positionals_.size()) {
*active->positionals_[pos_idx++].out = std::string{arg};
} else if (active->positional_many_.has_value() &&
active->positional_many_->out != nullptr) {
active->positional_many_->out->push_back(std::string{arg});
} else {
return ParseResult{
.outcome = ParseOutcome::Error,
.message =
"unexpected positional argument: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (matched_opt) continue;
// Unknown --/- prefixed arg
if (arg.size() > 1 && arg[0] == '-')
return std::unexpected{"unknown option: " + std::string{arg}};
// Positional
if (pos_idx >= positionals_.size())
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
*positionals_[pos_idx++].out = std::string{arg};
}
// Check required positionals
for (std::size_t j = pos_idx; j < positionals_.size(); ++j)
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"};
if (!active->subcommands_.empty()) {
const bool req = active->has_explicit_require_sub_
? active->require_subcommand_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {};
}
@@ -116,19 +292,42 @@ std::string Parser::help() const
{
std::ostringstream os;
os << "Usage: " << program_;
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& o : options_) {
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
const std::string_view dn =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " [" << o.lng << " <" << dn << ">]";
}
if (!subcommands_.empty()) {
os << " <command>";
}
for (const auto& p : positionals_) os << " <" << p.name << ">";
if (positional_many_.has_value()) {
os << (positional_many_->required ? " <" : " [")
<< positional_many_->name
<< (positional_many_->required ? "...>" : "...]");
}
os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n";
if (!positionals_.empty()) {
if (!subcommands_.empty()) {
os << "\nCommands:\n";
for (const auto& s : subcommands_) {
os << " " << s.name;
if (!s.parser->description_.empty()) {
os << " " << s.parser->description_;
}
os << "\n";
}
}
if (!positionals_.empty() || positional_many_.has_value()) {
os << "\nArguments:\n";
for (const auto& p : positionals_)
os << " <" << p.name << "> " << p.desc << "\n";
if (positional_many_.has_value()) {
os << " <" << positional_many_->name << "...> "
<< positional_many_->desc << "\n";
}
}
if (!flags_.empty()) {
os << "\nFlags:\n";
@@ -141,13 +340,13 @@ std::string Parser::help() const
if (!options_.empty()) {
os << "\nOptions:\n";
for (const auto& o : options_) {
// Derive a display name from the long option (strip leading --)
const std::string_view dname = std::string_view{o.lng}.substr(
o.lng.size() > 2 ? 2 : 0);
const std::string_view dname =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " " << o.lng;
if (!o.sht.empty()) os << ", " << o.sht;
os << " <" << dname << ">";
if (!o.def.empty()) os << " (default: " << o.def << ")";
if (o.out_many != nullptr) os << " (repeatable)";
os << " " << o.desc << "\n";
}
}
@@ -155,4 +354,4 @@ std::string Parser::help() const
return os.str();
}
} // namespace Void::Argparse
} // namespace Void::Argparse
+833
View File
@@ -0,0 +1,833 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <deque>
#include <filesystem>
#include <format>
#include <map>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
#if defined(__linux__)
namespace
{
constexpr std::uint32_t kWatchMask =
IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM |
IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK |
IN_ONLYDIR;
[[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate,
const std::filesystem::path& prefix)
{
const std::string c = candidate.lexically_normal().generic_string();
const std::string p = prefix.lexically_normal().generic_string();
if (c == p) {
return true;
}
if (p.empty()) {
return false;
}
const std::size_t plen = p.size();
return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/';
}
[[nodiscard]] std::filesystem::path
rebase_path(const std::filesystem::path& p,
const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
const std::string ps = p.lexically_normal().generic_string();
const std::string os = old_prefix.lexically_normal().generic_string();
if (ps == os) {
return new_prefix;
}
if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 &&
ps[os.size()] == '/') {
return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)};
}
return p;
}
} // namespace
struct DirectoryWatcher::Impl {
struct PendingMove {
std::filesystem::path path{};
bool is_directory{false};
std::chrono::steady_clock::time_point expires_at{};
};
Void::System::OwnedFd inotify_fd{};
Void::System::OwnedFd wake_fd{};
std::filesystem::path root{};
DirectoryWatcherOptions options{};
mutable std::mutex mutex{};
std::unordered_map<int, std::filesystem::path> wd_to_path{};
std::map<std::filesystem::path, int> path_to_wd{};
std::unordered_map<std::uint32_t, PendingMove> pending_moves{};
std::deque<DirectoryEvent> queue{};
bool rescan_emitted{false};
~Impl() noexcept
{
std::lock_guard lock{mutex};
for (const auto& [wd, _] : wd_to_path) {
if (inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
wd_to_path.clear();
path_to_wd.clear();
}
[[nodiscard]] bool should_ignore(const std::filesystem::path& p,
bool is_dir) const
{
if (options.ignore) {
return options.ignore(p, is_dir);
}
return false;
}
void push_event_locked(DirectoryEvent ev)
{
if (ev.kind == DirectoryEventKind::RescanRequired) {
if (rescan_emitted) {
return;
}
rescan_emitted = true;
queue.push_back(std::move(ev));
return;
}
if (queue.size() >= options.max_queued_events) {
if (!rescan_emitted) {
rescan_emitted = true;
queue.push_back(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher event queue full",
});
}
return;
}
queue.push_back(std::move(ev));
}
void remove_watch_by_wd_locked(int wd, bool call_rm)
{
auto it = wd_to_path.find(wd);
if (it == wd_to_path.end()) {
return;
}
path_to_wd.erase(it->second);
wd_to_path.erase(it);
if (call_rm && inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
void remove_subtree_watches_locked(const std::filesystem::path& prefix)
{
std::vector<int> wds;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, prefix)) {
wds.push_back(wd);
}
}
for (int wd : wds) {
remove_watch_by_wd_locked(wd, true);
}
}
void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
std::vector<std::pair<int, std::filesystem::path>> updates;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, old_prefix)) {
updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix));
}
}
for (const auto& [wd, new_p] : updates) {
auto old_it = wd_to_path.find(wd);
if (old_it != wd_to_path.end()) {
path_to_wd.erase(old_it->second);
old_it->second = new_p;
path_to_wd[new_p] = wd;
}
}
}
void attach_single_dir_locked(const std::filesystem::path& dir_path)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
if (path_to_wd.contains(norm)) {
return;
}
if (wd_to_path.size() >= options.max_watches) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher max_watches exceeded",
});
return;
}
const int wd =
::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask);
if (wd < 0) {
const int err = errno;
if (err == ENOSPC || err == ENOMEM) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = std::format(
"inotify_add_watch exhausted watches (errno={})", err),
});
}
return;
}
// inotify_add_watch may return an existing wd if directory inode aliased.
if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) {
if (existing->second != norm) {
path_to_wd.erase(existing->second);
existing->second = norm;
}
} else {
wd_to_path.emplace(wd, norm);
}
path_to_wd[norm] = wd;
}
void attach_subtree_locked(const std::filesystem::path& dir_path,
bool emit_existing_children)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
std::error_code ec;
const auto st = std::filesystem::symlink_status(norm, ec);
if (ec || std::filesystem::is_symlink(st) ||
!std::filesystem::is_directory(st)) {
return;
}
attach_single_dir_locked(norm);
std::vector<std::filesystem::path> stack{norm};
while (!stack.empty()) {
const std::filesystem::path cur = std::move(stack.back());
stack.pop_back();
ec.clear();
std::filesystem::directory_iterator it{
cur,
std::filesystem::directory_options::skip_permission_denied,
ec};
if (ec) {
continue;
}
for (const auto& entry : it) {
std::error_code st_ec;
const auto est = entry.symlink_status(st_ec);
if (st_ec || std::filesystem::is_symlink(est)) {
continue;
}
const bool is_dir = std::filesystem::is_directory(est);
const std::filesystem::path ep =
entry.path().lexically_normal();
if (should_ignore(ep, is_dir)) {
continue;
}
if (emit_existing_children) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = ep,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if (is_dir) {
attach_single_dir_locked(ep);
stack.push_back(ep);
}
}
}
}
void flush_expired_moves_locked(std::chrono::steady_clock::time_point now,
bool force_all)
{
for (auto it = pending_moves.begin(); it != pending_moves.end();) {
if (force_all || now >= it->second.expires_at) {
const auto p = it->second.path;
const bool is_dir = it->second.is_directory;
if (is_dir) {
remove_subtree_watches_locked(p);
}
if (!should_ignore(p, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = p,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
it = pending_moves.erase(it);
} else {
++it;
}
}
}
void process_inotify_event_locked(const struct inotify_event* ev)
{
if ((ev->mask & IN_Q_OVERFLOW) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)",
});
return;
}
if ((ev->mask & IN_IGNORED) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
return;
}
const auto dir_it = wd_to_path.find(ev->wd);
if (dir_it == wd_to_path.end()) {
return;
}
const std::filesystem::path base = dir_it->second;
const bool is_dir = (ev->mask & IN_ISDIR) != 0U;
if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) {
if (base == root) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "watched root directory deleted or moved",
});
remove_watch_by_wd_locked(ev->wd, false);
} else if ((ev->mask & IN_DELETE_SELF) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
}
return;
}
const std::string name =
(ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name}
: std::string{};
const std::filesystem::path full_path =
name.empty() ? base : (base / name).lexically_normal();
if ((ev->mask & IN_MOVED_FROM) != 0U) {
if (ev->cookie != 0U) {
pending_moves.insert_or_assign(
ev->cookie,
PendingMove{
.path = full_path,
.is_directory = is_dir,
.expires_at = std::chrono::steady_clock::now() +
options.rename_pair_window,
});
} else {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
if (!should_ignore(full_path, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
return;
}
if ((ev->mask & IN_MOVED_TO) != 0U) {
if (ev->cookie != 0U) {
if (auto mit = pending_moves.find(ev->cookie);
mit != pending_moves.end()) {
const std::filesystem::path old_path =
std::move(mit->second.path);
pending_moves.erase(mit);
const bool old_ignored = should_ignore(old_path, is_dir);
const bool new_ignored = should_ignore(full_path, is_dir);
if (is_dir) {
if (new_ignored) {
remove_subtree_watches_locked(old_path);
} else {
rewrite_subtree_watches_locked(old_path, full_path);
attach_subtree_locked(full_path, false);
}
}
if (!old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Renamed,
.path = full_path,
.old_path = old_path,
.is_directory = is_dir,
.detail = {},
});
} else if (!old_ignored && new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = old_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
} else if (old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
return;
}
}
if (should_ignore(full_path, is_dir)) {
return;
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
return;
}
if (should_ignore(full_path, is_dir)) {
return;
}
if ((ev->mask & IN_CREATE) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
}
if ((ev->mask & IN_DELETE) != 0U) {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Modified,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & IN_ATTRIB) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::AttributeChanged,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
drain_inotify_locked()
{
alignas(struct inotify_event) std::array<char, 16384> buf{};
for (;;) {
const ssize_t n =
::read(inotify_fd.get(), buf.data(), buf.size());
if (n > 0) {
ssize_t offset = 0;
while (offset < n) {
const auto* ev =
reinterpret_cast<const struct inotify_event*>(
buf.data() + offset);
process_inotify_event_locked(ev);
offset += static_cast<ssize_t>(
sizeof(struct inotify_event) + ev->len);
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher: read(inotify) failed",
err)};
}
return {};
}
void drain_wake_locked() noexcept
{
std::uint64_t val = 0;
while (::read(wake_fd.get(), &val, sizeof(val)) > 0 ||
(errno == EINTR)) {
}
}
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path& root,
DirectoryWatcherOptions options)
{
if (root.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::create: root cannot be empty")};
}
std::error_code ec;
const auto st = std::filesystem::status(root, ec);
if (ec || !std::filesystem::is_directory(st)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::not_found,
std::format(
"FileSystem::DirectoryWatcher::create: '{}' is not a directory",
root.string()))};
}
const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (ifd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: inotify_init1 failed",
err)};
}
Void::System::OwnedFd owned_ifd{ifd};
const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: eventfd failed",
err)};
}
Void::System::OwnedFd owned_efd{efd};
auto impl = std::make_unique<Impl>();
impl->inotify_fd = std::move(owned_ifd);
impl->wake_fd = std::move(owned_efd);
impl->root = std::filesystem::weakly_canonical(root, ec);
if (ec || impl->root.empty()) {
impl->root = root.lexically_normal();
}
impl->options = std::move(options);
{
std::lock_guard lock{impl->mutex};
impl->attach_subtree_locked(impl->root, false);
}
return DirectoryWatcher{std::move(impl)};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds timeout)
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::poll: moved-from watcher")};
}
const auto start = std::chrono::steady_clock::now();
const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout);
int ifd = -1;
int efd = -1;
{
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
timeout.count() <= 0);
if (!impl_->queue.empty() && impl_->pending_moves.empty()) {
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
ifd = impl_->inotify_fd.get();
efd = impl_->wake_fd.get();
}
if (timeout.count() > 0) {
for (;;) {
const auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point wait_until = end_time;
{
std::lock_guard lock{impl_->mutex};
for (const auto& [_, pm] : impl_->pending_moves) {
wait_until = std::min(wait_until, pm.expires_at);
}
}
if (now >= wait_until) {
std::lock_guard lock{impl_->mutex};
impl_->flush_expired_moves_locked(now, false);
if (now >= end_time ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
continue;
}
const auto rem_ms = std::max<long long>(
1,
std::chrono::duration_cast<std::chrono::milliseconds>(
wait_until - now)
.count());
std::array<struct pollfd, 2> pfds{{
{ifd, POLLIN, 0},
{efd, POLLIN, 0},
}};
const int rc =
::poll(pfds.data(), pfds.size(), static_cast<int>(rem_ms));
if (rc < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::poll: poll failed",
err)};
}
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
const bool woken = (pfds[1].revents & POLLIN) != 0;
if (woken) {
impl_->drain_wake_locked();
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
false);
if (woken ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
}
}
std::lock_guard lock{impl_->mutex};
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::rescan: moved-from watcher")};
}
std::lock_guard lock{impl_->mutex};
for (const auto& [wd, _] : impl_->wd_to_path) {
(void)::inotify_rm_watch(impl_->inotify_fd.get(), wd);
}
impl_->wd_to_path.clear();
impl_->path_to_wd.clear();
impl_->pending_moves.clear();
impl_->queue.clear();
impl_->rescan_emitted = false;
impl_->attach_subtree_locked(impl_->root, false);
return {};
}
void DirectoryWatcher::wake() noexcept
{
if (!impl_ || !impl_->wake_fd.valid()) {
return;
}
const std::uint64_t one = 1;
while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 &&
errno == EINTR) {
}
}
void DirectoryWatcher::simulate_overflow_for_test()
{
if (!impl_) {
return;
}
{
std::lock_guard lock{impl_->mutex};
impl_->push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = impl_->root,
.old_path = {},
.is_directory = true,
.detail = "simulated IN_Q_OVERFLOW",
});
}
wake();
}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept
{
if (!impl_) {
return 0;
}
std::lock_guard lock{impl_->mutex};
return impl_->wd_to_path.size();
}
int DirectoryWatcher::native_handle() const noexcept
{
return impl_ ? impl_->inotify_fd.get() : -1;
}
#else
struct DirectoryWatcher::Impl {
std::filesystem::path root{};
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path&,
DirectoryWatcherOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: inotify watcher is Linux-only")};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
void DirectoryWatcher::wake() noexcept {}
void DirectoryWatcher::simulate_overflow_for_test() {}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; }
int DirectoryWatcher::native_handle() const noexcept { return -1; }
#endif
} // namespace Void::FileSystem
+192 -54
View File
@@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default;
Child& Child::operator=(Child&&) noexcept = default;
bool Child::valid() const noexcept { return false; }
bool Child::running() const noexcept { return false; }
bool Child::process_group_alive() const noexcept { return false; }
long long Child::pid() const noexcept { return -1; }
long long Child::pgid() const noexcept { return -1; }
bool Child::owns_process_group() const noexcept { return false; }
@@ -142,6 +143,13 @@ Void::Result::Result<void, Void::Result::Error> reexec(
return Void::Result::fail("Process::reexec: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process
#else // POSIX
@@ -150,6 +158,9 @@ Void::Result::Result<void, Void::Result::Error> reexec(
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#if defined(__linux__) && __has_include(<sys/prctl.h>)
#include <sys/prctl.h>
#endif
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
@@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept
return st;
}
[[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept
{
if (pgid <= 0) {
return false;
}
for (;;) {
if (::kill(-pgid, 0) == 0) {
return true;
}
if (errno == EINTR) {
continue;
}
return errno == EPERM;
}
}
void reap_group_nonblocking(pid_t pid,
pid_t pgid,
bool owns_group,
bool& reaped,
ExitStatus& cached,
int& out_errno) noexcept
{
out_errno = 0;
if (!reaped && pid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(pid, &raw, WNOHANG);
if (w == pid) {
cached = decode_wait_status(raw);
reaped = true;
break;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped = true;
break;
}
out_errno = errno;
break;
}
}
if (owns_group && pgid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(-pgid, &raw, WNOHANG);
if (w > 0) {
if (w == pid && !reaped) {
cached = decode_wait_status(raw);
reaped = true;
}
continue;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
break;
}
}
}
[[nodiscard]] bool signal_target(pid_t pid,
pid_t pgid,
bool owns_group,
bool leader_reaped,
int sig,
int& out_errno) noexcept
{
bool delivered = false;
out_errno = 0;
if (owns_group && pgid > 0) {
if (::kill(-pgid, sig) == 0) {
return true;
}
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
delivered = true;
} else {
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
}
}
}
if (::kill(pid, sig) == 0) {
return true;
if (!leader_reaped && pid > 0) {
if (::kill(pid, sig) == 0) {
delivered = true;
} else {
out_errno = errno;
}
}
out_errno = errno;
return false;
return delivered;
}
[[nodiscard]] std::optional<std::string>
@@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept
bool Child::valid() const noexcept { return pid_ > 0; }
bool Child::running() const noexcept { return pid_ > 0 && !reaped_; }
bool Child::process_group_alive() const noexcept
{
if (owns_group_ && pgid_ > 0) {
return is_process_group_alive(static_cast<pid_t>(pgid_));
}
return running();
}
long long Child::pid() const noexcept { return pid_; }
long long Child::pgid() const noexcept { return pgid_; }
bool Child::owns_process_group() const noexcept { return owns_group_; }
@@ -738,7 +832,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::send_signal: invalid child")};
}
if (reaped_) {
if (reaped_ && (!owns_group_ || !process_group_alive())) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::Child::send_signal: child already reaped")};
@@ -747,6 +841,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
if (!signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
reaped_,
sig,
err)) {
return std::unexpected{Void::System::make_system_error(
@@ -798,35 +893,37 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::terminate: invalid child")};
}
if (reaped_) {
const pid_t target_pid = static_cast<pid_t>(pid_);
const pid_t target_pgid = static_cast<pid_t>(pgid_);
const bool group_owned = owns_group_ && target_pgid > 0;
auto group_finished = [&]() noexcept -> bool {
int reap_err = 0;
reap_group_nonblocking(
target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err);
if (!reaped_) {
return false;
}
return !group_owned || !is_process_group_alive(target_pgid);
};
if (group_finished()) {
return cached_status_;
}
const auto effective_grace =
(grace.count() >= 0) ? grace : kill_grace_;
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
}
int sig_err = 0;
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGTERM,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err);
const auto grace_deadline =
std::chrono::steady_clock::now() + effective_grace;
while (std::chrono::steady_clock::now() < grace_deadline) {
auto polled = try_wait();
if (!polled.has_value()) {
return std::unexpected{polled.error()};
}
if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
grace_deadline - std::chrono::steady_clock::now());
@@ -834,38 +931,61 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
break;
}
std::this_thread::sleep_for(
std::min(rem, std::chrono::milliseconds{10}));
std::min(rem, std::chrono::milliseconds{5}));
}
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGKILL,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err);
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(static_cast<pid_t>(pid_), &raw, 0);
if (w == static_cast<pid_t>(pid_)) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
return cached_status_;
if (!reaped_) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(target_pid, &raw, 0);
if (w == target_pid) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped_ = true;
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (group_owned) {
const auto kill_ceiling =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
while (!group_finished()) {
if (std::chrono::steady_clock::now() >= kill_ceiling) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::Child::terminate: process group members failed "
"to exit after SIGKILL")};
}
(void)signal_target(target_pid,
target_pgid,
group_owned,
reaped_,
SIGKILL,
sig_err);
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
return cached_status_;
}
Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking(
@@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept
stdin_.reset();
stdout_.reset();
stderr_.reset();
if (pid_ > 0 && !reaped_) {
if (pid_ > 0 && (!reaped_ || process_group_alive())) {
(void)terminate(kill_grace_);
}
pid_ = -1;
@@ -1643,6 +1763,24 @@ Void::Result::Result<void, Void::Result::Error>
err)};
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
#if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER)
if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed",
err)};
}
return {};
#else
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")};
#endif
}
} // namespace Void::Process
#endif // _WIN32