aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/wilson/wilson_span.h
blob: a6ea2d921cd34ece13294cdd6a9d6dc299b61289 (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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#pragma once

#include <library/cpp/actors/core/actor.h>
#include <library/cpp/actors/core/actorsystem.h>
#include <library/cpp/actors/wilson/protos/trace.pb.h>
#include <util/generic/hash.h>
#include <util/datetime/cputimer.h>

#include "wilson_trace.h"

namespace NWilson {

    enum class ERelation {
        FollowsFrom,
        ChildOf,
    };

    namespace NTraceProto = opentelemetry::proto::trace::v1;
    namespace NCommonProto = opentelemetry::proto::common::v1;

    struct TArrayValue;
    struct TKeyValueList;
    struct TBytes;

    using TAttributeValue = std::variant<
        TString,
        bool,
        i64,
        double,
        TArrayValue,
        TKeyValueList,
        TBytes
    >;

    struct TArrayValue : std::vector<TAttributeValue> {};
    struct TKeyValueList : THashMap<TString, TAttributeValue> {};
    struct TBytes : TString {};

    void SerializeKeyValue(TString key, TAttributeValue value, NCommonProto::KeyValue *pb);

    enum class EFlags : ui32 {
        NONE = 0,
        AUTO_END = 1,
    };

    Y_DECLARE_FLAGS(TFlags, EFlags)
    Y_DECLARE_OPERATORS_FOR_FLAGS(TFlags)

    class TSpan {
        struct TData {
            const TInstant StartTime;
            const ui64 StartCycles;
            const TTraceId TraceId;
            NTraceProto::Span Span;
            TFlags Flags;
            int UncaughtExceptions = std::uncaught_exceptions();
            bool Sent = false;

            TData(TInstant startTime, ui64 startCycles, TTraceId traceId, TFlags flags)
                : StartTime(startTime)
                , StartCycles(startCycles)
                , TraceId(std::move(traceId))
                , Flags(flags)
            {}

            ~TData() {
                Y_VERIFY_DEBUG(Sent);
            }
        };

        std::unique_ptr<TData> Data;

    public:
        TSpan() = default;
        TSpan(const TSpan&) = delete;
        TSpan(TSpan&&) = default;

        TSpan(ui8 verbosity, TTraceId parentId, std::optional<TString> name, TFlags flags = EFlags::NONE)
            : Data(parentId
                    ? std::make_unique<TData>(TInstant::Now(), GetCycleCount(), parentId.Span(verbosity), flags)
                    : nullptr)
        {
            if (Y_UNLIKELY(*this)) {
                if (verbosity <= parentId.GetVerbosity()) {
                    if (!parentId.IsRoot()) {
                        Data->Span.set_parent_span_id(parentId.GetSpanIdPtr(), parentId.GetSpanIdSize());
                    }
                    Data->Span.set_start_time_unix_nano(Data->StartTime.NanoSeconds());
                    Data->Span.set_kind(opentelemetry::proto::trace::v1::Span::SPAN_KIND_INTERNAL);

                    if (name) {
                        Name(std::move(*name));
                    }

                    Attribute("node_id", NActors::TActivationContext::ActorSystem()->NodeId);
                } else {
                    Data->Sent = true; // ignore this span due to verbosity mismatch, still allowing child spans to be created
                }
            }
        }

        ~TSpan() {
            if (Y_UNLIKELY(*this)) {
                if (std::uncaught_exceptions() != Data->UncaughtExceptions) {
                    EndError("span terminated due to stack unwinding");
                } else if (Data->Flags & EFlags::AUTO_END) {
                    End();
                } else {
                    EndError("unterminated span");
                }
            }
        }

        TSpan& operator =(const TSpan&) = delete;

        TSpan& operator =(TSpan&& other) {
            if (this != &other) {
                if (Y_UNLIKELY(*this)) {
                    EndError("TSpan instance incorrectly overwritten");
                }
                Data = std::exchange(other.Data, nullptr);
            }
            return *this;
        }

        explicit operator bool() const {
            return Data && !Data->Sent;
        }

        TSpan& EnableAutoEnd() {
            if (Y_UNLIKELY(*this)) {
                Data->Flags |= EFlags::AUTO_END;
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        TSpan& Relation(ERelation /*relation*/) {
            if (Y_UNLIKELY(*this)) {
                // update relation in data somehow
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        TSpan& Name(TString name) {
            if (Y_UNLIKELY(*this)) {
                Data->Span.set_name(std::move(name));
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        TSpan& Attribute(TString name, TAttributeValue value) {
            if (Y_UNLIKELY(*this)) {
                SerializeKeyValue(std::move(name), std::move(value), Data->Span.add_attributes());
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        TSpan& Event(TString name, TKeyValueList attributes) {
            if (Y_UNLIKELY(*this)) {
                auto *event = Data->Span.add_events();
                event->set_time_unix_nano(TimeUnixNano());
                event->set_name(std::move(name));
                for (auto&& [key, value] : attributes) {
                    SerializeKeyValue(std::move(key), std::move(value), event->add_attributes());
                }
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        TSpan& Link(const TTraceId& traceId, TKeyValueList attributes) {
            if (Y_UNLIKELY(*this)) {
                auto *link = Data->Span.add_links();
                link->set_trace_id(traceId.GetTraceIdPtr(), traceId.GetTraceIdSize());
                link->set_span_id(traceId.GetSpanIdPtr(), traceId.GetSpanIdSize());
                for (auto&& [key, value] : attributes) {
                    SerializeKeyValue(std::move(key), std::move(value), link->add_attributes());
                }
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
            return *this;
        }

        void EndOk() {
            if (Y_UNLIKELY(*this)) {
                auto *status = Data->Span.mutable_status();
                status->set_code(NTraceProto::Status::STATUS_CODE_OK);
                End();
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
        }

        void EndError(TString error) {
            if (Y_UNLIKELY(*this)) {
                auto *status = Data->Span.mutable_status();
                status->set_code(NTraceProto::Status::STATUS_CODE_ERROR);
                status->set_message(std::move(error));
                End();
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
        }

        void End() {
            if (Y_UNLIKELY(*this)) {
                Data->Span.set_trace_id(Data->TraceId.GetTraceIdPtr(), Data->TraceId.GetTraceIdSize());
                Data->Span.set_span_id(Data->TraceId.GetSpanIdPtr(), Data->TraceId.GetSpanIdSize());
                Data->Span.set_end_time_unix_nano(TimeUnixNano());
                Send();
            } else {
                Y_VERIFY_DEBUG(!Data, "span has been ended");
            }
        }

        TTraceId GetTraceId() const {
            return Data ? TTraceId(Data->TraceId) : TTraceId();
        }

    private:
        void Send();

        ui64 TimeUnixNano() const {
            const TInstant now = Data->StartTime + CyclesToDuration(GetCycleCount() - Data->StartCycles);
            return now.NanoSeconds();
        }
    };

} // NWilson