Debian Codegraph @

includes/libs/Stats/StatsFactory.php

raw symbols SCIP
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
20 declare( strict_types=1 );
21
22 namespace Wikimedia\Stats;
23
24 use InvalidArgumentException;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use TypeError;
28 use Wikimedia\Stats\Emitters\EmitterInterface;
29 use Wikimedia\Stats\Emitters\NullEmitter;
30 use Wikimedia\Stats\Exceptions\InvalidConfigurationException;
31 use Wikimedia\Stats\Metrics\BaseMetric;
32 use Wikimedia\Stats\Metrics\CounterMetric;
33 use Wikimedia\Stats\Metrics\GaugeMetric;
34 use Wikimedia\Stats\Metrics\NullMetric;
35 use Wikimedia\Stats\Metrics\TimingMetric;
36
37 /**
38 * StatsFactory Implementation
39 *
40 * This is the primary interface for validating metrics definitions
41 * caching defined metrics, and returning metric instances from cache
42 * if previously defined.
43 *
44 * @author Cole White
45 * @since 1.41
46 */
47 class StatsFactory {
48
49 /** @var string */
50 private string $component;
51
52 /** @var StatsCache */
53 private StatsCache $cache;
54
55 /** @var EmitterInterface */
56 private EmitterInterface $emitter;
57
58 /** @var LoggerInterface */
59 private LoggerInterface $logger;
60
61 /** @var IBufferingStatsdDataFactory|null */
62 private ?IBufferingStatsdDataFactory $statsdDataFactory = null;
63
64 /**
65 * StatsFactory builds, configures, and caches Metrics.
66 *
67 * @param StatsCache $cache
68 * @param EmitterInterface $emitter
69 * @param LoggerInterface $logger
70 * @param string $component
71 */
72 public function __construct(
73 StatsCache $cache,
74 EmitterInterface $emitter,
75 LoggerInterface $logger,
76 string $component = ''
77 ) {
78 $this->component = StatsUtils::normalizeString( $component );
79 $this->cache = $cache;
80 $this->emitter = $emitter;
81 $this->logger = $logger;
82 }
83
84 /**
85 * Returns a new StatsFactory instance prefixed by component.
86 *
87 * @param string $component
88 * @return StatsFactory
89 */
90 public function withComponent( string $component ): StatsFactory {
91 $statsFactory = new StatsFactory( $this->cache, $this->emitter, $this->logger, $component );
92 return $statsFactory->withStatsdDataFactory( $this->statsdDataFactory );
93 }
94
95 public function withStatsdDataFactory( ?IBufferingStatsdDataFactory $statsdDataFactory ): StatsFactory {
96 $this->statsdDataFactory = $statsdDataFactory;
97 return $this;
98 }
99
100 /**
101 * Makes a new CounterMetric or fetches one from cache.
102 *
103 * If a collision occurs, returns a NullMetric to suppress exceptions.
104 *
105 * @param string $name
106 * @return CounterMetric|NullMetric
107 */
108 public function getCounter( string $name ) {
109 return $this->getMetric( $name, CounterMetric::class );
110 }
111
112 /**
113 * Makes a new GaugeMetric or fetches one from cache.
114 *
115 * If a collision occurs, returns a NullMetric to suppress exceptions.
116 *
117 * @param string $name
118 * @return GaugeMetric|NullMetric
119 */
120 public function getGauge( string $name ) {
121 return $this->getMetric( $name, GaugeMetric::class );
122 }
123
124 /**
125 * Makes a new TimingMetric or fetches one from cache.
126 *
127 * If a collision occurs, returns a NullMetric to suppress exceptions.
128 *
129 * @param string $name
130 * @return TimingMetric|NullMetric
131 */
132 public function getTiming( string $name ) {
133 return $this->getMetric( $name, TimingMetric::class );
134 }
135
136 /**
137 * Send all buffered metrics to the target and destroy the cache.
138 */
139 public function flush(): void {
140 $this->trackUsage();
141 $this->emitter->send();
142 $this->cache->clear();
143 }
144
145 /**
146 * Create a metric totaling all samples in the cache.
147 */
148 private function trackUsage(): void {
149 $accumulator = 0;
150 foreach ( $this->cache->getAllMetrics() as $metric ) {
151 $accumulator += $metric->getSampleCount();
152 }
153 $this->getCounter( 'stats_buffered_total' )
154 ->copyToStatsdAt( 'stats.statslib.buffered' )
155 ->incrementBy( $accumulator );
156 }
157
158 /**
159 * Fetches a metric from cache or makes a new metric.
160 *
161 * If a metric name collision occurs, returns a NullMetric to suppress runtime exceptions.
162 *
163 * @param string $name
164 * @param string $className
165 * @return CounterMetric|TimingMetric|GaugeMetric|NullMetric
166 */
167 private function getMetric( string $name, string $className ) {
168 $name = StatsUtils::normalizeString( $name );
169 StatsUtils::validateMetricName( $name );
170 try {
171 $metric = $this->cache->get( $this->component, $name, $className );
172 } catch ( TypeError | InvalidArgumentException | InvalidConfigurationException $ex ) {
173 // Log the condition and give the caller something that will absorb calls.
174 trigger_error( $ex->getMessage(), E_USER_WARNING );
175 return new NullMetric;
176 }
177 if ( $metric === null ) {
178 $baseMetric = new BaseMetric( $this->component, $name );
179 $metric = new $className( $baseMetric->withStatsdDataFactory( $this->statsdDataFactory ), $this->logger );
180 $this->cache->set( $this->component, $name, $metric );
181 }
182 return $metric->fresh();
183 }
184
185 /**
186 * Returns an instance of StatsFactory as a NULL value object
187 * as a default for consumer code to fall back to. This can also
188 * be used in tests environment where we don't need the full
189 * UDP emitter object.
190 *
191 * @since 1.42
192 *
193 * @return self
194 */
195 public static function newNull(): self {
196 return new self( new StatsCache(), new NullEmitter(), new NullLogger() );
197 }
198 }