Skip to content

Commit

Permalink
add metricspoller(phystrix-dashboard)
Browse files Browse the repository at this point in the history
- add badges
- fix phystrix-dashboard errors
- add apcu libraries
- RequestCache support PSR-16
- default command key format changed. App\Phystrix\DummyCommand => App.Phystrix.DummyCommand
  • Loading branch information
yupmin committed Jun 2, 2019
1 parent 9a62894 commit 473b263
Show file tree
Hide file tree
Showing 13 changed files with 802 additions and 105 deletions.
23 changes: 16 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# Modern Phystrix

[![Build Status](https://travis-ci.org/yupmin/phystrix.svg)](https://travis-ci.org/yupmin/phystrix)
[![Latest Stable Version](https://poser.pugx.org/yupmin/modern-phystrix/v/stable)](https://packagist.org/packages/yupmin/modern-phystrix)
[![Total Downloads](https://poser.pugx.org/yupmin/modern-phystrix/downloads)](https://packagist.org/packages/yupmin/modern-phystrix)
[![License](https://poser.pugx.org/yupmin/modern-phystrix/license)](https://packagist.org/packages/yupmin/modern-phystrix)
[![Coding Standards](https://img.shields.io/badge/cs-PSR--2--R-yellow.svg)](https://github.com/php-fig-rectified/fig-rectified-standards)

## Requirement

* PHP 5.6 above
* Modern PHP

Expand All @@ -14,11 +19,15 @@ Phystrix protects the points of access to remote resources by keeping track of v

In case of a service failing way too often, to not make the situation worse, Phystrix will temporarily stop issuing requests to it. When the service comes back to life, Phystrix allows the client application to access it again.

And I fixed more for Modern PHP
* Use PHP 5.6 above
* Deleted 'Zend DI' and User 'PSR DI'
* DI is optional. (for using Your framework)
* PSR2 is default.
### Differences from [older version(upwork/phystrix)](https://github.com/upwork/phystrix)

* Use PHP 5.6 and PHP 7 above
* Change from 'Zend DI' to 'PSR DI', DI is optional. (for using Your framework)
* Add [phystrix dashboard](https://github.com/upwork/phystrix-dashboard) library, and fix more.
* Add Libraries of APCU
* PSR-2: Coding Style is default.
* PSR-3: Logger Interface(coming soon)
* PSR-16: Common Interface for Caching Libraries

### Understanding Phystrix

Expand All @@ -41,8 +50,8 @@ To store and share metrics between requests, Phystrix uses [APC](http://php.net/

### Php 7.2

In php 7 the API for `apcu` changed. You will need to install [apcu-bc](https://github.com/krakjoe/apcu-bc) in addition to `apcu` to use Phystrix.
The backwards compatibility layer extension must be loaded AFTER `apcu`.
In php 7 the API for `apcu` changed. You must use `ApcuStateStorage` and `ApcuMetricsPoller`. ~~You will need to install [apcu-bc](https://github.com/krakjoe/apcu-bc) in addition to `apcu` to use Phystrix.
The backwards compatibility layer extension must be loaded AFTER `apcu`.~~

## Usage

Expand Down
7 changes: 5 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
},
"require": {
"php": ">=5.6",
"ext-apcu": "*",
"ext-json": "*",
"psr/container": "^1.0",
"zendframework/zend-config": "^3.2"
"zendframework/zend-config": "^3.2",
"psr/simple-cache": "^1.0"
},
"require-dev": {
"php-di/php-di": "~5.4",
Expand All @@ -23,7 +26,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "2.0-dev"
"dev-master": "3.0-dev"
}
}
}
20 changes: 11 additions & 9 deletions library/Odesk/Phystrix/AbstractCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Odesk\Phystrix\Exception\FallbackNotAvailableException;
use Odesk\Phystrix\Exception\RuntimeException;
use Psr\Container\ContainerInterface;
use Psr\SimpleCache\CacheInterface;
use Zend\Config\Config;
use Exception;

Expand Down Expand Up @@ -69,7 +70,7 @@ abstract class AbstractCommand
protected $container;

/**
* @var RequestCache
* @var CacheInterface
*/
private $requestCache;

Expand Down Expand Up @@ -117,9 +118,9 @@ public function getCommandKey()
return $this->commandKey;
} else {
// If the command key hasn't been defined in the class we use the current class name
// but hystrix dashboard not work, because fixed below.
// refs : https://github.com/persevereVon/preq-laravel/blob/master/src/AbstractCommand.php#L100
// return str_replace('\\', '.', get_class($this));
return get_class($this);
return str_replace('\\', '.', get_class($this));
}
}

Expand All @@ -146,9 +147,9 @@ public function setCommandMetricsFactory(CommandMetricsFactory $commandMetricsFa
/**
* Sets shared object for request caching
*
* @param RequestCache $requestCache
* @param CacheInterface $requestCache
*/
public function setRequestCache(RequestCache $requestCache)
public function setRequestCache(CacheInterface $requestCache)
{
$this->requestCache = $requestCache;
}
Expand Down Expand Up @@ -201,7 +202,7 @@ public function setConfig(Config $config, $merge = true)
*/
private function isRequestCacheEnabled()
{
if (!$this->requestCache) {
if (!$this->requestCache instanceof CacheInterface) {
return false;
}

Expand All @@ -215,6 +216,7 @@ private function isRequestCacheEnabled()
* @return mixed
* @throws BadRequestException Re-throws it when the command throws it, without metrics tracking
* @throws Exception
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function execute()
{
Expand All @@ -227,11 +229,11 @@ public function execute()

// trying from cache first
if ($cacheEnabled) {
$cacheHit = $this->requestCache->exists($this->getCommandKey(), $this->getCacheKey());
$cacheHit = $this->requestCache->has($this->getCommandKey().'.'.$this->getCacheKey());
if ($cacheHit) {
$metrics->markResponseFromCache();
$this->recordExecutionEvent(self::EVENT_RESPONSE_FROM_CACHE);
return $this->requestCache->get($this->getCommandKey(), $this->getCacheKey());
return $this->requestCache->get($this->getCommandKey().'.'.$this->getCacheKey());
}
}
$circuitBreaker = $this->getCircuitBreaker();
Expand Down Expand Up @@ -261,7 +263,7 @@ public function execute()

// putting the result into cache
if ($cacheEnabled) {
$this->requestCache->put($this->getCommandKey(), $this->getCacheKey(), $result);
$this->requestCache->set($this->getCommandKey().'.'.$this->getCacheKey(), $result);
}

return $result;
Expand Down
157 changes: 157 additions & 0 deletions library/Odesk/Phystrix/ApcuStateStorage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php
/**
* This file is a part of the Phystrix library
*
* Copyright 2013-2014 oDesk Corporation. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Odesk\Phystrix;

/**
* APCU cache driven storage for Circuit Breaker metrics statistics
*/
class ApcuStateStorage implements StateStorageInterface
{
const BUCKET_EXPIRE_SECONDS = 120;

const CACHE_PREFIX = 'phystrix_cb_';

const OPENED_NAME = 'opened';

const SINGLE_TEST_BLOCKED = 'single_test_blocked';

/**
* Constructor
* @throws Exception\ApcNotLoadedException
*/
public function __construct()
{
if (!extension_loaded('apcu')) {
throw new Exception\ApcNotLoadedException('"apcu" PHP extension is required for Phystrix to work');
}
}

/**
* Prepends cache prefix and filters out invalid characters
*
* @param string $name
* @return string
*/
protected function prefix($name)
{
return self::CACHE_PREFIX . $name;
}

/**
* Returns counter value for the given bucket
*
* @param string $commandKey
* @param string $type
* @param integer $index
* @return integer
*/
public function getBucket($commandKey, $type, $index)
{
$bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index);
return apcu_fetch($bucketName);
}

/**
* Increments counter value for the given bucket
*
* @param string $commandKey
* @param string $type
* @param integer $index
*/
public function incrementBucket($commandKey, $type, $index)
{
$bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index);
if (!apcu_add($bucketName, 1, self::BUCKET_EXPIRE_SECONDS)) {
apcu_inc($bucketName);
}
}

/**
* If the given bucket is found, sets counter value to 0.
*
* @param string $commandKey Circuit breaker key
* @param string $type
* @param integer $index
*/
public function resetBucket($commandKey, $type, $index)
{
$bucketName = $this->prefix($commandKey . '_' . $type . '_' . $index);
if (apcu_exists($bucketName)) {
apcu_store($bucketName, 0, self::BUCKET_EXPIRE_SECONDS);
}
}

/**
* Marks the given circuit as open
*
* @param string $commandKey Circuit key
* @param integer $sleepingWindowInMilliseconds In how much time we should allow a single test
*/
public function openCircuit($commandKey, $sleepingWindowInMilliseconds)
{
$openedKey = $this->prefix($commandKey . self::OPENED_NAME);
$singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED);

apcu_store($openedKey, true);
// the single test blocked flag will expire automatically in $sleepingWindowInMilliseconds
// thus allowing us a single test. Notice, APC doesn't allow us to use
// expire time less than a second.
$sleepingWindowInSeconds = ceil($sleepingWindowInMilliseconds / 1000);
apcu_add($singleTestFlagKey, true, $sleepingWindowInSeconds);
}

/**
* Whether a single test is allowed
*
* @param string $commandKey Circuit breaker key
* @param integer $sleepingWindowInMilliseconds In how much time we should allow the next single test
* @return boolean
*/
public function allowSingleTest($commandKey, $sleepingWindowInMilliseconds)
{
$singleTestFlagKey = $this->prefix($commandKey . self::SINGLE_TEST_BLOCKED);
// using 'add' enforces thread safety.
$sleepingWindowInSeconds = ceil($sleepingWindowInMilliseconds / 1000);
// another APCU limitation is that within the current request variables will never expire.
return (boolean) apcu_add($singleTestFlagKey, true, $sleepingWindowInSeconds);
}

/**
* Whether a circuit is open
*
* @param string $commandKey Circuit breaker key
* @return boolean
*/
public function isCircuitOpen($commandKey)
{
$openedKey = $this->prefix($commandKey . self::OPENED_NAME);
return (boolean) apcu_fetch($openedKey);
}

/**
* Marks the given circuit as closed
*
* @param string $commandKey Circuit key
*/
public function closeCircuit($commandKey)
{
$openedKey = $this->prefix($commandKey . self::OPENED_NAME);
apcu_store($openedKey, false);
}
}
7 changes: 4 additions & 3 deletions library/Odesk/Phystrix/CommandFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
namespace Odesk\Phystrix;

use Psr\SimpleCache\CacheInterface;
use ReflectionClass;
use ReflectionException;
use Psr\Container\ContainerInterface;
Expand Down Expand Up @@ -50,7 +51,7 @@ class CommandFactory
protected $commandMetricsFactory;

/**
* @var RequestCache
* @var CacheInterface
*/
protected $requestCache;

Expand All @@ -65,15 +66,15 @@ class CommandFactory
* @param Config $config
* @param CircuitBreakerFactory $circuitBreakerFactory
* @param CommandMetricsFactory $commandMetricsFactory
* @param RequestCache|null $requestCache
* @param CacheInterface|null $requestCache
* @param RequestLog|null $requestLog
* @param ContainerInterface|null $container
*/
public function __construct(
Config $config,
CircuitBreakerFactory $circuitBreakerFactory,
CommandMetricsFactory $commandMetricsFactory,
RequestCache $requestCache = null,
CacheInterface $requestCache = null,
RequestLog $requestLog = null,
ContainerInterface $container = null
) {
Expand Down
Loading

0 comments on commit 473b263

Please sign in to comment.