Skip to content

Commit

Permalink
Tags processor (#26)
Browse files Browse the repository at this point in the history
* test processors

* add tag processors to inject tags at runtime

* manuall check version of tag processors
  • Loading branch information
Harry Bragg committed Jun 26, 2018
1 parent c477f21 commit f001f5d
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 25 deletions.
22 changes: 0 additions & 22 deletions LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,3 @@ SOFTWARE.
-- Software originally forked from:

thephpleague/statsd - https://github.com/thephpleague/statsd

The MIT License (MIT)

Copyright (c) 2015 Harry Bragg <h.bragg@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ lint-fix: ## Run phpcsf and fix possible lint errors.
${DOCKER_RUN} vendor/bin/phpcbf -p src/ tests/

test-unit: ## Run the unit testsuite.
${DOCKER_RUN} vendor/bin/phpunit --colors=always --testsuite unit
${DOCKER_RUN} vendor/bin/phpunit --colors=always --testsuite unit --stop-on-failure

test-integration: ## Run the integration testsuite
${MAKE} test-echo
Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,17 @@ $statsd->set('api.unique_logins', $userID, ['tag']);
$statsd->timing('api.response_time', 245, ['end-point' => 'page', 'env' => 'test']);
```

##### Tags Processors

You can add tag processors to inject tags at runtime for each metric.

```php
$statsd->addTagProcessor(function (array $tags) {
$tags['new-key'] = 'new-value';
return $tags;
});
```

#### Events

```php
Expand Down
45 changes: 44 additions & 1 deletion src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ class Client
*/
protected $tags = [];

/**
* List of tags processors to apply to every metric being sent out
*
* @var callable[]
*/
protected $tagProcessors = [];

/**
* Singleton Reference
*
Expand Down Expand Up @@ -224,6 +231,7 @@ public function __toString()
* :onError <enum[error,exception,ignore]> - What we should do on error
* :dataDog <bool> - Use DataDog's version of statsd (Default: true)
* :tags <array> - List of tags to add to each message
* :tagProcessors <array> - List of tags processors to use
*
* @return Client This instance
* @throws ConfigurationException If port is invalid
Expand Down Expand Up @@ -252,6 +260,15 @@ public function configure(array $options = [])
$setOption('dataDog', 'boolean');
$setOption('tags', 'array');

if (isset($options['tagProcessors']) && is_array($options['tagProcessors'])) {
foreach ($options['tagProcessors'] as $tagProcessor) {
if (!is_callable($tagProcessor)) {
throw new ConfigurationException($this->instanceId, 'supplied tag processor is not a callable');
}
$this->addTagProcessor($tagProcessor);
}
}

$this->port = (int) $this->port;
if (!$this->port || !is_numeric($this->port) || $this->port > 65535) {
throw new ConfigurationException($this->instanceId, 'Option: Port is invalid or is out of range');
Expand All @@ -270,6 +287,17 @@ public function configure(array $options = [])
return $this;
}

/**
* @param callable $tagsProcessor
*
* @return Client
*/
public function addTagProcessor(callable $tagsProcessor)
{
$this->tagProcessors[] = $tagsProcessor;
return $this;
}

/**
* Get Host
*
Expand Down Expand Up @@ -593,7 +621,7 @@ protected function send(array $data, array $tags = [])
{
$messages = [];
$prefix = $this->namespace ? $this->namespace . '.' : '';
$formattedTags = $this->formatTags(array_merge($this->tags, $tags));
$formattedTags = $this->formatTags($this->processTags(array_merge($this->tags, $tags)));
foreach ($data as $key => $value) {
$messages[] = $prefix . $key . ':' . $value . $formattedTags;
}
Expand Down Expand Up @@ -622,4 +650,19 @@ protected function sendMessages(array $messages)

return $this;
}

/**
* Process a set of tags with some user defined processes to add custom runtime data
*
* @param array $tags
*
* @return array|mixed
*/
private function processTags(array $tags)
{
foreach ($this->tagProcessors as $tagProcessor) {
$tags = call_user_func($tagProcessor, $tags);
}
return $tags;
}
}
23 changes: 22 additions & 1 deletion tests/unit/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace Graze\DogStatsD\Test\Unit;

use Graze\DogStatsD\Exception\ConfigurationException;
use Graze\DogStatsD\Test\TestCase;

class ConfigurationTest extends TestCase
Expand Down Expand Up @@ -138,4 +137,26 @@ public function testOnErrorConfiguration()
$this->client->configure(['onError' => 'ignore']);
$this->assertAttributeEquals('ignore', 'onError', $this->client);
}

public function testTagsProcessorAcceptsCallable()
{
$processor = function (array $tags) {
return $tags;
};
$this->client->configure([
'tagProcessors' => [$processor],
]);
$this->assertAttributeEquals([$processor], 'tagProcessors', $this->client);
}

/**
* @expectedException \Graze\DogStatsD\Exception\ConfigurationException
* @expectedExceptionMessage supplied tag processor is not a callable
*/
public function testTagsProcessorDoesNotAcceptOtherThings()
{
$this->client->configure([
'tagProcessors' => ['a string']
]);
}
}
48 changes: 48 additions & 0 deletions tests/unit/TagProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
/**
* This file is part of graze/dog-statsd
*
* Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license https://github.com/graze/dog-statsd/blob/master/LICENSE.md
* @link https://github.com/graze/dog-statsd
*/

namespace Graze\DogStatsD\Test\Unit;

use Graze\DogStatsD\Test\TestCase;

class TagProcessorTest extends TestCase
{
public function testSingleProcessor()
{
$this->client->addTagProcessor(function (array $tags) {
$tags['custom'] = 1;
return $tags;
});
$this->client->increment('test_metric', 1, 1, ['tag']);
$this->assertEquals('test_metric:1|c|#tag,custom:1', $this->client->getLastMessage());
}

public function testMultipleProcessors()
{
$this->client->addTagProcessor(function (array $tags) {
$tags['custom'] = 1;
return $tags;
});
$this->client->addTagProcessor(function (array $tags) {
$this->assertArrayHasKey(
'custom',
$tags,
'ensure that the processors get processed in the order they are attached to the client'
);
$tags['second'] = 2;
return $tags;
});
$this->client->increment('test_metric', 1, 1, ['tag' => 'value']);
$this->assertEquals('test_metric:1|c|#tag:value,custom:1,second:2', $this->client->getLastMessage());
}
}

0 comments on commit f001f5d

Please sign in to comment.