Skip to content

Commit

Permalink
Merge pull request #17 from michaelmoussa/configurable-timeout
Browse files Browse the repository at this point in the history
Added a configurable timeout value for the StatsD Client
  • Loading branch information
philsturgeon committed Mar 19, 2015
2 parents 23425db + 63f99f4 commit b867ba7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ $statsd1 = StatsD\Client::instance('server1')->configure(array(...));
$statsd2 = StatsD\Client::instance('server2')->configure(array(...));
```

The StatsD client wait for `ini_get('default_socket_timeout')` seconds when opening the socket by default. To reduce
this timeout, add `'timeout' => <float>` to your config.

### Counters

```php
Expand Down
15 changes: 14 additions & 1 deletion src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ class Client
*/
protected $namespace = '';

/**
* Timeout for creating the socket connection
* @var null|float
*/
protected $timeout;


/**
* Singleton Reference
Expand All @@ -77,6 +83,10 @@ public static function instance($name = 'default')
public function __construct($instance_id = null)
{
$this->instance_id = $instance_id ?: uniqid();

if (empty($this->timeout)) {
$this->timeout = ini_get('default_socket_timeout');
}
}


Expand Down Expand Up @@ -111,6 +121,9 @@ public function configure(array $options = array())
if (isset($options['namespace'])) {
$this->namespace = $options['namespace'];
}
if (isset($options['timeout'])) {
$this->timeout = $options['timeout'];
}
return $this;
}

Expand Down Expand Up @@ -266,7 +279,7 @@ public function set($metric, $value)
protected function send(array $data)
{

$socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr);
$socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr, $this->timeout);
if (! $socket) {
throw new ConnectionException($this, '(' . $errno . ') ' . $errstr);
}
Expand Down
13 changes: 13 additions & 0 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,18 @@ public function testInvalidHost()
$this->client->increment('test');
}

public function testTimeoutSettingIsUsedWhenCreatingSocketIfProvided()
{
$this->client->configure(array(
'host' => 'localhost',
'timeout' => 123
));

$this->assertAttributeSame(123, 'timeout', $this->client);
}

public function testTimeoutDefaultsToPhpIniDefaultSocketTimeout()
{
$this->assertAttributeSame(ini_get('default_socket_timeout'), 'timeout', $this->client);
}
}

0 comments on commit b867ba7

Please sign in to comment.