MediaWiki master
UDPEmitter.php
Go to the documentation of this file.
1<?php
20declare( strict_types=1 );
21
23
24use InvalidArgumentException;
25use UDPTransport;
30
39class UDPEmitter implements EmitterInterface {
40
42 private string $prefix;
43
45 private StatsCache $cache;
46
48 private FormatterInterface $formatter;
49
51 private ?UDPTransport $transport;
52
54 private int $payloadSize;
55
56 public function __construct( string $prefix, StatsCache $cache, FormatterInterface $formatter, ?string $target ) {
57 $this->prefix = $this->normalizePrefix( $prefix );
58 $this->cache = $cache;
59 $this->formatter = $formatter;
60 $this->transport = $target ? UDPTransport::newFromString( $target ) : null;
61 $this->payloadSize = UDPTransport::MAX_PAYLOAD_SIZE;
62 }
63
70 public function withPayloadSize( int $payloadSize ): UDPEmitter {
71 $this->payloadSize = $payloadSize;
72 return $this;
73 }
74
81 public function withTransport( UDPTransport $transport ): UDPEmitter {
82 $this->transport = $transport;
83 return $this;
84 }
85
86 private function normalizePrefix( string $prefix ): string {
87 if ( $prefix === '' ) {
88 throw new InvalidArgumentException( 'UDPEmitter: Prefix cannot be empty.' );
89 }
90 return StatsUtils::normalizeString( $prefix );
91 }
92
98 private function render(): array {
99 $output = [];
100 foreach ( $this->cache->getAllMetrics() as $metric ) {
101 // Skip NullMetric instances.
102 if ( get_class( $metric ) === NullMetric::class ) {
103 continue;
104 }
105 foreach ( $this->formatter->getFormattedSamples( $this->prefix, $metric ) as $formatted ) {
106 $output[] = $formatted;
107 }
108 }
109 return $output;
110 }
111
120 private function batch( array $samples, int $payloadSize ): void {
121 $payload = '';
122 foreach ( $samples as $sample ) {
123 if ( strlen( $payload ) + strlen( $sample ) + 1 < $payloadSize ) {
124 $payload .= $sample . "\n";
125 } else {
126 // Send this payload and make a new one
127 $this->transport->emit( $payload );
128 $payload = '';
129 }
130 }
131 // Send what is left in the payload
132 if ( strlen( $payload ) > 0 ) {
133 $this->transport->emit( $payload );
134 }
135 }
136
140 public function send(): void {
141 $this->batch( $this->render(), $this->payloadSize );
142 }
143}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
A generic class to send a message over UDP.
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.
StatsUtils Implementation.