Files
Library/include/Void/System/AsyncWatcher.hpp
T

117 lines
2.9 KiB
C++

#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <string>
namespace Void::SystemAsync
{
enum class WatchEventKind {
created,
modified,
deleted,
replaced_inode,
symlink_changed,
permission_denied,
rescan_required,
};
struct WatchEvent {
WatchEventKind kind{WatchEventKind::modified};
std::filesystem::path path{};
bool exists{false};
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint64_t size{0};
int sys_errno{0};
};
struct WatcherLimits {
std::size_t max_watched_paths{1024};
std::size_t max_queued_events{256};
std::chrono::milliseconds poll_interval{std::chrono::milliseconds{250}};
int debounce_polls{1};
};
struct WatchPathOptions {
std::optional<std::filesystem::path> allowed_root{};
bool allow_symlink{false};
};
using WatchCallback = std::function<void(const WatchEvent&)>;
using ErrorSink = std::function<void(const Void::Result::Error&)>;
class WatcherService;
class WatchSubscription
{
public:
WatchSubscription() noexcept = default;
~WatchSubscription() noexcept;
WatchSubscription(const WatchSubscription&) = delete;
WatchSubscription& operator=(const WatchSubscription&) = delete;
WatchSubscription(WatchSubscription&&) noexcept;
WatchSubscription& operator=(WatchSubscription&&) noexcept;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
close_and_join();
private:
friend class WatcherService;
struct Token;
std::shared_ptr<Token> token_;
};
class WatcherService
{
public:
struct Impl;
explicit WatcherService(
Void::Async::Executor& executor,
WatcherLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance(),
ErrorSink error_sink = {},
bool start_background_thread = false);
~WatcherService() noexcept;
WatcherService(const WatcherService&) = delete;
WatcherService& operator=(const WatcherService&) = delete;
WatcherService(WatcherService&&) = delete;
WatcherService& operator=(WatcherService&&) = delete;
[[nodiscard]] Void::Result::Result<WatchSubscription, Void::Result::Error>
watch(const std::filesystem::path& path,
WatchCallback callback,
WatchPathOptions options = {});
void poll_once();
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] std::size_t queued_event_count() const noexcept;
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> shutdown();
private:
std::shared_ptr<Impl> impl_;
};
} // namespace Void::SystemAsync