20declare( strict_types=1 );
24use InvalidArgumentException;
41 private string $prefix;
45 private int $payloadSize;
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;
62 $this->payloadSize = $payloadSize;
73 $this->transport = $transport;
77 private function normalizePrefix(
string $prefix ): string {
78 if ( $prefix ===
'' ) {
79 throw new InvalidArgumentException(
'UDPEmitter: Prefix cannot be empty.' );
81 return StatsUtils::normalizeString( $prefix );
87 private function render(): array {
89 foreach ( $this->cache->getAllMetrics() as $metric ) {
91 if ( get_class( $metric ) === NullMetric::class ) {
94 foreach ( $this->formatter->getFormattedSamples( $this->prefix, $metric ) as $formatted ) {
95 $output[] = $formatted;
109 private function batch( array $samples,
int $payloadSize ): void {
111 foreach ( $samples as $sample ) {
112 if ( strlen( $payload ) + strlen( $sample ) + 1 > $payloadSize ) {
114 $this->transport->emit( $payload );
117 $payload .= $sample .
"\n";
120 if ( strlen( $payload ) > 0 ) {
121 $this->transport->emit( $payload );
129 $this->batch( $this->render(), $this->payloadSize );
if(!defined('MW_SETUP_CALLBACK'))
A generic class to send a message over UDP.