aboutsummaryrefslogtreecommitdiffstats
path: root/yt/yt/library/tracing/jaeger/sampler.h
blob: 03ada6bf9f3b300ce7ac81a63b060278584cf5d7 (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
#pragma once

#include "private.h"

#include <yt/yt/library/syncmap/map.h>

#include <yt/yt/core/ytree/yson_struct.h>

#include <library/cpp/yt/memory/atomic_intrusive_ptr.h>

namespace NYT::NTracing {

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

struct TSamplerConfig
    : public NYTree::TYsonStruct
{
    //! Request is sampled with probability P.
    double GlobalSampleRate;

    //! Additionally, request is sampled with probability P(user).
    THashMap<TString, double> UserSampleRate;

    //! Spans are sent to specified endpoint.
    THashMap<TString, TString> UserEndpoint;

    //! Additionally, sample first N requests for each user in the window.
    ui64 MinPerUserSamples;
    TDuration MinPerUserSamplesPeriod;

    //! Clear sampled from from incoming user request.
    THashMap<TString, bool> ClearSampledFlag;

    REGISTER_YSON_STRUCT(TSamplerConfig);

    static void Register(TRegistrar registrar);
};

DEFINE_REFCOUNTED_TYPE(TSamplerConfig)

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

class TSampler
    : public TRefCounted
{
public:
    explicit TSampler(
        TSamplerConfigPtr config = New<TSamplerConfig>(),
        const NProfiling::TProfiler& profiler = TracingProfiler());

    void SampleTraceContext(const std::string& user, const TTraceContextPtr& traceContext);

    void UpdateConfig(TSamplerConfigPtr config);

private:
    TAtomicIntrusivePtr<TSamplerConfig> Config_;

    NProfiling::TProfiler Profiler_;

    struct TUserState final
    {
        std::atomic<ui64> Sampled = {0};
        std::atomic<NProfiling::TCpuInstant> LastReset = {0};

        bool TrySampleByMinCount(ui64 minCount, NProfiling::TCpuDuration period);

        NProfiling::TCounter TracesSampledByUser;
        NProfiling::TCounter TracesSampledByProbability;
    };

    NConcurrency::TSyncMap<TString, TIntrusivePtr<TUserState>> Users_;
    NProfiling::TCounter TracesSampled_;
};

DEFINE_REFCOUNTED_TYPE(TSampler)

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

} // namespace NYT::NTracing