aboutsummaryrefslogtreecommitdiffstats
path: root/includes/libs/Stats/StatsFactory.php
blob: b24d540fe86d3478da8d392c353a73b7f087ac68 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 * @file
 */

declare( strict_types=1 );

namespace Wikimedia\Stats;

use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use TypeError;
use Wikimedia\Stats\Emitters\EmitterInterface;
use Wikimedia\Stats\Emitters\NullEmitter;
use Wikimedia\Stats\Exceptions\InvalidConfigurationException;
use Wikimedia\Stats\Metrics\BaseMetric;
use Wikimedia\Stats\Metrics\CounterMetric;
use Wikimedia\Stats\Metrics\GaugeMetric;
use Wikimedia\Stats\Metrics\NullMetric;
use Wikimedia\Stats\Metrics\TimingMetric;

/**
 * This is the primary interface for validating metrics definitions,
 * caching defined metrics, and returning metric instances from cache
 * if previously defined.
 *
 * @author Cole White
 * @since 1.41
 */
class StatsFactory {

	private string $component;
	private StatsCache $cache;
	private EmitterInterface $emitter;
	private LoggerInterface $logger;
	private ?IBufferingStatsdDataFactory $statsdDataFactory = null;

	/**
	 * StatsFactory builds, configures, and caches Metrics.
	 *
	 * @param StatsCache $cache
	 * @param EmitterInterface $emitter
	 * @param LoggerInterface $logger
	 * @param string $component
	 */
	public function __construct(
		StatsCache $cache,
		EmitterInterface $emitter,
		LoggerInterface $logger,
		string $component = ''
	) {
		$this->component = StatsUtils::normalizeString( $component );
		$this->cache = $cache;
		$this->emitter = $emitter;
		$this->logger = $logger;
	}

	/**
	 * Returns a new StatsFactory instance prefixed by component.
	 *
	 * @param string $component
	 * @return StatsFactory
	 */
	public function withComponent( string $component ): StatsFactory {
		$statsFactory = new StatsFactory( $this->cache, $this->emitter, $this->logger, $component );
		return $statsFactory->withStatsdDataFactory( $this->statsdDataFactory );
	}

	public function withStatsdDataFactory( ?IBufferingStatsdDataFactory $statsdDataFactory ): StatsFactory {
		$this->statsdDataFactory = $statsdDataFactory;
		return $this;
	}

	/**
	 * Makes a new CounterMetric or fetches one from cache.
	 *
	 * If a collision occurs, returns a NullMetric to suppress exceptions.
	 *
	 * @param string $name
	 * @return CounterMetric|NullMetric
	 */
	public function getCounter( string $name ) {
		return $this->getMetric( $name, CounterMetric::class );
	}

	/**
	 * Makes a new GaugeMetric or fetches one from cache.
	 *
	 * If a collision occurs, returns a NullMetric to suppress exceptions.
	 *
	 * @param string $name
	 * @return GaugeMetric|NullMetric
	 */
	public function getGauge( string $name ) {
		return $this->getMetric( $name, GaugeMetric::class );
	}

	/**
	 * Makes a new TimingMetric or fetches one from cache.
	 *
	 * If a collision occurs, returns a NullMetric to suppress exceptions.
	 *
	 * @param string $name
	 * @return TimingMetric|NullMetric
	 */
	public function getTiming( string $name ) {
		return $this->getMetric( $name, TimingMetric::class );
	}

	/**
	 * Send all buffered metrics to the target and destroy the cache.
	 */
	public function flush(): void {
		$this->trackUsage();
		$this->emitter->send();
		$this->cache->clear();
	}

	/**
	 * Create a metric totaling all samples in the cache.
	 */
	private function trackUsage(): void {
		$accumulator = 0;
		foreach ( $this->cache->getAllMetrics() as $metric ) {
			$accumulator += $metric->getSampleCount();
		}
		$this->getCounter( 'stats_buffered_total' )
			->copyToStatsdAt( 'stats.statslib.buffered' )
			->incrementBy( $accumulator );
	}

	/**
	 * Fetches a metric from cache or makes a new metric.
	 *
	 * If a metric name collision occurs, returns a NullMetric to suppress runtime exceptions.
	 *
	 * @param string $name
	 * @param string $className
	 * @return CounterMetric|TimingMetric|GaugeMetric|NullMetric
	 */
	private function getMetric( string $name, string $className ) {
		$name = StatsUtils::normalizeString( $name );
		StatsUtils::validateMetricName( $name );
		try {
			$metric = $this->cache->get( $this->component, $name, $className );
		} catch ( TypeError | InvalidArgumentException | InvalidConfigurationException $ex ) {
			// Log the condition and give the caller something that will absorb calls.
			trigger_error( $ex->getMessage(), E_USER_WARNING );
			return new NullMetric;
		}
		if ( $metric === null ) {
			$baseMetric = new BaseMetric( $this->component, $name );
			$metric = new $className( $baseMetric->withStatsdDataFactory( $this->statsdDataFactory ), $this->logger );
			$this->cache->set( $this->component, $name, $metric );
		}
		return $metric->fresh();
	}

	/**
	 * Returns an instance of StatsFactory as a NULL value object
	 * as a default for consumer code to fall back to. This can also
	 * be used in tests environment where we don't need the full
	 * UDP emitter object.
	 *
	 * @since 1.42
	 *
	 * @return self
	 */
	public static function newNull(): self {
		return new self( new StatsCache(), new NullEmitter(), new NullLogger() );
	}
}