summaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/logging/tagged_payload.cpp
blob: 4133cc0bd55079f1d3653f5b9e8848a1559e4d44 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#include "tagged_payload.h"
#include "private.h"

#include <library/cpp/yt/assert/assert.h>

#include <library/cpp/yt/misc/tls.h>

#include <util/system/compiler.h>
#include <util/system/types.h>

#include <util/generic/bitops.h>

#include <algorithm>

namespace NYT::NLogging {

////////////////////////////////////////////////////////////////////////////////

namespace {

struct TPerThreadCache;

YT_DEFINE_THREAD_LOCAL(TPerThreadCache*, Cache);
YT_DEFINE_THREAD_LOCAL(bool, CacheDestroyed);

struct TPerThreadCache
{
    TSharedMutableRef Chunk;
    size_t ChunkOffset = 0;

    ~TPerThreadCache()
    {
        TTaggedPayloadBuilder::DisablePerThreadCache();
    }

    static YT_PREVENT_TLS_CACHING TPerThreadCache* GetCache()
    {
        auto& cache = Cache();
        [[likely]] if (cache) {
            return cache;
        }
        if (CacheDestroyed()) {
            return nullptr;
        }
        static thread_local TPerThreadCache CacheData;
        cache = &CacheData;
        return cache;
    }
};

TSharedMutableRef AllocateChunk(size_t size)
{
    return TSharedMutableRef::Allocate<::NYT::NLogging::NDetail::TMessageBufferTag>(size, {.InitializeStorage = false});
}

} // namespace

////////////////////////////////////////////////////////////////////////////////

void TTaggedPayloadBuilder::DisablePerThreadCache()
{
    Cache() = nullptr;
    CacheDestroyed() = true;
}

void TTaggedPayloadBuilder::DoReset()
{
    Buffer_.Reset();
}

void TTaggedPayloadBuilder::DoReserve(size_t newCapacity)
{
    auto oldLength = GetLength();
    newCapacity = FastClp2(newCapacity);

    auto newChunkSize = std::max(ChunkSize, newCapacity);
    // Hold the old buffer until the data is copied.
    auto oldBuffer = std::move(Buffer_);
    auto* cache = TPerThreadCache::GetCache();
    [[likely]] if (cache) {
        auto oldCapacity = End_ - Begin_;
        auto deltaCapacity = newCapacity - oldCapacity;
        if (End_ == cache->Chunk.Begin() + cache->ChunkOffset &&
            cache->ChunkOffset + deltaCapacity <= cache->Chunk.Size())
        {
            // Resize inplace.
            Buffer_ = cache->Chunk.Slice(cache->ChunkOffset - oldCapacity, cache->ChunkOffset + deltaCapacity);
            cache->ChunkOffset += deltaCapacity;
            End_ = Begin_ + newCapacity;
            return;
        }

        [[unlikely]] if (cache->ChunkOffset + newCapacity > cache->Chunk.Size()) {
            cache->Chunk = AllocateChunk(newChunkSize);
            cache->ChunkOffset = 0;
        }

        Buffer_ = cache->Chunk.Slice(cache->ChunkOffset, cache->ChunkOffset + newCapacity);
        cache->ChunkOffset += newCapacity;
    } else {
        Buffer_ = AllocateChunk(newChunkSize);
        newCapacity = newChunkSize;
    }
    if (oldLength > 0) {
        ::memcpy(Buffer_.Begin(), Begin_, oldLength);
    }
    Begin_ = Buffer_.Begin();
    End_ = Begin_ + newCapacity;
}

////////////////////////////////////////////////////////////////////////////////

void TTaggedPayloadWriter::DisablePerThreadCache()
{
    TTaggedPayloadBuilder::DisablePerThreadCache();
}

////////////////////////////////////////////////////////////////////////////////

TTaggedPayloadReader::TTaggedPayloadReader(const TTaggedLogEventPayload& payload)
    : Current_(payload.Underlying().Begin())
    , End_(payload.Underlying().End())
{ }

TStringBuf TTaggedPayloadReader::ReadMessage()
{
    YT_ASSERT(!MessageRead_);
    MessageRead_ = true;
    return ReadString();
}

std::optional<TTaggedPayloadReader::TTag> TTaggedPayloadReader::TryReadTag()
{
    YT_ASSERT(MessageRead_);
    if (Current_ == End_) {
        return std::nullopt;
    }
    auto keySize = ReadLength();
    bool wellKnown = (keySize & WellKnownTagFlag) != 0;
    auto key = ReadBytes(keySize & ~WellKnownTagFlag);
    auto value = ReadString();
    return TTag{.IsWellKnown = wellKnown, .Key = key, .Value = value};
}

ui32 TTaggedPayloadReader::ReadLength()
{
    YT_ASSERT(Current_ + sizeof(ui32) <= End_);
    ui32 size;
    ::memcpy(&size, Current_, sizeof(size));
    Current_ += sizeof(size);
    return size;
}

TStringBuf TTaggedPayloadReader::ReadBytes(ui32 size)
{
    YT_ASSERT(Current_ + size <= End_);
    TStringBuf result(Current_, size);
    Current_ += size;
    return result;
}

TStringBuf TTaggedPayloadReader::ReadString()
{
    return ReadBytes(ReadLength());
}

////////////////////////////////////////////////////////////////////////////////

TTaggedLogEventPayload MakeTaggedPayloadFromMessage(TStringBuf message)
{
    TTaggedPayloadWriter writer;
    writer.BeginMessage()->AppendString(message);
    writer.EndMessage();
    return writer.Finish();
}

TStringBuf GetMessageFromTaggedPayload(const TTaggedLogEventPayload& payload)
{
    return TTaggedPayloadReader(payload).ReadMessage();
}

std::string FormatTaggedPayload(const TTaggedLogEventPayload& payload)
{
    TTaggedPayloadReader reader(payload);
    std::string result(reader.ReadMessage());
    // Well-known tags (e.g. an error) are always written last -- the fluent |.With| chain
    // enforces this at the type level (see #TWellKnownTaggedLoggingGuard) -- so they render
    // after the |(...)| group on trailing lines in a single pass.
    bool parenOpen = false;
    while (auto tag = reader.TryReadTag()) {
        if (tag->IsWellKnown) {
            if (parenOpen) {
                result += ')';
                parenOpen = false;
            }
            result += '\n';
            result += tag->Value;
        } else {
            result += parenOpen ? ", " : " (";
            parenOpen = true;
            result += tag->Key;
            result += ": ";
            result += tag->Value;
        }
    }
    if (parenOpen) {
        result += ')';
    }
    return result;
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NLogging