aboutsummaryrefslogtreecommitdiffstats
path: root/yt/yt/library/tracing/jaeger/sampler.h
blob: 57119f044137952b2758e672e86f6932ed1924ba (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 "public.h"

#include <yt/yt/library/profiling/sensor.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 {

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

class TSamplerConfig
    : public NYTree::TYsonStruct
{
public:
    //! 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:
    TSampler();
    explicit TSampler(const TSamplerConfigPtr& config);

    void SampleTraceContext(const TString& user, const TTraceContextPtr& traceContext);

    void UpdateConfig(const TSamplerConfigPtr& config);

private:
    TAtomicIntrusivePtr<TSamplerConfig> Config_;

    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