Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,13 @@ All notable changes to this project will be documented in this file.
validation for MDBX payload compression.
- Added an optional nlohmann::json frontend that maps JSON text or values into
the parser-neutral configuration model without performing runtime side effects.
- Added C++11 append-only atomic registration of prepared backend/formatter
batches with per-ID routing options and immutable ID-to-index results.

### Fixed

- Fixed legacy logger registration exception safety by constructing the new
registry snapshot before live mutation, and serialized registration with shutdown.
- Fixed a race in the MPSC `TaskExecutor::wait()` completion barrier that could
allow a wait to return before the final accepted task completed.

Expand Down
49 changes: 45 additions & 4 deletions docs/configuration-loading-RU.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ JSON value или text
-> ConfigurationDocument
-> validation и materialization
-> разрешение programmatic bindings
-> создание runtime logger'ов
-> подготовка runtime-пар (ConfigurationPreparedSet)
-> атомарная append-only регистрация (Logger)
```

Основная semantic model и runtime-слои не зависят от JSON-библиотеки. JSON
Expand Down Expand Up @@ -83,6 +84,46 @@ level logger'а и не создаёт formatter из materialized strategy. Д
`TRACE`; formatter schema v1 имеет тип `simple`, defaults публичного
`SimpleLogFormatter::Config`, а затем применяет явные pattern и JSON overrides.
Prepared result использует shared ownership в соответствии с существующим
factory API. `Logger::add_logger()` пока принимает unique ownership, поэтому
регистрация остаётся отдельной границей; подготовка не изменяет глобальный
singleton поэлементно.
factory API. Подготовка не изменяет глобальный singleton поэлементно.

## Атомарная регистрация

`Logger::register_configuration()` добавляет весь подготовленный batch одной
публикацией dispatch snapshot, сохраняя существующие индексы и strategy flags:

```cpp
logit::ConfigurationPreparedSet prepared; // Successful prepare_configuration() output.
logit::ConfigurationRegistrationOptions options;
options["application-file"].enabled = true;
options["application-file"].single_mode = false;
std::shared_ptr<const logit::ConfigurationRegistrationResult> registered;
if (logit::Logger::get_instance().register_configuration(
prepared, options, registered, diagnostics)) {
const int file_index = registered->indices.at("application-file");
logit::Logger::get_instance().set_logger_enabled(file_index, true);
}
```

Перед вызовом default-constructed `prepared` из примера должен быть заполнен
успешной подготовкой schema v1. Регистрация проверяет и вручную созданные наборы:
ID, non-null пары, level metadata, ID опций, object aliases и предел индексов.
Level и formatter повторно не применяются. Повторные ID отклоняются: это не
replacement, hot reload или идемпотентная повторная регистрация. Корректный пустой
batch возвращает пустую карту без публикации snapshot. Количество стратегий
ограничено `INT_MAX`, последний допустимый индекс — `INT_MAX - 1`.

При ошибке prepared input, живой registry и прежний result handle сохраняются;
diagnostics заменяются при каждом вызове. Исключения allocation могут выйти только
до commit с той же гарантией сохранения. Готовый результат передаётся без allocation.
При гонке с shutdown либо публикуется весь batch, который увидит shutdown, либо
регистрация завершается без изменений.

Один complete backend/formatter object не может принадлежать разным стратегиям,
включая legacy entries и предыдущие batch, независимо от concurrency capability.
Объект с двумя интерфейсами внутри одной стратегии требует общего control block.
Разные объекты с одним control block допустимы. Внешние shared owners сохраняют
lifetime, но не дают права на несинхронизированные вызовы, изменение или shutdown.
Уничтожение prepared set не удаляет зарегистрированные entries.
`Logger::add_logger(unique_ptr, unique_ptr, bool)` сохраняет прежний интерфейс
и также подготавливает snapshot до изменения registry. Reset/restart singleton
не добавлен.
51 changes: 47 additions & 4 deletions docs/configuration-loading.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ JSON value or text
-> ConfigurationDocument
-> validation and materialization
-> programmatic binding resolution
-> runtime logger construction
-> runtime preparation (ConfigurationPreparedSet)
-> atomic append-only registration (Logger)
```

