userver: userver/formats/json/masking.hpp Source File
Loading...
Searching...
No Matches
masking.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/masking.hpp
4/// @brief Streaming JSON masking for bounded log output.
5
6#include <cstddef>
7#include <memory>
8#include <string>
9#include <string_view>
10#include <vector>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace formats::json {
15
16/// @brief A sequence of object member names. Arrays do not consume a segment.
17using MaskingPath = std::vector<std::string>;
18
19/// @brief Whether paths select hidden or visible subtrees.
20enum class MaskingListMode {
21 kBlacklist, ///< Mask the selected paths and their complete subtrees.
22 kWhitelist, ///< Preserve only the selected paths and their subtrees.
23};
24
25struct MaskedJson;
26
27/// @brief Immutable compiled masking rules, cheaply copyable and safe to share.
28/// A whole segment "*" matches any member name unless an exact child exists.
29/// Exact and wildcard branches are not merged or retried on a later mismatch.
30/// An empty path selects the root. Empty blacklists preserve everything;
31/// empty whitelists mask everything. Incomplete whitelist paths hide scalars.
32class MaskingRules final {
33public:
34 /// @brief Compile paths once for reuse by subsequent masking calls.
35 explicit MaskingRules(
36 const std::vector<MaskingPath>& paths = {},
38 );
39
40private:
41 struct Impl;
42 std::shared_ptr<const Impl> impl_;
43
44 friend MaskedJson MaskJson(std::string_view, const MaskingRules&, std::size_t);
45};
46
47/// @brief Masked JSON or its UTF-8-safe prefix when the output budget is reached.
48struct MaskedJson final {
49 std::string text; ///< Complete JSON or a UTF-8-safe prefix without a suffix.
50 bool limit_reached; ///< Processing stopped because the output budget was reached.
51};
52
53/// @brief Mask JSON using RapidJSON streaming parsing and serialization.
54/// Scalars become "...", objects "{...}", and arrays "[...]".
55/// Output is compact JSON until @p log_limit bytes are produced; then parsing
56/// stops and the result may be incomplete JSON. No suffix is added.
57/// Reaching the budget, even exactly, sets @ref formats::json::MaskedJson::limit_reached;
58/// the unread input suffix is not validated. A zero budget skips parsing.
59/// A single input token may be fully decoded before its SAX callback runs.
60/// @throws formats::json::ParseException on invalid JSON, invalid UTF-8, or
61/// excessive nesting encountered before reaching the budget. Error messages
62/// contain no input fragments. Rules and input are never modified.
63MaskedJson MaskJson(std::string_view input, const MaskingRules& rules, std::size_t log_limit);
64
65} // namespace formats::json
66
67USERVER_NAMESPACE_END