Skip to content

Commit

Permalink
Merge pull request #3 from hellofresh/feature/cache-socket-connection
Browse files Browse the repository at this point in the history
Added opened socket reuse for statsd
  • Loading branch information
vgarvardt authored Feb 14, 2018
2 parents 4a99107 + 0988b54 commit 4344ab8
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Client/StatsD.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
use HelloFresh\Stats\HTTPMetricAlterCallback;
use HelloFresh\Stats\Incrementer;
use HelloFresh\Stats\State;
use HelloFresh\Stats\StatsD\CachingClient as StatsDClient;
use HelloFresh\Stats\Timer;
use League\StatsD\Client as StatsDClient;
use League\StatsD\Exception\ConfigurationException;

class StatsD extends AbstractClient implements Client
{
Expand All @@ -25,7 +26,8 @@ class StatsD extends AbstractClient implements Client
/**
* StatsD constructor.
*
* @param string $dsn statsd connection dsn
* @param string $dsn statsd connection dsn
* @throws ConfigurationException
*/
public function __construct($dsn)
{
Expand Down
66 changes: 66 additions & 0 deletions src/StatsD/CachingClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
namespace HelloFresh\Stats\StatsD;

use League\StatsD\Client;
use League\StatsD\Exception\ConnectionException;

class CachingClient extends Client
{
/** @var resource */
protected $socket;

/**
* @throws ConnectionException
* @return resource
*/
protected function getSocket()
{
if (!$this->socket) {
$this->socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr, $this->timeout);
if (!$this->socket) {
throw new ConnectionException($this, '(' . $errno . ') ' . $errstr);
}
}

return $this->socket;
}

/**
* Send Data to StatsD Server
* @param array $data A list of messages to send to the server
* @throws ConnectionException If there is a connection problem with the host
* @return $this
*/
protected function send(array $data)
{
try {
$socket = $this->getSocket();
$messages = [];
$prefix = $this->namespace ? $this->namespace . '.' : '';
foreach ($data as $key => $value) {
$messages[] = $prefix . $key . ':' . $value;
}
$this->message = implode("\n", $messages);
@fwrite($socket, $this->message);
fflush($socket);
} catch (ConnectionException $e) {
if ($this->throwConnectionExceptions) {
throw $e;
} else {
trigger_error(
sprintf('StatsD server connection failed (udp://%s:%d)', $this->host, $this->port),
E_USER_WARNING
);
}
}

return $this;
}

public function __destruct()
{
if ($this->socket) {
fclose($this->socket);
}
}
}

0 comments on commit 4344ab8

Please sign in to comment.