The core semantic model and runtime layers do not depend on a JSON library.
Expand Down Expand Up @@ -89,6 +90,48 @@ a `ConfigurationPreparedSet` containing each stable logger ID, the concrete
`TRACE`; schema-v1 formatters use `simple` with the public
`SimpleLogFormatter::Config` defaults, then apply explicit pattern and JSON
overrides. The prepared result uses shared ownership to match the existing
factory API. `Logger::add_logger()` currently accepts unique ownership and is
therefore a separate registration boundary; preparation does not mutate the
global singleton incrementally.
factory API. Preparation does not mutate the global singleton incrementally.

## Atomic registration

`Logger::register_configuration()` appends the complete prepared batch with one
dispatch snapshot publication. Existing indices and strategy flags are preserved:

```cpp
logit::ConfigurationPreparedSet prepared; // Successful prepare_configuration() output.
logit::ConfigurationRegistrationOptions options;
// Optional per-ID overrides; unknown IDs are errors.
options["application-file"].enabled = true;
options["application-file"].single_mode = false;
std::shared_ptr<const logit::ConfigurationRegistrationResult> registered;
if (logit::Logger::get_instance().register_configuration(
prepared, options, registered, diagnostics)) {
const int file_index = registered->indices.at("application-file");
logit::Logger::get_instance().set_logger_enabled(file_index, true);
}
```

The caller supplies a schema-v1 prepared set; the default-constructed set in
this snippet must first be populated by a successful preparation call. The
operation validates manually constructed sets too: IDs, non-null pairs, level
metadata, routing-option IDs, object aliases, and index capacity. Levels and
formatters are not reapplied during registration. Repeated IDs fail; this is
not replacement, hot reload, or idempotent re-registration. Valid empty batches
return an empty mapping without publishing a snapshot. Registry count is capped
at `INT_MAX`, so the last supported index is `INT_MAX - 1`.

Failures preserve the prepared input, live registry, and previous result handle;
diagnostics are replaced on each call. Allocation exceptions may propagate only
before commit, with the same preservation guarantee. The complete result is
prepared before commit and handed off without allocation. A race with shutdown
either commits the whole batch for shutdown to observe, or fails unchanged.

The same complete backend/formatter object cannot appear in different strategies,
including legacy entries and earlier batches, regardless of concurrency capability.
A combined backend/formatter in one strategy requires shared ownership of one
control block. Distinct objects sharing a control block are allowed. Retained
prepared-set pointers preserve lifetime, not permission for unsynchronized direct
invocation, mutation, or shutdown. Destroying the prepared set does not remove
registered entries. `Logger::add_logger(unique_ptr, unique_ptr, bool)` remains
available with its existing behavior and now also prepares its snapshot before
mutating the registry. No singleton reset/restart API is introduced.
4 changes: 2 additions & 2 deletions docs/future-plans.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ Legend:
the existing backend configuration. The proposed contract is recorded in
[ADR 0009](adr/0009-configuration-loading-contract.md). The parser-neutral
model, built-in materialization/runtime layers, and optional JSON text/value
frontend are delivered; atomic registration is specified separately in
[ADR 0010](adr/0010-atomic-configuration-registration.md), while
frontend and append-only atomic registration are delivered; registration
follows [ADR 0010](adr/0010-atomic-configuration-registration.md), while
file-loading convenience and a properties frontend remain follow-ups. File
watching/hot reload is not part of this API.
- [ ] **Extended filtering** — evaluate source/file, message, tag/MDC, and
Expand Down
1 change: 1 addition & 0 deletions include/logit_cpp/logit.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "logit/loggers.hpp"
#include "logit/configuration_runtime.hpp"
#include "logit/configuration_runtime_builtins.hpp"
#include "logit/configuration_registration.hpp"
#ifdef LOGIT_WITH_JSON_CONFIG
#include "logit/configuration_json.hpp"
#endif
Expand Down
Loading
Loading