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
41 private string $prefix;
42 private StatsCache $cache;
43 private FormatterInterface $formatter;
44 private ?UDPTransport $transport;
45 private int $payloadSize;
46
47 public function __construct( string $prefix, StatsCache $cache, FormatterInterface $formatter, ?string $target ) {
48 $this->prefix = $this->normalizePrefix( $prefix );
49 $this->cache = $cache;
50 $this->formatter = $formatter;
51 $this->transport = $target ? UDPTransport::newFromString( $target ) : null;
52 $this->payloadSize = UDPTransport::MAX_PAYLOAD_SIZE;
53 }
54
61 public function withPayloadSize( int $payloadSize ): UDPEmitter {
62 $this->payloadSize = $payloadSize;
63 return $this;
64 }
65
72 public function withTransport( UDPTransport $transport ): UDPEmitter {
73 $this->transport = $transport;
74 return $this;
75 }
76
77 private function normalizePrefix( string $prefix ): string {
78 if ( $prefix === '' ) {
79 throw new InvalidArgumentException( 'UDPEmitter: Prefix cannot be empty.' );
80 }
81 return StatsUtils::normalizeString( $prefix );
82 }
83
87 private function render(): array {
88 $output = [];
89 foreach ( $this->cache->getAllMetrics() as $metric ) {
90 // Skip NullMetric instances.
91 if ( get_class( $metric ) === NullMetric::class ) {
92 continue;
93 }
94 foreach ( $this->formatter->getFormattedSamples( $this->prefix, $metric ) as $formatted ) {
95 $output[] = $formatted;
96 }
97 }
98 return $output;
99 }
100
109 private function batch( array $samples, int $payloadSize ): void {
110 $payload = '';
111 foreach ( $samples as $sample ) {
112 if ( strlen( $payload ) + strlen( $sample ) + 1 > $payloadSize ) {
113 // Send this payload and make a new one
114 $this->transport->emit( $payload );
115 $payload = '';
116 }
117 $payload .= $sample . "\n";
118 }
119 // Send what is left in the payload
120 if ( strlen( $payload ) > 0 ) {
121 $this->transport->emit( $payload );
122 }
123 }
124
128 public function send(): void {
129 $this->batch( $this->render(), $this->payloadSize );
130 }
131}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:82
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.
Functionality common to all metric types.