Skip to content

Instantly share code, notes, and snippets.

@lezhnev74
Created December 23, 2023 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lezhnev74/3fd78b2c97c097ddf4d12c038abbbc5f to your computer and use it in GitHub Desktop.
Save lezhnev74/3fd78b2c97c097ddf4d12c038abbbc5f to your computer and use it in GitHub Desktop.
Observability PHP client
<?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