373 lines
13 KiB
C++
373 lines
13 KiB
C++
#include <Void/Log/FileLogger.hpp>
|
|
#include <Void/Log/Formatter.hpp>
|
|
#include <Void/Log/Log.hpp>
|
|
#include <Void/Log/Logger.hpp>
|
|
#include <Void/Log/RotatingFileLogger.hpp>
|
|
#include <Void/Log/Sinks.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <condition_variable>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <stdexcept>
|
|
#include <stop_token>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
namespace
|
|
{
|
|
|
|
using namespace Void::Logging;
|
|
using namespace std::chrono_literals;
|
|
using Void::Testing::expect;
|
|
using Void::Testing::expect_eq;
|
|
using Void::Testing::require;
|
|
|
|
struct FacadeGuard {
|
|
~FacadeGuard()
|
|
{
|
|
(void)Void::Log::detach_and_drain(0);
|
|
Void::Log::set_emergency_handler(nullptr);
|
|
Void::Log::set_min_level(Void::Log::Level::Trace);
|
|
}
|
|
};
|
|
|
|
std::atomic<int> g_emergency_calls{0};
|
|
void record_emergency(std::string_view) noexcept
|
|
{
|
|
g_emergency_calls.fetch_add(1, std::memory_order_relaxed);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
Void::Testing::Test log_facade_reentrant_replace_drain_and_suppression()
|
|
{
|
|
FacadeGuard guard;
|
|
g_emergency_calls.store(0, std::memory_order_relaxed);
|
|
Void::Log::set_emergency_handler(&record_emergency);
|
|
|
|
const auto before_drops = Void::Log::reentrant_dropped();
|
|
std::atomic<bool> destroyed{false};
|
|
struct OwnerFlag {
|
|
std::atomic<bool>* flag;
|
|
~OwnerFlag() { flag->store(true, std::memory_order_release); }
|
|
};
|
|
auto owner = std::make_shared<OwnerFlag>(&destroyed);
|
|
|
|
std::mutex mu;
|
|
std::condition_variable cv;
|
|
bool in_cb = false;
|
|
bool release_cb = false;
|
|
std::atomic<bool> self_drain_blocked{false};
|
|
std::atomic<int> secondary_calls{0};
|
|
|
|
const auto id = Void::Log::register_sink(
|
|
[&](Void::Log::Level,
|
|
std::string_view,
|
|
std::string_view,
|
|
const std::source_location&) {
|
|
// Reentrant log into same registration is suppressed & routed to emergency hook.
|
|
Void::Log::info("LogHardening", "recursive call");
|
|
|
|
// Synchronous self-drain detects active registration -> would_deadlock.
|
|
if (Void::Log::detach_and_drain(0) == Void::Log::DrainResult::would_deadlock) {
|
|
self_drain_blocked.store(true, std::memory_order_release);
|
|
}
|
|
|
|
// Reentrant sink replacement must NOT deadlock; old registration stays
|
|
// alive via Hook/ActiveRegistrationGuard until callback exits.
|
|
Void::Log::set_sink([&](auto, auto, auto, auto) {
|
|
secondary_calls.fetch_add(1, std::memory_order_relaxed);
|
|
});
|
|
|
|
{
|
|
std::unique_lock lock{mu};
|
|
in_cb = true;
|
|
cv.notify_all();
|
|
cv.wait(lock, [&] { return release_cb; });
|
|
}
|
|
},
|
|
owner);
|
|
owner.reset();
|
|
|
|
std::thread emitter{[&] {
|
|
Void::Log::info("LogHardening", "outer event");
|
|
}};
|
|
{
|
|
std::unique_lock lock{mu};
|
|
cv.wait(lock, [&] { return in_cb; });
|
|
}
|
|
|
|
// Even after callback called set_sink(secondary), original owner must stay alive
|
|
// until detach_and_drain(id) finishes waiting on active_calls == 0.
|
|
std::atomic<Void::Log::DrainResult> dr{Void::Log::DrainResult::not_found};
|
|
std::atomic<bool> drain_done{false};
|
|
std::thread drainer{[&] {
|
|
dr.store(Void::Log::detach_and_drain(id), std::memory_order_release);
|
|
drain_done.store(true, std::memory_order_release);
|
|
}};
|
|
std::this_thread::sleep_for(10ms);
|
|
expect(!drain_done.load(std::memory_order_acquire));
|
|
expect(!destroyed.load(std::memory_order_acquire));
|
|
|
|
{
|
|
std::lock_guard lock{mu};
|
|
release_cb = true;
|
|
}
|
|
cv.notify_all();
|
|
emitter.join();
|
|
drainer.join();
|
|
|
|
expect(self_drain_blocked.load());
|
|
expect(dr.load() == Void::Log::DrainResult::drained);
|
|
expect(destroyed.load(std::memory_order_acquire));
|
|
expect(Void::Log::reentrant_dropped() > before_drops);
|
|
expect(g_emergency_calls.load() >= 1);
|
|
|
|
Void::Log::info("LogHardening", "after replace");
|
|
expect_eq(secondary_calls.load(), 1);
|
|
}
|
|
|
|
Void::Testing::Test log_bounded_permits_drop_oldest_and_tickets()
|
|
{
|
|
std::mutex mu;
|
|
std::condition_variable cv;
|
|
bool stalled = true;
|
|
std::atomic<bool> in_sink{false};
|
|
std::vector<std::string> delivered;
|
|
|
|
LoggerOptions opt;
|
|
opt.mode = Mode::Async;
|
|
opt.policy = OverflowPolicy::DropOldest;
|
|
opt.limits.entries = 3;
|
|
opt.limits.batch_entries = 1;
|
|
opt.limits.owned_bytes = 64 * 1024;
|
|
opt.suppress_reentrancy = true;
|
|
|
|
auto sink = std::make_shared<CallbackLogger>(
|
|
[&](const Entry& e) {
|
|
in_sink.store(true, std::memory_order_release);
|
|
{
|
|
std::unique_lock lock{mu};
|
|
cv.wait(lock, [&] { return !stalled; });
|
|
}
|
|
delivered.push_back(e.message);
|
|
},
|
|
opt);
|
|
|
|
// 1st entry starts executing in worker immediately and occupies in-flight permit (1/3).
|
|
auto r1 = sink->try_submit(Entry{.level = Level::Info, .message = "first"});
|
|
require(r1.has_value() && r1->state == SubmitState::Accepted);
|
|
while (!in_sink.load(std::memory_order_acquire)) {
|
|
std::this_thread::sleep_for(1ms);
|
|
}
|
|
|
|
// Queue 2 more -> now queued(2) + in_flight(1) == 3 (at capacity!).
|
|
auto r2 = sink->try_submit(Entry{.level = Level::Info, .message = "second"});
|
|
auto r3 = sink->try_submit(Entry{.level = Level::Info, .message = "third"});
|
|
auto r4 = sink->try_submit(Entry{.level = Level::Info, .message = "fourth"});
|
|
require(r2.has_value() && r3.has_value() && r4.has_value());
|
|
expect(r4->state == SubmitState::Accepted);
|
|
|
|
// Total active (queued + in_flight) never exceeds capacity 3; "second" was evicted.
|
|
const auto st_stall = sink->stats();
|
|
expect(st_stall.queued_entries + st_stall.in_flight_entries <= 3);
|
|
expect_eq(st_stall.dropped, std::uint64_t{1});
|
|
|
|
// Release stalled worker and verify contiguous watermark & report include evicted loss.
|
|
{
|
|
std::lock_guard lock{mu};
|
|
stalled = false;
|
|
}
|
|
cv.notify_all();
|
|
|
|
auto rep = sink->flush_through(*r4->ticket, {});
|
|
require(rep.has_value());
|
|
expect_eq(rep->delivered, std::uint64_t{3});
|
|
expect_eq(rep->dropped, std::uint64_t{1});
|
|
expect_eq(rep->watermark, *r4->ticket);
|
|
expect_eq(delivered.size(), std::size_t{3});
|
|
expect_eq(delivered[0], std::string{"first"});
|
|
expect_eq(delivered[1], std::string{"third"});
|
|
expect_eq(delivered[2], std::string{"fourth"});
|
|
|
|
// Non-file sink must report unsupported_capability for SyncFiles durability.
|
|
auto sync_res = sink->flush_through(0, FlushOptions{FlushDurability::SyncFiles, {}});
|
|
expect(!sync_res.has_value());
|
|
expect_eq(sync_res.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::unsupported_capability));
|
|
|
|
auto close_rep = sink->close({});
|
|
require(close_rep.has_value());
|
|
auto after_close = sink->try_submit(Entry{.level = Level::Info, .message = "late"});
|
|
require(after_close.has_value());
|
|
expect(after_close->state == SubmitState::Closed);
|
|
}
|
|
|
|
Void::Testing::Test log_quarantine_reentrancy_and_block_cancel()
|
|
{
|
|
int attempts = 0;
|
|
LoggerOptions qopt;
|
|
qopt.mode = Mode::Immediate;
|
|
qopt.failure_policy = FailurePolicy::Quarantine;
|
|
qopt.suppress_reentrancy = true;
|
|
|
|
std::shared_ptr<CallbackLogger> qsink;
|
|
bool trigger_reenter = true;
|
|
qsink = std::make_shared<CallbackLogger>(
|
|
[&](const Entry&) {
|
|
++attempts;
|
|
if (trigger_reenter) {
|
|
trigger_reenter = false;
|
|
auto sub = qsink->try_submit(Entry{.level = Level::Info, .message = "inner"});
|
|
expect(sub.has_value() && sub->state == SubmitState::Dropped);
|
|
// Synchronous self-flush must return would_deadlock.
|
|
auto sf = qsink->flush_through(0, {});
|
|
expect(!sf.has_value());
|
|
expect_eq(sf.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::would_deadlock));
|
|
}
|
|
throw std::runtime_error{"disk fault"};
|
|
},
|
|
qopt);
|
|
|
|
auto r = qsink->try_submit(Entry{.level = Level::Error, .message = "fail"});
|
|
require(r.has_value());
|
|
expect(qsink->is_quarantined());
|
|
expect(qsink->last_error_summary().find("disk fault") != std::string::npos);
|
|
expect_eq(qsink->stats().failed, std::uint64_t{1});
|
|
expect_eq(qsink->stats().reentrant_dropped, std::uint64_t{1});
|
|
|
|
// Subsequent submissions fail with quarantined until operator resets quarantine.
|
|
auto blocked = qsink->try_submit(Entry{.level = Level::Error, .message = "next"});
|
|
expect(!blocked.has_value());
|
|
expect_eq(blocked.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::quarantined));
|
|
|
|
qsink->reset_quarantine();
|
|
expect(!qsink->is_quarantined());
|
|
|
|
// Cancellable Block submit stops cleanly when stalled.
|
|
std::mutex mu;
|
|
std::condition_variable cv;
|
|
bool hold = true;
|
|
std::atomic<bool> entered{false};
|
|
LoggerOptions bopt;
|
|
bopt.mode = Mode::Async;
|
|
bopt.policy = OverflowPolicy::Block;
|
|
bopt.limits.entries = 1;
|
|
bopt.limits.batch_entries = 1;
|
|
|
|
CallbackLogger blocker{
|
|
[&](const Entry&) {
|
|
entered.store(true, std::memory_order_release);
|
|
std::unique_lock lock{mu};
|
|
cv.wait(lock, [&] { return !hold; });
|
|
},
|
|
bopt};
|
|
expect(blocker.try_submit(Entry{.level = Level::Info, .message = "fill"})->state ==
|
|
SubmitState::Accepted);
|
|
while (!entered.load(std::memory_order_acquire)) {
|
|
std::this_thread::sleep_for(1ms);
|
|
}
|
|
|
|
std::stop_source stop_src;
|
|
std::thread stopper{[&] {
|
|
std::this_thread::sleep_for(10ms);
|
|
stop_src.request_stop();
|
|
}};
|
|
auto cancelled = blocker.try_submit(
|
|
Entry{.level = Level::Info, .message = "wait"},
|
|
Void::Async::OperationOptions{.stop = stop_src.get_token()});
|
|
stopper.join();
|
|
expect(!cancelled.has_value());
|
|
expect_eq(cancelled.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::cancelled));
|
|
|
|
{
|
|
std::lock_guard lock{mu};
|
|
hold = false;
|
|
}
|
|
cv.notify_all();
|
|
expect(blocker.close({}).has_value());
|
|
}
|
|
|
|
Void::Testing::Test log_formatters_multilogger_and_file_sync_reopen()
|
|
{
|
|
// 1. Logfmt escaping + redaction + format_bounded.
|
|
Entry e;
|
|
e.level = Level::Warning;
|
|
e.message = "line1\nline2\t\"q\"";
|
|
e.truncated = true;
|
|
e.fields = {{"secret", "s3cr3t"}, {"note", "a\nb\rc"}};
|
|
|
|
LogfmtFormatter logfmt;
|
|
logfmt.set_field_filter(FieldFilter{.redact = {"secret"}});
|
|
const std::string line = logfmt.format(e);
|
|
expect(line.find("truncated=true") != std::string::npos);
|
|
expect(line.find("secret=\"[REDACTED]\"") != std::string::npos);
|
|
expect(line.find("s3cr3t") == std::string::npos);
|
|
expect(line.find("\\n") != std::string::npos);
|
|
expect(line.find("\\r") != std::string::npos);
|
|
expect(line.find("\\t") != std::string::npos);
|
|
|
|
const auto too_big = format_bounded(logfmt, e, 16, false);
|
|
expect(!too_big.has_value());
|
|
const auto trunc_ok = format_bounded(logfmt, e, 24, true);
|
|
require(trunc_ok.has_value());
|
|
expect_eq(trunc_ok->size(), std::size_t{24});
|
|
expect(trunc_ok->ends_with("...[truncated]"));
|
|
|
|
// 2. MultiLogger fanout cap (8) + cycle rejection.
|
|
auto root = std::make_shared<MultiLogger>();
|
|
auto child = std::make_shared<MultiLogger>();
|
|
expect(root->try_add(child).has_value());
|
|
auto self_cycle = child->try_add(root);
|
|
expect(!self_cycle.has_value());
|
|
expect_eq(self_cycle.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::cycle_detected));
|
|
for (int i = 0; i < 7; ++i) {
|
|
expect(root->try_add(std::make_shared<NullLogger>()).has_value());
|
|
}
|
|
auto ninth = root->try_add(std::make_shared<NullLogger>());
|
|
expect(!ninth.has_value());
|
|
expect_eq(ninth.error().code().value,
|
|
static_cast<std::int32_t>(LogErrorCode::queue_full));
|
|
|
|
// 3. RotatingFileOptions::roadmap_defaults rejects missing dir + FileLogger sync/reopen.
|
|
const auto base = std::filesystem::temp_directory_path() / "void_log_hardening_test";
|
|
std::filesystem::remove_all(base);
|
|
auto missing_rot = RotatingFileLogger::open(
|
|
base / "no_such_dir" / "app.log",
|
|
RotatingFileOptions::roadmap_defaults());
|
|
expect(!missing_rot.has_value());
|
|
|
|
std::filesystem::create_directories(base);
|
|
const auto file_path = base / "durable.log";
|
|
{
|
|
auto fl_res = FileLogger::open(file_path, LoggerOptions{.mode = Mode::Immediate});
|
|
require(fl_res.has_value());
|
|
auto& fl = *fl_res;
|
|
auto ticket = fl->try_submit(Entry{.level = Level::Info, .message = "before-reopen"});
|
|
require(ticket.has_value() && ticket->ticket.has_value());
|
|
auto synced = fl->flush_through(*ticket->ticket, FlushOptions{FlushDurability::SyncFiles, {}});
|
|
expect(synced.has_value());
|
|
|
|
expect(fl->reopen().has_value());
|
|
expect(fl->try_submit(Entry{.level = Level::Info, .message = "after-reopen"}).has_value());
|
|
expect(fl->close({}).has_value());
|
|
}
|
|
std::ifstream ifs{file_path};
|
|
std::string content{(std::istreambuf_iterator<char>(ifs)), {}};
|
|
expect(content.find("before-reopen") != std::string::npos);
|
|
expect(content.find("after-reopen") != std::string::npos);
|
|
std::filesystem::remove_all(base);
|
|
}
|