Files
Library/include/Void/System/FileWatcher.hpp
T
faumarayandClaude Fable 5 c74a02a5a5 Overhaul Logging and Configuration; integrate the log facade library-wide
Void::Log facade (header-only, macro-free):
- Leveled function templates trace/debug/info/warn/error/fatal(module,
  fmt, args...) with lazy formatting - a disabled call is one relaxed
  atomic load, no allocation, no formatting.
- Global min level + per-module overrides (can raise or lower); empty
  sink/Disabled level = logging fully off; set_sink remains the splice
  point for external logging libraries.

Void::Logging::Logger - async by default, one class for both modes:
- Mode::Async (default): lock-free MPSC queue + logger-owned worker
  delivering batches via on_flush outside any lock; Immediate/Buffered
  give synchronous behavior via constructor arg or set_mode at runtime.
- Bounded queue with OverflowPolicy{Block, DropNewest, DropOldest};
  flush() (now virtual) blocks until everything submitted is delivered;
  base destructor only stops/joins the worker, never touches virtuals.
- Fixed a wakeup race: stale park token + fresh release overflowed the
  binary semaphore; wakeup is a counting semaphore (spurious wakes are
  absorbed by the worker loop).

New sinks and formatters:
- RotatingFileLogger (size-based rotation, max-files cap), NullLogger,
  CallbackLogger, MultiLogger (tee via new Logger::relay), SyslogLogger.
- Formatter interface: PatternFormatter ({time}/{level}/{scopes}/...),
  JsonLinesFormatter, LogfmtFormatter; installable on Console/File/
  Rotating sinks. Console/File sinks now default to Async.
- Logging::from_config builds the whole sink tree from Config keys;
  apply_facade_config drives facade levels.

Configuration:
- Typed get_as<T>/get_or_as<T> (numbers, bool spellings, enums by name,
  chrono durations), dotted keys, subtree(), sorted keys().
- New sources: from_env_prefix (APP_LOG__LEVEL -> log.level), from_ini
  (sections as prefixes), from_json (objects/arrays flattened),
  from_args (--key=value / --key value / --flag).
- Bind.hpp: reflection bind<T>(cfg, prefix) fills aggregates; defaults
  in the struct are the schema; nested aggregates, optional, vector.
- Watch.hpp: ConfigWatch reloads on change with per-key diff; parse
  failures keep the previous config.

System: new FileSystem::FileWatcher - debounced polling watcher (stable
mtime+size across N polls), callbacks off-thread, deletion events;
shared groundwork for plugin hot-reload.

Sweep: all internal Void::Log::log call sites migrated to the leveled
API ("Umbrella.Feature" labels); Plugin loader now logs load/reload.

918 tests green (28 new), stable across 30 consecutive runs, ASan+UBSan
clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 00:11:13 +03:00

95 lines
2.5 KiB
C++

#pragma once
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <map>
#include <mutex>
#include <thread>
namespace Void::FileSystem
{
/// Polling file watcher with debounce.
///
/// One background thread polls every watched path's (mtime, size) at
/// `poll_interval`. After a change is observed, the callback fires only
/// once the metadata has been stable for `debounce_polls` consecutive
/// polls — this avoids reacting to half-written files (e.g. a .so or
/// config file still being copied).
///
/// Callbacks run on the watcher thread; keep them short or hand off.
/// A path that disappears is reported once with `exists == false` and
/// again when it reappears (after debounce).
struct FileWatcherOptions {
std::chrono::milliseconds poll_interval{500};
int debounce_polls = 2;
};
class FileWatcher
{
public:
using Options = FileWatcherOptions;
struct Event {
std::filesystem::path path;
bool exists; // false when the file vanished
};
using Callback = std::function<void(const Event&)>;
explicit FileWatcher(Options options = {});
~FileWatcher();
FileWatcher(const FileWatcher&) = delete;
FileWatcher& operator=(const FileWatcher&) = delete;
FileWatcher(FileWatcher&&) = delete;
FileWatcher& operator=(FileWatcher&&) = delete;
/// Watch a path. Replaces any existing callback for it.
/// Thread-safe.
void watch(std::filesystem::path path, Callback callback);
/// Stop watching a path. Thread-safe.
void unwatch(const std::filesystem::path& path);
[[nodiscard]] std::size_t watch_count() const;
/// Run one poll round immediately (test hook; also usable to
/// force a check without waiting out the interval).
void poll_now();
private:
struct Signature {
bool exists = false;
std::filesystem::file_time_type mtime{};
std::uintmax_t size = 0;
bool operator==(const Signature&) const = default;
};
struct Entry {
Callback callback;
Signature accepted; // last state we reported (or initial)
Signature pending; // candidate new state being debounced
int stable_polls = 0;
bool dirty = false; // pending differs from accepted
};
static Signature stat(const std::filesystem::path& path);
void poll_round();
void run();
Options m_options;
mutable std::mutex m_mutex;
std::condition_variable m_cv;
std::map<std::filesystem::path, Entry> m_watches;
bool m_stop = false;
std::thread m_thread;
};
} // namespace Void::FileSystem