Files
Library/src/Log/Logger.cpp
T

912 lines
25 KiB
C++

#include <Void/Log/Logger.hpp>
#include <Void/Log/Field.hpp>
#include <algorithm>
#include <exception>
#include <limits>
#include <optional>
#include <stop_token>
#include <utility>
namespace Void::Logging
{
namespace
{
constexpr std::size_t kEntryOverheadBytes = 128;
constexpr std::size_t kMaxErrorSummaryBytes = 256;
constexpr std::size_t kMaxNestedLoggerDepth = 8;
thread_local std::vector<const Logger*> t_active_loggers;
struct ActiveLoggerGuard {
const Logger* logger{nullptr};
bool pushed{false};
explicit ActiveLoggerGuard(const Logger* l) : logger(l)
{
t_active_loggers.push_back(logger);
pushed = true;
}
~ActiveLoggerGuard() noexcept
{
if (pushed && !t_active_loggers.empty()) {
t_active_loggers.pop_back();
}
}
ActiveLoggerGuard(const ActiveLoggerGuard&) = delete;
ActiveLoggerGuard& operator=(const ActiveLoggerGuard&) = delete;
};
LoggerOptions make_legacy_options(Mode mode,
std::size_t capacity,
OverflowPolicy policy) noexcept
{
LoggerOptions opt;
opt.mode = mode;
opt.policy = policy;
const std::size_t cap = capacity > 0 ? capacity : 1;
opt.limits.entries = cap;
opt.limits.owned_bytes =
std::max<std::size_t>(8ULL * 1024ULL * 1024ULL, cap * 1024ULL);
opt.limits.max_scopes = 64;
opt.limits.max_fields = 64;
opt.suppress_reentrancy = false;
return opt;
}
} // namespace
Void::Result::Result<void> DeliveryLimits::validate() const
{
if (entries == 0 || owned_bytes == 0 || max_entry_bytes == 0 ||
batch_entries == 0 || batch_bytes == 0 || max_fields == 0 ||
max_scopes == 0 || max_field_key_bytes == 0 ||
max_field_value_bytes == 0 || max_format_scratch_bytes == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"DeliveryLimits bounds must all be non-zero"));
}
if (max_entry_bytes > owned_bytes) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"DeliveryLimits::max_entry_bytes cannot exceed owned_bytes"));
}
return {};
}
thread_local std::vector<std::string> Logger::s_scope_stack;
Logger::ScopedContext::ScopedContext(Logger& owner,
std::string name,
Level level,
std::source_location loc) noexcept
: m_owner(&owner), m_name(std::move(name)), m_level(level)
{
try {
s_scope_stack.push_back(m_name);
} catch (...) {
m_active = false;
return;
}
owner.emit_scope_boundary(Kind::ScopeEnter, m_name, m_level, loc);
}
Logger::ScopedContext::~ScopedContext() noexcept
{
if (!m_active || m_owner == nullptr) {
return;
}
m_owner->emit_scope_boundary(
Kind::ScopeExit,
m_name,
m_level,
std::source_location{});
if (!s_scope_stack.empty()) {
s_scope_stack.pop_back();
}
}
Logger::ScopedContext::ScopedContext(ScopedContext&& other) noexcept
: m_owner(std::exchange(other.m_owner, nullptr)),
m_name(std::move(other.m_name)), m_level(other.m_level),
m_active(std::exchange(other.m_active, false))
{
}
Logger::Logger(Mode mode,
std::size_t capacity,
OverflowPolicy policy) noexcept
: m_mode(mode),
m_options(make_legacy_options(mode, capacity, policy)),
m_buffer_capacity(capacity > 0 ? capacity : 1)
{
}
Logger::Logger(LoggerOptions options)
: m_mode(options.mode),
m_options(std::move(options)),
m_buffer_capacity(
m_options.limits.entries > 0 ? m_options.limits.entries : 1)
{
if (m_options.clock == nullptr) {
m_options.clock = &Void::Time::SystemMonotonicClock::instance();
}
}
Logger::~Logger() noexcept
{
{
std::lock_guard lock{m_mutex};
m_stop_admission = true;
m_closed = true;
}
m_stop_worker.store(true, std::memory_order_release);
m_space_cv.notify_all();
m_work_cv.notify_all();
m_done_cv.notify_all();
if (m_worker.joinable()) {
m_worker.join();
}
}
void Logger::set_level(Level level) noexcept
{
m_level.store(level, std::memory_order_relaxed);
}
Level Logger::level() const noexcept
{
return m_level.load(std::memory_order_relaxed);
}
void Logger::set_mode(Mode mode) noexcept
{
std::unique_lock lock{m_mutex};
const Mode old = m_mode.load(std::memory_order_acquire);
if (old == mode) {
return;
}
m_mode_changing = true;
const Ticket target = m_next_ticket;
m_space_cv.notify_all();
if (old == Mode::Buffered && !m_queue.empty()) {
std::vector<QueuedItem> batch;
std::size_t batch_bytes = m_queued_bytes;
batch.reserve(m_queue.size());
while (!m_queue.empty()) {
batch.push_back(std::move(m_queue.front()));
m_queue.pop_front();
}
m_queued_entries = 0;
m_queued_bytes = 0;
m_in_flight_entries += batch.size();
m_in_flight_bytes += batch_bytes;
lock.unlock();
deliver_batch_unlocked(batch, false, batch_bytes);
lock.lock();
} else {
m_work_cv.notify_all();
m_done_cv.wait(lock, [this, target] {
return m_completed_watermark >= target ||
m_stop_worker.load(std::memory_order_acquire);
});
}
m_mode.store(mode, std::memory_order_release);
m_mode_changing = false;
lock.unlock();
m_space_cv.notify_all();
}
Mode Logger::mode() const noexcept
{
return m_mode.load(std::memory_order_acquire);
}
void Logger::set_buffer_capacity(std::size_t n) noexcept
{
std::lock_guard lock{m_mutex};
m_buffer_capacity = n > 0 ? n : 1;
}
std::size_t Logger::buffer_capacity() const noexcept
{
std::lock_guard lock{m_mutex};
return m_buffer_capacity;
}
OverflowPolicy Logger::overflow_policy() const noexcept
{
return m_options.policy;
}
std::size_t Logger::estimate_entry_bytes(const Entry& entry) noexcept
{
std::size_t total = kEntryOverheadBytes + entry.message.size();
for (const auto& sc : entry.scopes) {
total += 32 + sc.size();
}
for (const auto& [k, v] : entry.fields) {
total += 48 + k.size() + v.size();
}
return total;
}
Void::Result::Result<void> Logger::prepare_entry(Entry& entry) const
{
const auto& lim = m_options.limits;
if (auto v = lim.validate(); !v) {
return v;
}
auto reject_or_truncate = [&](std::string_view reason) -> Void::Result::Result<void> {
if (!lim.truncate_oversize) {
return Void::Result::fail(make_log_error(
LogErrorCode::entry_too_large, std::string{reason}));
}
entry.truncated = true;
return {};
};
if (entry.scopes.size() > lim.max_scopes) {
if (auto r = reject_or_truncate("Log entry exceeds max_scopes"); !r) {
return r;
}
entry.scopes.resize(lim.max_scopes);
}
if (entry.fields.size() > lim.max_fields) {
if (auto r = reject_or_truncate("Log entry exceeds max_fields"); !r) {
return r;
}
entry.fields.resize(lim.max_fields);
}
for (auto& [k, v] : entry.fields) {
if (k.size() > lim.max_field_key_bytes) {
if (auto r = reject_or_truncate("Log field key exceeds bound"); !r) {
return r;
}
k.resize(lim.max_field_key_bytes);
}
if (v.size() > lim.max_field_value_bytes) {
if (auto r = reject_or_truncate("Log field value exceeds bound"); !r) {
return r;
}
v.resize(lim.max_field_value_bytes);
}
}
const std::size_t msg_cap = lim.max_entry_bytes;
if (entry.message.size() > msg_cap ||
estimate_entry_bytes(entry) > lim.max_entry_bytes + kEntryOverheadBytes + 1024) {
if (estimate_entry_bytes(entry) > lim.max_entry_bytes + kEntryOverheadBytes * 4) {
if (auto r = reject_or_truncate("Log entry exceeds max_entry_bytes"); !r) {
return r;
}
if (entry.message.size() > msg_cap) {
entry.message.resize(msg_cap);
}
}
}
if (entry.message.size() > lim.max_entry_bytes) {
if (auto r = reject_or_truncate("Log message exceeds max_entry_bytes"); !r) {
return r;
}
entry.message.resize(lim.max_entry_bytes);
}
return {};
}
bool Logger::is_active_logger_on_thread() const noexcept
{
for (const auto* l : t_active_loggers) {
if (l == this) {
return true;
}
}
return false;
}
Void::Result::Result<SubmitReceipt>
Logger::try_submit(Entry entry, Void::Async::OperationOptions options)
{
if (entry.level < m_level.load(std::memory_order_relaxed)) {
return SubmitReceipt{SubmitState::Filtered, std::nullopt, entry.truncated};
}
if (t_active_loggers.size() >= kMaxNestedLoggerDepth ||
(m_options.suppress_reentrancy && is_active_logger_on_thread())) {
m_reentrant_dropped.fetch_add(1, std::memory_order_relaxed);
return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated};
}
if (m_quarantined.load(std::memory_order_acquire)) {
return Void::Result::fail(make_log_error(
LogErrorCode::quarantined, last_error_summary()));
}
if (auto prep = prepare_entry(entry); !prep) {
return Void::Result::fail(std::move(prep).error());
}
const std::size_t entry_bytes = estimate_entry_bytes(entry);
if (entry_bytes > m_options.limits.owned_bytes) {
return Void::Result::fail(make_log_error(
LogErrorCode::entry_too_large,
"Log entry byte cost exceeds Logger DeliveryLimits::owned_bytes"));
}
if (options.stop.stop_requested()) {
return Void::Result::fail(make_log_error(
LogErrorCode::cancelled,
"Log submission cancelled before admission"));
}
if (Void::Async::is_deadline_expired(options, *m_options.clock)) {
return Void::Result::fail(make_log_error(
LogErrorCode::timeout,
"Log submission deadline expired before admission"));
}
const Mode active_mode = m_mode.load(std::memory_order_acquire);
if (active_mode == Mode::Async) {
start_worker();
}
std::unique_lock lock{m_mutex};
if (m_stop_admission || m_closed ||
m_next_ticket == std::numeric_limits<Ticket>::max()) {
m_stop_admission = true;
return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated};
}
auto fits_budget = [this, entry_bytes]() noexcept {
return (m_queued_entries + m_in_flight_entries + 1 <=
m_options.limits.entries) &&
(entry_bytes <=
m_options.limits.owned_bytes -
std::min(m_queued_bytes + m_in_flight_bytes,
m_options.limits.owned_bytes));
};
if (active_mode == Mode::Immediate) {
if (!fits_budget()) {
++m_dropped_count;
return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated};
}
const Ticket t = ++m_next_ticket;
++m_admitted_count;
++m_in_flight_entries;
m_in_flight_bytes += entry_bytes;
const bool trunc = entry.truncated;
std::vector<QueuedItem> single;
single.push_back(QueuedItem{t, entry_bytes, std::move(entry)});
lock.unlock();
deliver_batch_unlocked(single, false, entry_bytes);
return SubmitReceipt{SubmitState::Accepted, t, trunc};
}
if (active_mode == Mode::Buffered) {
while (!fits_budget() && m_options.policy == OverflowPolicy::DropOldest &&
!m_queue.empty()) {
auto evicted = std::move(m_queue.front());
m_queue.pop_front();
--m_queued_entries;
m_queued_bytes -= std::min(m_queued_bytes, evicted.bytes);
++m_dropped_count;
mark_terminal_locked(evicted.ticket, TerminalOutcome::Dropped);
}
if (!fits_budget()) {
++m_dropped_count;
return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated};
}
const Ticket t = ++m_next_ticket;
++m_admitted_count;
++m_queued_entries;
m_queued_bytes += entry_bytes;
const bool trunc = entry.truncated;
m_queue.push_back(QueuedItem{t, entry_bytes, std::move(entry)});
if (m_queue.size() >= m_buffer_capacity) {
std::vector<QueuedItem> batch;
const std::size_t batch_bytes = m_queued_bytes;
batch.reserve(m_queue.size());
while (!m_queue.empty()) {
batch.push_back(std::move(m_queue.front()));
m_queue.pop_front();
}
m_queued_entries = 0;
m_queued_bytes = 0;
m_in_flight_entries += batch.size();
m_in_flight_bytes += batch_bytes;
lock.unlock();
deliver_batch_unlocked(batch, false, batch_bytes);
}
return SubmitReceipt{SubmitState::Accepted, t, trunc};
}
// Mode::Async
switch (m_options.policy) {
case OverflowPolicy::DropNewest:
if (m_mode_changing || !fits_budget()) {
++m_dropped_count;
return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated};
}
break;
case OverflowPolicy::DropOldest:
while ((m_mode_changing || !fits_budget()) && !m_queue.empty()) {
auto evicted = std::move(m_queue.front());
m_queue.pop_front();
--m_queued_entries;
m_queued_bytes -= std::min(m_queued_bytes, evicted.bytes);
++m_dropped_count;
mark_terminal_locked(evicted.ticket, TerminalOutcome::Dropped);
}
if (m_mode_changing || !fits_budget()) {
// All capacity is in flight -> drop new arrival.
++m_dropped_count;
return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated};
}
m_done_cv.notify_all();
break;
case OverflowPolicy::Block: {
if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) ||
is_active_logger_on_thread()) {
return Void::Result::fail(make_log_error(
LogErrorCode::would_deadlock,
"Blocking submit from inside logger delivery/worker would deadlock"));
}
struct StopNotifier {
std::condition_variable* cv;
void operator()() const noexcept { cv->notify_all(); }
};
std::optional<std::stop_callback<StopNotifier>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopNotifier{&m_space_cv});
}
while (!m_stop_admission && !m_closed &&
!m_quarantined.load(std::memory_order_acquire) &&
(m_mode_changing || !fits_budget())) {
if (options.stop.stop_requested()) {
return Void::Result::fail(make_log_error(
LogErrorCode::cancelled,
"Blocked log submission cancelled"));
}
if (Void::Async::is_deadline_expired(options, *m_options.clock)) {
return Void::Result::fail(make_log_error(
LogErrorCode::timeout,
"Blocked log submission timed out"));
}
if (options.deadline.has_value()) {
const auto rem = *options.deadline - m_options.clock->now();
const auto slice = std::min<std::chrono::nanoseconds>(
rem, std::chrono::milliseconds{5});
if (slice.count() > 0) {
m_space_cv.wait_for(lock, slice);
}
} else {
m_space_cv.wait(lock);
}
}
if (m_stop_admission || m_closed) {
return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated};
}
if (m_quarantined.load(std::memory_order_acquire)) {
return Void::Result::fail(make_log_error(
LogErrorCode::quarantined, m_last_error));
}
break;
}
}
if (m_next_ticket == std::numeric_limits<Ticket>::max()) {
m_stop_admission = true;
return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated};
}
const Ticket t = ++m_next_ticket;
++m_admitted_count;
++m_queued_entries;
m_queued_bytes += entry_bytes;
const bool trunc = entry.truncated;
m_queue.push_back(QueuedItem{t, entry_bytes, std::move(entry)});
lock.unlock();
m_work_cv.notify_one();
return SubmitReceipt{SubmitState::Accepted, t, trunc};
}
void Logger::relay(Entry entry) { (void)try_submit(std::move(entry)); }
void Logger::trace(std::string_view msg, std::source_location loc)
{
log(Level::Trace, msg, loc);
}
void Logger::debug(std::string_view msg, std::source_location loc)
{
log(Level::Debug, msg, loc);
}
void Logger::info(std::string_view msg, std::source_location loc)
{
log(Level::Info, msg, loc);
}
void Logger::warning(std::string_view msg, std::source_location loc)
{
log(Level::Warning, msg, loc);
}
void Logger::error(std::string_view msg, std::source_location loc)
{
log(Level::Error, msg, loc);
}
void Logger::fatal(std::string_view msg, std::source_location loc)
{
log(Level::Fatal, msg, loc);
}
Void::Result::Result<FlushReport>
Logger::flush_through(Ticket target, FlushOptions options)
{
if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) ||
is_active_logger_on_thread()) {
return Void::Result::fail(make_log_error(
LogErrorCode::would_deadlock,
"flush_through cannot run from inside active delivery callback or worker"));
}
std::unique_lock lock{m_mutex};
const Ticket resolved_target = target == 0 ? m_next_ticket : target;
if (m_mode.load(std::memory_order_acquire) == Mode::Buffered &&
!m_queue.empty()) {
std::vector<QueuedItem> batch;
const std::size_t batch_bytes = m_queued_bytes;
batch.reserve(m_queue.size());
while (!m_queue.empty()) {
batch.push_back(std::move(m_queue.front()));
m_queue.pop_front();
}
m_queued_entries = 0;
m_queued_bytes = 0;
m_in_flight_entries += batch.size();
m_in_flight_bytes += batch_bytes;
lock.unlock();
deliver_batch_unlocked(batch, false, batch_bytes);
lock.lock();
}
struct StopNotifier {
std::condition_variable* cv;
void operator()() const noexcept { cv->notify_all(); }
};
std::optional<std::stop_callback<StopNotifier>> stop_cb;
if (options.async.stop.stop_possible()) {
stop_cb.emplace(options.async.stop, StopNotifier{&m_done_cv});
}
FlushReport report;
while (m_completed_watermark < resolved_target &&
!m_stop_worker.load(std::memory_order_acquire)) {
if (options.async.stop.stop_requested()) {
report.cancelled = true;
break;
}
if (Void::Async::is_deadline_expired(options.async, *m_options.clock)) {
report.timed_out = true;
break;
}
m_work_cv.notify_all();
if (options.async.deadline.has_value()) {
const auto rem = *options.async.deadline - m_options.clock->now();
const auto slice = std::min<std::chrono::nanoseconds>(
rem, std::chrono::milliseconds{5});
if (slice.count() > 0) {
m_done_cv.wait_for(lock, slice);
}
} else {
m_done_cv.wait(lock);
}
}
report.delivered = m_wm_delivered;
report.dropped = m_wm_dropped;
report.failed = m_wm_failed;
report.watermark = m_completed_watermark;
lock.unlock();
if (!report.cancelled && !report.timed_out &&
options.durability == FlushDurability::SyncFiles) {
if (auto sres = sync_files(); !sres) {
return Void::Result::fail(std::move(sres).error());
}
}
return report;
}
Void::Result::Result<FlushReport> Logger::close(CloseOptions options)
{
if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) ||
is_active_logger_on_thread()) {
return Void::Result::fail(make_log_error(
LogErrorCode::would_deadlock,
"Logger::close cannot self-join from active callback or worker"));
}
Ticket target = 0;
{
std::lock_guard lock{m_mutex};
m_stop_admission = true;
target = m_next_ticket;
if (options.drop_pending) {
while (!m_queue.empty()) {
auto item = std::move(m_queue.front());
m_queue.pop_front();
--m_queued_entries;
m_queued_bytes -= std::min(m_queued_bytes, item.bytes);
++m_dropped_count;
mark_terminal_locked(item.ticket, TerminalOutcome::Dropped);
}
}
m_space_cv.notify_all();
m_work_cv.notify_all();
m_done_cv.notify_all();
}
auto rep = flush_through(
target, FlushOptions{FlushDurability::BufferFlush, options.async});
if (!rep) {
return rep;
}
if (!rep->timed_out && !rep->cancelled) {
m_stop_worker.store(true, std::memory_order_release);
m_work_cv.notify_all();
if (m_worker.joinable()) {
m_worker.join();
}
std::lock_guard lock{m_mutex};
m_closed = true;
}
return rep;
}
void Logger::request_close() noexcept
{
std::lock_guard lock{m_mutex};
m_stop_admission = true;
m_space_cv.notify_all();
}
void Logger::flush() { (void)flush_through(0, {}); }
LoggerStats Logger::stats() const
{
std::lock_guard lock{m_mutex};
return LoggerStats{
.queued_entries = m_queued_entries,
.queued_bytes = m_queued_bytes,
.in_flight_entries = m_in_flight_entries,
.in_flight_bytes = m_in_flight_bytes,
.admitted = m_admitted_count,
.delivered = m_delivered_count,
.dropped = m_dropped_count,
.failed = m_failed_count,
.reentrant_dropped =
m_reentrant_dropped.load(std::memory_order_relaxed),
.completed_watermark = m_completed_watermark,
.quarantined = m_quarantined.load(std::memory_order_acquire),
.closed = m_closed};
}
bool Logger::is_quarantined() const noexcept
{
return m_quarantined.load(std::memory_order_acquire);
}
std::string Logger::last_error_summary() const
{
std::lock_guard lock{m_mutex};
return m_last_error;
}
void Logger::reset_quarantine() noexcept
{
std::lock_guard lock{m_mutex};
m_quarantined.store(false, std::memory_order_release);
m_last_error.clear();
m_space_cv.notify_all();
}
Logger::ScopedContext Logger::push_scope(std::string name,
Level level,
std::source_location loc) noexcept
{
return ScopedContext(*this, std::move(name), level, loc);
}
void Logger::scope(std::string_view name,
Level level,
std::source_location loc)
{
emit_scope_boundary(Kind::ScopeEnter, name, level, loc);
emit_scope_boundary(
Kind::ScopeExit, name, level, std::source_location{});
}
std::span<const std::string> Logger::current_scopes() noexcept
{
return s_scope_stack;
}
Logger::Preset Logger::make_preset(Level level, std::string prefix) noexcept
{
return Preset(*this, level, std::move(prefix));
}
void Logger::on_flush(std::span<const Entry> entries)
{
for (const auto& entry : entries) {
write(entry);
}
}
Void::Result::Result<void> Logger::sync_files()
{
return Void::Result::fail(make_log_error(
LogErrorCode::unsupported_capability,
"Logger sink does not support durable file syncing"));
}
void Logger::emit_scope_boundary(Kind kind,
std::string_view name,
Level level,
std::source_location loc)
{
if (level < m_level.load(std::memory_order_relaxed)) {
return;
}
const auto fields = current_fields();
Entry entry{
.kind = kind,
.level = level,
.message = std::string(name),
.timestamp = std::chrono::system_clock::now(),
.location = loc,
.thread_id = std::this_thread::get_id(),
.scopes = s_scope_stack,
.fields = {fields.begin(), fields.end()},
};
(void)try_submit(std::move(entry));
}
void Logger::mark_terminal_locked(Ticket t, TerminalOutcome outcome)
{
m_pending_terminals.emplace(t, outcome);
advance_watermark_locked();
}
void Logger::advance_watermark_locked()
{
while (!m_pending_terminals.empty() &&
m_pending_terminals.begin()->first == m_completed_watermark + 1) {
const auto [ticket, outcome] = *m_pending_terminals.begin();
m_pending_terminals.erase(m_pending_terminals.begin());
m_completed_watermark = ticket;
switch (outcome) {
case TerminalOutcome::Delivered: ++m_wm_delivered; break;
case TerminalOutcome::Dropped: ++m_wm_dropped; break;
case TerminalOutcome::Failed: ++m_wm_failed; break;
}
}
}
void Logger::deliver_batch_unlocked(
std::vector<QueuedItem>& items,
bool stopping,
std::size_t total_bytes)
{
std::vector<Entry> raw_entries;
raw_entries.reserve(items.size());
for (const auto& item : items) {
raw_entries.push_back(item.entry);
}
bool failed = false;
std::string err_summary;
if (!stopping && !m_quarantined.load(std::memory_order_acquire)) {
ActiveLoggerGuard guard{this};
try {
on_flush(raw_entries);
} catch (const std::exception& e) {
failed = true;
err_summary = e.what();
} catch (...) {
failed = true;
err_summary = "Unknown sink exception";
}
}
if (err_summary.size() > kMaxErrorSummaryBytes) {
err_summary.resize(kMaxErrorSummaryBytes);
}
std::lock_guard lock{m_mutex};
m_in_flight_entries -= std::min(m_in_flight_entries, items.size());
m_in_flight_bytes -= std::min(m_in_flight_bytes, total_bytes);
for (const auto& item : items) {
if (stopping) {
++m_dropped_count;
mark_terminal_locked(item.ticket, TerminalOutcome::Dropped);
} else if (failed) {
++m_failed_count;
mark_terminal_locked(item.ticket, TerminalOutcome::Failed);
} else {
++m_delivered_count;
mark_terminal_locked(item.ticket, TerminalOutcome::Delivered);
}
}
if (failed) {
m_last_error = std::move(err_summary);
if (m_options.failure_policy == FailurePolicy::Quarantine) {
m_quarantined.store(true, std::memory_order_release);
}
}
m_space_cv.notify_all();
m_done_cv.notify_all();
}
void Logger::start_worker()
{
if (m_worker_started.load(std::memory_order_acquire)) {
return;
}
std::call_once(m_worker_once, [this] {
m_worker = std::thread([this] { worker_loop(); });
m_worker_started.store(true, std::memory_order_release);
});
}
void Logger::worker_loop()
{
m_worker_id.store(std::this_thread::get_id(), std::memory_order_release);
std::vector<QueuedItem> batch;
for (;;) {
std::size_t batch_bytes = 0;
bool stopping = false;
{
std::unique_lock lock{m_mutex};
m_work_cv.wait(lock, [this] {
return !m_queue.empty() ||
m_stop_worker.load(std::memory_order_acquire);
});
stopping = m_stop_worker.load(std::memory_order_acquire);
if (m_queue.empty() && stopping) {
return;
}
const std::size_t max_n = m_options.limits.batch_entries;
const std::size_t max_b = m_options.limits.batch_bytes;
while (!m_queue.empty() && batch.size() < max_n) {
const std::size_t item_bytes = m_queue.front().bytes;
if (!batch.empty() && batch_bytes + item_bytes > max_b) {
break;
}
batch_bytes += item_bytes;
batch.push_back(std::move(m_queue.front()));
m_queue.pop_front();
}
m_queued_entries -= std::min(m_queued_entries, batch.size());
m_queued_bytes -= std::min(m_queued_bytes, batch_bytes);
m_in_flight_entries += batch.size();
m_in_flight_bytes += batch_bytes;
}
deliver_batch_unlocked(batch, stopping, batch_bytes);
batch.clear();
}
}
} // namespace Void::Logging