Created
December 23, 2023 16:49
-
-
Save lezhnev74/3fd78b2c97c097ddf4d12c038abbbc5f to your computer and use it in GitHub Desktop.
Observability PHP client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace notes; | |
/** | |
* ObservabilityClient can throw upon instantiation, but sending does not block. | |
*/ | |
class ObservabilityClient | |
{ | |
private \Closure $sendMessage; | |
public function __construct(string $serverAddr, int $serverPort) | |
{ | |
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); | |
if ($socket === false) { | |
throw new \RuntimeException("unable to create a UDP socket"); | |
} | |
$this->sendMessage = fn(string $payload) => socket_sendto( | |
$socket, | |
$payload, | |
strlen($payload), | |
0, | |
$serverAddr, | |
$serverPort, | |
); | |
} | |
public function send(int $time, int $val, string $name, string ...$tags): void | |
{ | |
($this->sendMessage)($this->encodeMetric($time, $val, $name, ...$tags)); | |
} | |
protected function encodeMetric(int $time, int $val, string $name, string ...$tags): string | |
{ | |
$r = pack("VP", $time, $val); | |
$r .= $name; | |
foreach ($tags as $tag) { | |
if (!strlen($tag)) { | |
break; | |
} | |
$r .= "\x00" . $tag; | |
} | |
return $r; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment