summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/sdk/Metrics/Stream/MetricAggregator.php
blob: b1328eb0781b59e1e1818562480d3a4aa875ab99 (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
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Metrics\Stream;

use OpenTelemetry\Context\ContextInterface;
use OpenTelemetry\SDK\Common\Attribute\AttributesInterface;
use OpenTelemetry\SDK\Metrics\AggregationInterface;
use OpenTelemetry\SDK\Metrics\AttributeProcessorInterface;
use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarReservoirInterface;
use function serialize;

/**
 * @internal
 */
final class MetricAggregator implements MetricAggregatorInterface
{
    private ?AttributeProcessorInterface $attributeProcessor;
    private AggregationInterface $aggregation;
    private ?ExemplarReservoirInterface $exemplarReservoir;

    /** @var array<AttributesInterface> */
    private array $attributes = [];
    private array $summaries = [];

    public function __construct(
        ?AttributeProcessorInterface $attributeProcessor,
        AggregationInterface $aggregation,
        ?ExemplarReservoirInterface $exemplarReservoir = null
    ) {
        $this->attributeProcessor = $attributeProcessor;
        $this->aggregation = $aggregation;
        $this->exemplarReservoir = $exemplarReservoir;
    }

    /**
     * @param float|int $value
     */
    public function record($value, AttributesInterface $attributes, ContextInterface $context, int $timestamp): void
    {
        $filteredAttributes = $this->attributeProcessor !== null
            ? $this->attributeProcessor->process($attributes, $context)
            : $attributes;
        $raw = $filteredAttributes->toArray();
        $index = $raw !== [] ? serialize($raw) : 0;
        $this->attributes[$index] ??= $filteredAttributes;
        $this->aggregation->record(
            $this->summaries[$index] ??= $this->aggregation->initialize(),
            $value,
            $attributes,
            $context,
            $timestamp,
        );

        if ($this->exemplarReservoir !== null) {
            $this->exemplarReservoir->offer($index, $value, $attributes, $context, $timestamp);
        }
    }

    public function collect(int $timestamp): Metric
    {
        $exemplars = $this->exemplarReservoir
            ? $this->exemplarReservoir->collect($this->attributes)
            : [];
        $metric = new Metric($this->attributes, $this->summaries, $timestamp, $exemplars);

        $this->attributes = [];
        $this->summaries = [];

        return $metric;
    }
}