20declare( strict_types=1 );
24use InvalidArgumentException;
42 private string $prefix;
54 private int $payloadSize;
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;
71 $this->payloadSize = $payloadSize;
82 $this->transport = $transport;
86 private function normalizePrefix(
string $prefix ): string {
87 if ( $prefix ===
'' ) {
88 throw new InvalidArgumentException(
'UDPEmitter: Prefix cannot be empty.' );
90 return StatsUtils::normalizeString( $prefix );
98 private function render(): array {
100 foreach ( $this->cache->getAllMetrics() as $metric ) {
102 if ( get_class( $metric ) === NullMetric::class ) {
105 foreach ( $this->formatter->getFormattedSamples( $this->prefix, $metric ) as $formatted ) {
106 $output[] = $formatted;
120 private function batch( array $samples,
int $payloadSize ): void {
122 foreach ( $samples as $sample ) {
123 if ( strlen( $payload ) + strlen( $sample ) + 1 < $payloadSize ) {
124 $payload .= $sample .
"\n";
127 $this->transport->emit( $payload );
132 if ( strlen( $payload ) > 0 ) {
133 $this->transport->emit( $payload );
141 $this->batch( $this->render(), $this->payloadSize );
if(!defined('MW_SETUP_CALLBACK'))
A generic class to send a message over UDP.