Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.38% covered (warning)
59.38%
19 / 32
60.00% covered (warning)
60.00%
6 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
StatsFactory
59.38% covered (warning)
59.38%
19 / 32
60.00% covered (warning)
60.00%
6 / 10
24.33
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 withComponent
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 withStatsdDataFactory
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getCounter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getGauge
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTiming
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 flush
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 trackUsage
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getMetric
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 newNull
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 * @file
18 */
19
20declare( strict_types=1 );
21
22namespace Wikimedia\Stats;
23
24use IBufferingStatsdDataFactory;
25use InvalidArgumentException;
26use Psr\Log\LoggerInterface;
27use Psr\Log\NullLogger;
28use TypeError;
29use Wikimedia\Stats\Emitters\EmitterInterface;
30use Wikimedia\Stats\Emitters\NullEmitter;
31use Wikimedia\Stats\Exceptions\InvalidConfigurationException;
32use Wikimedia\Stats\Metrics\BaseMetric;
33use Wikimedia\Stats\Metrics\CounterMetric;
34use Wikimedia\Stats\Metrics\GaugeMetric;
35use Wikimedia\Stats\Metrics\NullMetric;
36use Wikimedia\Stats\Metrics\TimingMetric;
37
38/**
39 * StatsFactory Implementation
40 *
41 * This is the primary interface for validating metrics definitions
42 * caching defined metrics, and returning metric instances from cache
43 * if previously defined.
44 *
45 * @author Cole White
46 * @since 1.41
47 */
48class StatsFactory {
49
50    /** @var string */
51    private string $component;
52
53    /** @var StatsCache */
54    private StatsCache $cache;
55
56    /** @var EmitterInterface */
57    private EmitterInterface $emitter;
58
59    /** @var LoggerInterface */
60    private LoggerInterface $logger;
61
62    /** @var IBufferingStatsdDataFactory|null */
63    private ?IBufferingStatsdDataFactory $statsdDataFactory = null;
64
65    /**
66     * StatsFactory builds, configures, and caches Metrics.
67     *
68     * @param StatsCache $cache
69     * @param EmitterInterface $emitter
70     * @param LoggerInterface $logger
71     * @param string $component
72     */
73    public function __construct(
74        StatsCache $cache,
75        EmitterInterface $emitter,
76        LoggerInterface $logger,
77        string $component = ''
78    ) {
79        $this->component = StatsUtils::normalizeString( $component );
80        $this->cache = $cache;
81        $this->emitter = $emitter;
82        $this->logger = $logger;
83    }
84
85    /**
86     * Returns a new StatsFactory instance prefixed by component.
87     *
88     * @param string $component
89     * @return StatsFactory
90     */
91    public function withComponent( string $component ): StatsFactory {
92        $statsFactory = new StatsFactory( $this->cache, $this->emitter, $this->logger, $component );
93        return $statsFactory->withStatsdDataFactory( $this->statsdDataFactory );
94    }
95
96    public function withStatsdDataFactory( ?IBufferingStatsdDataFactory $statsdDataFactory ): StatsFactory {
97        $this->statsdDataFactory = $statsdDataFactory;
98        return $this;
99    }
100
101    /**
102     * Makes a new CounterMetric or fetches one from cache.
103     *
104     * If a collision occurs, returns a NullMetric to suppress exceptions.
105     *
106     * @param string $name
107     * @return CounterMetric|NullMetric
108     */
109    public function getCounter( string $name ) {
110        return $this->getMetric( $name, CounterMetric::class );
111    }
112
113    /**
114     * Makes a new GaugeMetric or fetches one from cache.
115     *
116     * If a collision occurs, returns a NullMetric to suppress exceptions.
117     *
118     * @param string $name
119     * @return GaugeMetric|NullMetric
120     */
121    public function getGauge( string $name ) {
122        return $this->getMetric( $name, GaugeMetric::class );
123    }
124
125    /**
126     * Makes a new TimingMetric or fetches one from cache.
127     *
128     * If a collision occurs, returns a NullMetric to suppress exceptions.
129     *
130     * @param string $name
131     * @return TimingMetric|NullMetric
132     */
133    public function getTiming( string $name ) {
134        return $this->getMetric( $name, TimingMetric::class );
135    }
136
137    /**
138     * Send all buffered metrics to the target and destroy the cache.
139     */
140    public function flush(): void {
141        $this->trackUsage();
142        $this->emitter->send();
143        $this->cache->clear();
144    }
145
146    /**
147     * Create a metric totaling all samples in the cache.
148     */
149    private function trackUsage(): void {
150        $accumulator = 0;
151        foreach ( $this->cache->getAllMetrics() as $metric ) {
152            $accumulator += $metric->getSampleCount();
153        }
154        $this->getCounter( 'stats_buffered_total' )
155            ->copyToStatsdAt( 'stats.statslib.buffered' )
156            ->incrementBy( $accumulator );
157    }
158
159    /**
160     * Fetches a metric from cache or makes a new metric.
161     *
162     * If a metric name collision occurs, returns a NullMetric to suppress runtime exceptions.
163     *
164     * @param string $name
165     * @param string $className
166     * @return CounterMetric|TimingMetric|GaugeMetric|NullMetric
167     */
168    private function getMetric( string $name, string $className ) {
169        $name = StatsUtils::normalizeString( $name );
170        StatsUtils::validateMetricName( $name );
171        try {
172            $metric = $this->cache->get( $this->component, $name, $className );
173        } catch ( TypeError | InvalidArgumentException | InvalidConfigurationException $ex ) {
174            // Log the condition and give the caller something that will absorb calls.
175            trigger_error( $ex->getMessage(), E_USER_WARNING );
176            return new NullMetric;
177        }
178        if ( $metric === null ) {
179            $baseMetric = new BaseMetric( $this->component, $name );
180            $metric = new $className( $baseMetric->withStatsdDataFactory( $this->statsdDataFactory ), $this->logger );
181            $this->cache->set( $this->component, $name, $metric );
182        }
183        return $metric->fresh();
184    }
185
186    /**
187     * Returns an instance of StatsFactory as a NULL value object
188     * as a default for consumer code to fall back to. This can also
189     * be used in tests environment where we don't need the full
190     * UDP emitter object.
191     *
192     * @since 1.42
193     *
194     * @return self
195     */
196    public static function newNull(): self {
197        return new self( new StatsCache(), new NullEmitter(), new NullLogger() );
198    }
199}