summaryrefslogtreecommitdiff
path: root/vendor/jonahgeorge/jaeger-client-php/src/Jaeger/Sampler/ProbabilisticSampler.php
blob: cb265d01e7a0dcb9513f6a6c42b8e130776145d3 (plain)
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
<?php

namespace Jaeger\Sampler;

use OutOfBoundsException;
use const Jaeger\SAMPLER_PARAM_TAG_KEY;
use const Jaeger\SAMPLER_TYPE_PROBABILISTIC;
use const Jaeger\SAMPLER_TYPE_TAG_KEY;

/**
 * A sampler that randomly samples a certain percentage of traces specified
 * by the samplingRate, in the range between 0.0 and 1.0.
 *
 * @package Jaeger\Sampler
 */
class ProbabilisticSampler implements SamplerInterface
{
    /**
     * The sampling rate rate between 0.0 and 1.0.
     *
     * @var float
     */
    private $rate;

    /**
     * A list of the sampler tags.
     *
     * @var array
     */
    private $tags = [];

    /**
     * The boundary of the sample sampling rate.
     *
     * @var float
     */
    private $boundary;

    /**
     * ProbabilisticSampler constructor.
     *
     * @param float $rate
     * @throws OutOfBoundsException
     */
    public function __construct(float $rate)
    {
        $this->tags = [
            SAMPLER_TYPE_TAG_KEY => SAMPLER_TYPE_PROBABILISTIC,
            SAMPLER_PARAM_TAG_KEY => $rate,
        ];

        if ($rate < 0.0 || $rate > 1.0) {
            throw new OutOfBoundsException('Sampling rate must be between 0.0 and 1.0.');
        }

        $this->rate = $rate;
        if ($rate < 0.5) {
            $this->boundary = (int)($rate * PHP_INT_MAX);
        } else {
            // more precise calculation due to int and float having different precision near PHP_INT_MAX
            $this->boundary = PHP_INT_MAX - (int)((1 - $rate) * PHP_INT_MAX);
        }
    }

    /**
     * {@inheritdoc}
     *
     * @param string $traceId   The traceId on the span.
     * @param string $operation The operation name set on the span.
     * @return array
     */
    public function isSampled(string $traceId, string $operation = ''): array
    {
        return [($traceId < $this->boundary), $this->tags];
    }

    /**
     * {@inheritdoc}
     *
     * Only implemented to satisfy the sampler interface.
     *
     * @return void
     */
    public function close()
    {
        // nothing to do
    }
}