MediaWiki master
UDPEmitter.php
Go to the documentation of this file.
1<?php
7declare( strict_types=1 );
8
10
11use InvalidArgumentException;
12use UDPTransport;
17
26class UDPEmitter implements EmitterInterface {
27
28 private string $prefix;
29 private StatsCache $cache;
30 private FormatterInterface $formatter;
31 private ?UDPTransport $transport;
32 private int $payloadSize;
33
34 public function __construct( string $prefix, StatsCache $cache, FormatterInterface $formatter, ?string $target ) {
35 $this->prefix = $this->normalizePrefix( $prefix );
36 $this->cache = $cache;
37 $this->formatter = $formatter;
38 $this->transport = $target ? UDPTransport::newFromString( $target ) : null;
39 $this->payloadSize = UDPTransport::MAX_PAYLOAD_SIZE;
40 }
41
48 public function withPayloadSize( int $payloadSize ): UDPEmitter {
49 $this->payloadSize = $payloadSize;
50 return $this;
51 }
52
59 public function withTransport( UDPTransport $transport ): UDPEmitter {
60 $this->transport = $transport;
61 return $this;
62 }
63
64 private function normalizePrefix( string $prefix ): string {
65 if ( $prefix === '' ) {
66 throw new InvalidArgumentException( 'UDPEmitter: Prefix cannot be empty.' );
67 }
68 return StatsUtils::normalizeString( $prefix );
69 }
70
74 private function render(): array {
75 $output = [];
76 foreach ( $this->cache->getAllMetrics() as $metric ) {
77 // Skip NullMetric instances.
78 if ( get_class( $metric ) === NullMetric::class ) {
79 continue;
80 }
81 foreach ( $this->formatter->getFormattedSamples( $this->prefix, $metric ) as $formatted ) {
82 $output[] = $formatted;
83 }
84 }
85 return $output;
86 }
87
96 private function batch( array $samples, int $payloadSize ): void {
97 $payload = '';
98 foreach ( $samples as $sample ) {
99 if ( strlen( $payload ) + strlen( $sample ) + 1 > $payloadSize ) {
100 // Send this payload and make a new one
101 $this->transport->emit( $payload );
102 $payload = '';
103 }
104 $payload .= $sample . "\n";
105 }
106 // Send what is left in the payload
107 if ( strlen( $payload ) > 0 ) {
108 $this->transport->emit( $payload );
109 }
110 }
111
115 public function send(): void {
116 $this->batch( $this->render(), $this->payloadSize );
117 }
118}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:68
A generic class to send a message over UDP.
const MAX_PAYLOAD_SIZE
static newFromString( $info)
Metrics UDP Emitter Implementation.
__construct(string $prefix, StatsCache $cache, FormatterInterface $formatter, ?string $target)
withTransport(UDPTransport $transport)
Overrides the transport.
send()
Runs metrics and their samples from the cache through the formatter and sends them along....
withPayloadSize(int $payloadSize)
Sets payload size for batching.
Null Metric Implementation.
Singleton cache for Metric instances.
Functionality common to all metric types.