mirror of
https://github.com/the-djmaze/snappymail.git
synced 2026-08-29 20:19:22 +03:00
Moved cache drivers outside core to extensions (plugins)
This commit is contained in:
parent
d5690fc579
commit
4fc04648cf
267 changed files with 39 additions and 64 deletions
239
plugins/cache-redis/Predis/Connection/AbstractConnection.php
Normal file
239
plugins/cache-redis/Predis/Connection/AbstractConnection.php
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\CommunicationException;
|
||||
use Predis\Protocol\ProtocolException;
|
||||
|
||||
/**
|
||||
* Base class with the common logic used by connection classes to communicate
|
||||
* with Redis.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
abstract class AbstractConnection implements NodeConnectionInterface
|
||||
{
|
||||
private $resource;
|
||||
private $cachedId;
|
||||
|
||||
protected $parameters;
|
||||
protected $initCommands = array();
|
||||
|
||||
/**
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
*/
|
||||
public function __construct(ParametersInterface $parameters)
|
||||
{
|
||||
$this->parameters = $this->assertParameters($parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server and destroys the underlying resource when
|
||||
* PHP's garbage collector kicks in.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks some of the parameters used to initialize the connection.
|
||||
*
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return ParametersInterface
|
||||
*/
|
||||
protected function assertParameters(ParametersInterface $parameters)
|
||||
{
|
||||
switch ($parameters->scheme) {
|
||||
case 'tcp':
|
||||
case 'redis':
|
||||
case 'unix':
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new \InvalidArgumentException("Invalid scheme: '$parameters->scheme'.");
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the underlying resource used to communicate with Redis.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract protected function createResource();
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isConnected()
|
||||
{
|
||||
return isset($this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
if (!$this->isConnected()) {
|
||||
$this->resource = $this->createResource();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
unset($this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function addConnectCommand(CommandInterface $command)
|
||||
{
|
||||
$this->initCommands[] = $command;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command)
|
||||
{
|
||||
$this->writeRequest($command);
|
||||
|
||||
return $this->readResponse($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readResponse(CommandInterface $command)
|
||||
{
|
||||
return $this->read();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method that returns an exception message augmented with useful
|
||||
* details from the connection parameters.
|
||||
*
|
||||
* @param string $message Error message.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function createExceptionMessage($message)
|
||||
{
|
||||
$parameters = $this->parameters;
|
||||
|
||||
if ($parameters->scheme === 'unix') {
|
||||
return "$message [$parameters->scheme:$parameters->path]";
|
||||
}
|
||||
|
||||
if (filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
||||
return "$message [$parameters->scheme://[$parameters->host]:$parameters->port]";
|
||||
}
|
||||
|
||||
return "$message [$parameters->scheme://$parameters->host:$parameters->port]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to handle connection errors.
|
||||
*
|
||||
* @param string $message Error message.
|
||||
* @param int $code Error code.
|
||||
*/
|
||||
protected function onConnectionError($message, $code = null)
|
||||
{
|
||||
CommunicationException::handle(
|
||||
new ConnectionException($this, static::createExceptionMessage($message), $code)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to handle protocol errors.
|
||||
*
|
||||
* @param string $message Error message.
|
||||
*/
|
||||
protected function onProtocolError($message)
|
||||
{
|
||||
CommunicationException::handle(
|
||||
new ProtocolException($this, static::createExceptionMessage($message))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getResource()
|
||||
{
|
||||
if (isset($this->resource)) {
|
||||
return $this->resource;
|
||||
}
|
||||
|
||||
$this->connect();
|
||||
|
||||
return $this->resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getParameters()
|
||||
{
|
||||
return $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an identifier for the connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getIdentifier()
|
||||
{
|
||||
if ($this->parameters->scheme === 'unix') {
|
||||
return $this->parameters->path;
|
||||
}
|
||||
|
||||
return "{$this->parameters->host}:{$this->parameters->port}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
if (!isset($this->cachedId)) {
|
||||
$this->cachedId = $this->getIdentifier();
|
||||
}
|
||||
|
||||
return $this->cachedId;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array('parameters', 'initCommands');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection\Aggregate;
|
||||
|
||||
use Predis\Connection\AggregateConnectionInterface;
|
||||
|
||||
/**
|
||||
* Defines a cluster of Redis servers formed by aggregating multiple connection
|
||||
* instances to single Redis nodes.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface ClusterInterface extends AggregateConnectionInterface
|
||||
{
|
||||
}
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection\Aggregate;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\Connection\NodeConnectionInterface;
|
||||
use Predis\Replication\ReplicationStrategy;
|
||||
|
||||
/**
|
||||
* Aggregate connection handling replication of Redis nodes configured in a
|
||||
* single master / multiple slaves setup.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class MasterSlaveReplication implements ReplicationInterface
|
||||
{
|
||||
protected $strategy;
|
||||
protected $master;
|
||||
protected $slaves;
|
||||
protected $current;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(ReplicationStrategy $strategy = null)
|
||||
{
|
||||
$this->slaves = array();
|
||||
$this->strategy = $strategy ?: new ReplicationStrategy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if one master and at least one slave have been defined.
|
||||
*/
|
||||
protected function check()
|
||||
{
|
||||
if (!isset($this->master) || !$this->slaves) {
|
||||
throw new \RuntimeException('Replication needs one master and at least one slave.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the connection state.
|
||||
*/
|
||||
protected function reset()
|
||||
{
|
||||
$this->current = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function add(NodeConnectionInterface $connection)
|
||||
{
|
||||
$alias = $connection->getParameters()->alias;
|
||||
|
||||
if ($alias === 'master') {
|
||||
$this->master = $connection;
|
||||
} else {
|
||||
$this->slaves[$alias ?: count($this->slaves)] = $connection;
|
||||
}
|
||||
|
||||
$this->reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function remove(NodeConnectionInterface $connection)
|
||||
{
|
||||
if ($connection->getParameters()->alias === 'master') {
|
||||
$this->master = null;
|
||||
$this->reset();
|
||||
|
||||
return true;
|
||||
} else {
|
||||
if (($id = array_search($connection, $this->slaves, true)) !== false) {
|
||||
unset($this->slaves[$id]);
|
||||
$this->reset();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnection(CommandInterface $command)
|
||||
{
|
||||
if ($this->current === null) {
|
||||
$this->check();
|
||||
$this->current = $this->strategy->isReadOperation($command)
|
||||
? $this->pickSlave()
|
||||
: $this->master;
|
||||
|
||||
return $this->current;
|
||||
}
|
||||
|
||||
if ($this->current === $this->master) {
|
||||
return $this->current;
|
||||
}
|
||||
|
||||
if (!$this->strategy->isReadOperation($command)) {
|
||||
$this->current = $this->master;
|
||||
}
|
||||
|
||||
return $this->current;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnectionById($connectionId)
|
||||
{
|
||||
if ($connectionId === 'master') {
|
||||
return $this->master;
|
||||
}
|
||||
|
||||
if (isset($this->slaves[$connectionId])) {
|
||||
return $this->slaves[$connectionId];
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function switchTo($connection)
|
||||
{
|
||||
$this->check();
|
||||
|
||||
if (!$connection instanceof NodeConnectionInterface) {
|
||||
$connection = $this->getConnectionById($connection);
|
||||
}
|
||||
if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) {
|
||||
throw new \InvalidArgumentException('Invalid connection or connection not found.');
|
||||
}
|
||||
|
||||
$this->current = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getCurrent()
|
||||
{
|
||||
return $this->current;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getMaster()
|
||||
{
|
||||
return $this->master;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getSlaves()
|
||||
{
|
||||
return array_values($this->slaves);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying replication strategy.
|
||||
*
|
||||
* @return ReplicationStrategy
|
||||
*/
|
||||
public function getReplicationStrategy()
|
||||
{
|
||||
return $this->strategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random slave.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
protected function pickSlave()
|
||||
{
|
||||
return $this->slaves[array_rand($this->slaves)];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isConnected()
|
||||
{
|
||||
return $this->current ? $this->current->isConnected() : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
if ($this->current === null) {
|
||||
$this->check();
|
||||
$this->current = $this->pickSlave();
|
||||
}
|
||||
|
||||
$this->current->connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
if ($this->master) {
|
||||
$this->master->disconnect();
|
||||
}
|
||||
|
||||
foreach ($this->slaves as $connection) {
|
||||
$connection->disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$this->getConnection($command)->writeRequest($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readResponse(CommandInterface $command)
|
||||
{
|
||||
return $this->getConnection($command)->readResponse($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command)
|
||||
{
|
||||
return $this->getConnection($command)->executeCommand($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array('master', 'slaves', 'strategy');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,235 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection\Aggregate;
|
||||
|
||||
use Predis\Cluster\PredisStrategy;
|
||||
use Predis\Cluster\StrategyInterface;
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\Connection\NodeConnectionInterface;
|
||||
use Predis\NotSupportedException;
|
||||
|
||||
/**
|
||||
* Abstraction for a cluster of aggregate connections to various Redis servers
|
||||
* implementing client-side sharding based on pluggable distribution strategies.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* @todo Add the ability to remove connections from pool.
|
||||
*/
|
||||
class PredisCluster implements ClusterInterface, \IteratorAggregate, \Countable
|
||||
{
|
||||
private $pool;
|
||||
private $strategy;
|
||||
private $distributor;
|
||||
|
||||
/**
|
||||
* @param StrategyInterface $strategy Optional cluster strategy.
|
||||
*/
|
||||
public function __construct(StrategyInterface $strategy = null)
|
||||
{
|
||||
$this->pool = array();
|
||||
$this->strategy = $strategy ?: new PredisStrategy();
|
||||
$this->distributor = $this->strategy->getDistributor();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isConnected()
|
||||
{
|
||||
foreach ($this->pool as $connection) {
|
||||
if ($connection->isConnected()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
foreach ($this->pool as $connection) {
|
||||
$connection->connect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
foreach ($this->pool as $connection) {
|
||||
$connection->disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function add(NodeConnectionInterface $connection)
|
||||
{
|
||||
$parameters = $connection->getParameters();
|
||||
|
||||
if (isset($parameters->alias)) {
|
||||
$this->pool[$parameters->alias] = $connection;
|
||||
} else {
|
||||
$this->pool[] = $connection;
|
||||
}
|
||||
|
||||
$weight = isset($parameters->weight) ? $parameters->weight : null;
|
||||
$this->distributor->add($connection, $weight);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function remove(NodeConnectionInterface $connection)
|
||||
{
|
||||
if (($id = array_search($connection, $this->pool, true)) !== false) {
|
||||
unset($this->pool[$id]);
|
||||
$this->distributor->remove($connection);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a connection instance using its alias or index.
|
||||
*
|
||||
* @param string $connectionID Alias or index of a connection.
|
||||
*
|
||||
* @return bool Returns true if the connection was in the pool.
|
||||
*/
|
||||
public function removeById($connectionID)
|
||||
{
|
||||
if ($connection = $this->getConnectionById($connectionID)) {
|
||||
return $this->remove($connection);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnection(CommandInterface $command)
|
||||
{
|
||||
$slot = $this->strategy->getSlot($command);
|
||||
|
||||
if (!isset($slot)) {
|
||||
throw new NotSupportedException(
|
||||
"Cannot use '{$command->getId()}' over clusters of connections."
|
||||
);
|
||||
}
|
||||
|
||||
$node = $this->distributor->getBySlot($slot);
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnectionById($connectionID)
|
||||
{
|
||||
return isset($this->pool[$connectionID]) ? $this->pool[$connectionID] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a connection instance from the cluster using a key.
|
||||
*
|
||||
* @param string $key Key string.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getConnectionByKey($key)
|
||||
{
|
||||
$hash = $this->strategy->getSlotByKey($key);
|
||||
$node = $this->distributor->getBySlot($hash);
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying command hash strategy used to hash commands by
|
||||
* using keys found in their arguments.
|
||||
*
|
||||
* @return StrategyInterface
|
||||
*/
|
||||
public function getClusterStrategy()
|
||||
{
|
||||
return $this->strategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->pool);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getIterator()
|
||||
{
|
||||
return new \ArrayIterator($this->pool);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$this->getConnection($command)->writeRequest($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readResponse(CommandInterface $command)
|
||||
{
|
||||
return $this->getConnection($command)->readResponse($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command)
|
||||
{
|
||||
return $this->getConnection($command)->executeCommand($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the specified Redis command on all the nodes of a cluster.
|
||||
*
|
||||
* @param CommandInterface $command A Redis command.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function executeCommandOnNodes(CommandInterface $command)
|
||||
{
|
||||
$responses = array();
|
||||
|
||||
foreach ($this->pool as $connection) {
|
||||
$responses[] = $connection->executeCommand($command);
|
||||
}
|
||||
|
||||
return $responses;
|
||||
}
|
||||
}
|
||||
553
plugins/cache-redis/Predis/Connection/Aggregate/RedisCluster.php
Normal file
553
plugins/cache-redis/Predis/Connection/Aggregate/RedisCluster.php
Normal file
|
|
@ -0,0 +1,553 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection\Aggregate;
|
||||
|
||||
use Predis\Cluster\RedisStrategy as RedisClusterStrategy;
|
||||
use Predis\Cluster\StrategyInterface;
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\Command\RawCommand;
|
||||
use Predis\Connection\FactoryInterface;
|
||||
use Predis\Connection\NodeConnectionInterface;
|
||||
use Predis\NotSupportedException;
|
||||
use Predis\Response\ErrorInterface as ErrorResponseInterface;
|
||||
|
||||
/**
|
||||
* Abstraction for a Redis-backed cluster of nodes (Redis >= 3.0.0).
|
||||
*
|
||||
* This connection backend offers smart support for redis-cluster by handling
|
||||
* automatic slots map (re)generation upon -MOVED or -ASK responses returned by
|
||||
* Redis when redirecting a client to a different node.
|
||||
*
|
||||
* The cluster can be pre-initialized using only a subset of the actual nodes in
|
||||
* the cluster, Predis will do the rest by adjusting the slots map and creating
|
||||
* the missing underlying connection instances on the fly.
|
||||
*
|
||||
* It is possible to pre-associate connections to a slots range with the "slots"
|
||||
* parameter in the form "$first-$last". This can greatly reduce runtime node
|
||||
* guessing and redirections.
|
||||
*
|
||||
* It is also possible to ask for the full and updated slots map directly to one
|
||||
* of the nodes and optionally enable such a behaviour upon -MOVED redirections.
|
||||
* Asking for the cluster configuration to Redis is actually done by issuing a
|
||||
* CLUSTER SLOTS command to a random node in the pool.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class RedisCluster implements ClusterInterface, \IteratorAggregate, \Countable
|
||||
{
|
||||
private $useClusterSlots = true;
|
||||
private $defaultParameters = array();
|
||||
private $pool = array();
|
||||
private $slots = array();
|
||||
private $slotsMap;
|
||||
private $strategy;
|
||||
private $connections;
|
||||
|
||||
/**
|
||||
* @param FactoryInterface $connections Optional connection factory.
|
||||
* @param StrategyInterface $strategy Optional cluster strategy.
|
||||
*/
|
||||
public function __construct(
|
||||
FactoryInterface $connections,
|
||||
StrategyInterface $strategy = null
|
||||
) {
|
||||
$this->connections = $connections;
|
||||
$this->strategy = $strategy ?: new RedisClusterStrategy();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isConnected()
|
||||
{
|
||||
foreach ($this->pool as $connection) {
|
||||
if ($connection->isConnected()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
if ($connection = $this->getRandomConnection()) {
|
||||
$connection->connect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
foreach ($this->pool as $connection) {
|
||||
$connection->disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function add(NodeConnectionInterface $connection)
|
||||
{
|
||||
$this->pool[(string) $connection] = $connection;
|
||||
unset($this->slotsMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function remove(NodeConnectionInterface $connection)
|
||||
{
|
||||
if (false !== $id = array_search($connection, $this->pool, true)) {
|
||||
unset(
|
||||
$this->pool[$id],
|
||||
$this->slotsMap
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a connection instance by using its identifier.
|
||||
*
|
||||
* @param string $connectionID Connection identifier.
|
||||
*
|
||||
* @return bool True if the connection was in the pool.
|
||||
*/
|
||||
public function removeById($connectionID)
|
||||
{
|
||||
if (isset($this->pool[$connectionID])) {
|
||||
unset(
|
||||
$this->pool[$connectionID],
|
||||
$this->slotsMap
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the current slots map by guessing the cluster configuration out
|
||||
* of the connection parameters of the connections in the pool.
|
||||
*
|
||||
* Generation is based on the same algorithm used by Redis to generate the
|
||||
* cluster, so it is most effective when all of the connections supplied on
|
||||
* initialization have the "slots" parameter properly set accordingly to the
|
||||
* current cluster configuration.
|
||||
*/
|
||||
public function buildSlotsMap()
|
||||
{
|
||||
$this->slotsMap = array();
|
||||
|
||||
foreach ($this->pool as $connectionID => $connection) {
|
||||
$parameters = $connection->getParameters();
|
||||
|
||||
if (!isset($parameters->slots)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$slots = explode('-', $parameters->slots, 2);
|
||||
$this->setSlots($slots[0], $slots[1], $connectionID);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an updated slots map fetching the cluster configuration using
|
||||
* the CLUSTER SLOTS command against the specified node or a random one from
|
||||
* the pool.
|
||||
*
|
||||
* @param NodeConnectionInterface $connection Optional connection instance.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function askSlotsMap(NodeConnectionInterface $connection = null)
|
||||
{
|
||||
if (!$connection && !$connection = $this->getRandomConnection()) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$command = RawCommand::create('CLUSTER', 'SLOTS');
|
||||
$response = $connection->executeCommand($command);
|
||||
|
||||
foreach ($response as $slots) {
|
||||
// We only support master servers for now, so we ignore subsequent
|
||||
// elements in the $slots array identifying slaves.
|
||||
list($start, $end, $master) = $slots;
|
||||
|
||||
if ($master[0] === '') {
|
||||
$this->setSlots($start, $end, (string) $connection);
|
||||
} else {
|
||||
$this->setSlots($start, $end, "{$master[0]}:{$master[1]}");
|
||||
}
|
||||
}
|
||||
|
||||
return $this->slotsMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current slots map for the cluster.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getSlotsMap()
|
||||
{
|
||||
if (!isset($this->slotsMap)) {
|
||||
$this->slotsMap = array();
|
||||
}
|
||||
|
||||
return $this->slotsMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-associates a connection to a slots range to avoid runtime guessing.
|
||||
*
|
||||
* @param int $first Initial slot of the range.
|
||||
* @param int $last Last slot of the range.
|
||||
* @param NodeConnectionInterface|string $connection ID or connection instance.
|
||||
*
|
||||
* @throws \OutOfBoundsException
|
||||
*/
|
||||
public function setSlots($first, $last, $connection)
|
||||
{
|
||||
if ($first < 0x0000 || $first > 0x3FFF ||
|
||||
$last < 0x0000 || $last > 0x3FFF ||
|
||||
$last < $first
|
||||
) {
|
||||
throw new \OutOfBoundsException(
|
||||
"Invalid slot range for $connection: [$first-$last]."
|
||||
);
|
||||
}
|
||||
|
||||
$slots = array_fill($first, $last - $first + 1, (string) $connection);
|
||||
$this->slotsMap = $this->getSlotsMap() + $slots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guesses the correct node associated to a given slot using a precalculated
|
||||
* slots map, falling back to the same logic used by Redis to initialize a
|
||||
* cluster (best-effort).
|
||||
*
|
||||
* @param int $slot Slot index.
|
||||
*
|
||||
* @return string Connection ID.
|
||||
*/
|
||||
protected function guessNode($slot)
|
||||
{
|
||||
if (!isset($this->slotsMap)) {
|
||||
$this->buildSlotsMap();
|
||||
}
|
||||
|
||||
if (isset($this->slotsMap[$slot])) {
|
||||
return $this->slotsMap[$slot];
|
||||
}
|
||||
|
||||
$count = count($this->pool);
|
||||
$index = min((int) ($slot / (int) (16384 / $count)), $count - 1);
|
||||
$nodes = array_keys($this->pool);
|
||||
|
||||
return $nodes[$index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new connection instance from the given connection ID.
|
||||
*
|
||||
* @param string $connectionID Identifier for the connection.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
protected function createConnection($connectionID)
|
||||
{
|
||||
$separator = strrpos($connectionID, ':');
|
||||
|
||||
$parameters = array_merge($this->defaultParameters, array(
|
||||
'host' => substr($connectionID, 0, $separator),
|
||||
'port' => substr($connectionID, $separator + 1),
|
||||
));
|
||||
|
||||
$connection = $this->connections->create($parameters);
|
||||
|
||||
return $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnection(CommandInterface $command)
|
||||
{
|
||||
$slot = $this->strategy->getSlot($command);
|
||||
|
||||
if (!isset($slot)) {
|
||||
throw new NotSupportedException(
|
||||
"Cannot use '{$command->getId()}' with redis-cluster."
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($this->slots[$slot])) {
|
||||
return $this->slots[$slot];
|
||||
} else {
|
||||
return $this->getConnectionBySlot($slot);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the connection currently associated to a given slot.
|
||||
*
|
||||
* @param int $slot Slot index.
|
||||
*
|
||||
* @throws \OutOfBoundsException
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getConnectionBySlot($slot)
|
||||
{
|
||||
if ($slot < 0x0000 || $slot > 0x3FFF) {
|
||||
throw new \OutOfBoundsException("Invalid slot [$slot].");
|
||||
}
|
||||
|
||||
if (isset($this->slots[$slot])) {
|
||||
return $this->slots[$slot];
|
||||
}
|
||||
|
||||
$connectionID = $this->guessNode($slot);
|
||||
|
||||
if (!$connection = $this->getConnectionById($connectionID)) {
|
||||
$connection = $this->createConnection($connectionID);
|
||||
$this->pool[$connectionID] = $connection;
|
||||
}
|
||||
|
||||
return $this->slots[$slot] = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getConnectionById($connectionID)
|
||||
{
|
||||
if (isset($this->pool[$connectionID])) {
|
||||
return $this->pool[$connectionID];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random connection from the pool.
|
||||
*
|
||||
* @return NodeConnectionInterface|null
|
||||
*/
|
||||
protected function getRandomConnection()
|
||||
{
|
||||
if ($this->pool) {
|
||||
return $this->pool[array_rand($this->pool)];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently associates the connection instance to a new slot.
|
||||
* The connection is added to the connections pool if not yet included.
|
||||
*
|
||||
* @param NodeConnectionInterface $connection Connection instance.
|
||||
* @param int $slot Target slot index.
|
||||
*/
|
||||
protected function move(NodeConnectionInterface $connection, $slot)
|
||||
{
|
||||
$this->pool[(string) $connection] = $connection;
|
||||
$this->slots[(int) $slot] = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles -ERR responses returned by Redis.
|
||||
*
|
||||
* @param CommandInterface $command Command that generated the -ERR response.
|
||||
* @param ErrorResponseInterface $error Redis error response object.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error)
|
||||
{
|
||||
$details = explode(' ', $error->getMessage(), 2);
|
||||
|
||||
switch ($details[0]) {
|
||||
case 'MOVED':
|
||||
return $this->onMovedResponse($command, $details[1]);
|
||||
|
||||
case 'ASK':
|
||||
return $this->onAskResponse($command, $details[1]);
|
||||
|
||||
default:
|
||||
return $error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles -MOVED responses by executing again the command against the node
|
||||
* indicated by the Redis response.
|
||||
*
|
||||
* @param CommandInterface $command Command that generated the -MOVED response.
|
||||
* @param string $details Parameters of the -MOVED response.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function onMovedResponse(CommandInterface $command, $details)
|
||||
{
|
||||
list($slot, $connectionID) = explode(' ', $details, 2);
|
||||
|
||||
if (!$connection = $this->getConnectionById($connectionID)) {
|
||||
$connection = $this->createConnection($connectionID);
|
||||
}
|
||||
|
||||
if ($this->useClusterSlots) {
|
||||
$this->askSlotsMap($connection);
|
||||
}
|
||||
|
||||
$this->move($connection, $slot);
|
||||
$response = $this->executeCommand($command);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles -ASK responses by executing again the command against the node
|
||||
* indicated by the Redis response.
|
||||
*
|
||||
* @param CommandInterface $command Command that generated the -ASK response.
|
||||
* @param string $details Parameters of the -ASK response.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function onAskResponse(CommandInterface $command, $details)
|
||||
{
|
||||
list($slot, $connectionID) = explode(' ', $details, 2);
|
||||
|
||||
if (!$connection = $this->getConnectionById($connectionID)) {
|
||||
$connection = $this->createConnection($connectionID);
|
||||
}
|
||||
|
||||
$connection->executeCommand(RawCommand::create('ASKING'));
|
||||
$response = $connection->executeCommand($command);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$this->getConnection($command)->writeRequest($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readResponse(CommandInterface $command)
|
||||
{
|
||||
return $this->getConnection($command)->readResponse($command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command)
|
||||
{
|
||||
$connection = $this->getConnection($command);
|
||||
$response = $connection->executeCommand($command);
|
||||
|
||||
if ($response instanceof ErrorResponseInterface) {
|
||||
return $this->onErrorResponse($command, $response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->pool);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getIterator()
|
||||
{
|
||||
return new \ArrayIterator(array_values($this->pool));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying command hash strategy used to hash commands by
|
||||
* using keys found in their arguments.
|
||||
*
|
||||
* @return StrategyInterface
|
||||
*/
|
||||
public function getClusterStrategy()
|
||||
{
|
||||
return $this->strategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying connection factory used to create new connection
|
||||
* instances to Redis nodes indicated by redis-cluster.
|
||||
*
|
||||
* @return FactoryInterface
|
||||
*/
|
||||
public function getConnectionFactory()
|
||||
{
|
||||
return $this->connections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables automatic fetching of the current slots map from one of the nodes
|
||||
* using the CLUSTER SLOTS command. This option is disabled by default but
|
||||
* asking the current slots map to Redis upon -MOVED responses may reduce
|
||||
* overhead by eliminating the trial-and-error nature of the node guessing
|
||||
* procedure, mostly when targeting many keys that would end up in a lot of
|
||||
* redirections.
|
||||
*
|
||||
* The slots map can still be manually fetched using the askSlotsMap()
|
||||
* method whether or not this option is enabled.
|
||||
*
|
||||
* @param bool $value Enable or disable the use of CLUSTER SLOTS.
|
||||
*/
|
||||
public function useClusterSlots($value)
|
||||
{
|
||||
$this->useClusterSlots = (bool) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a default array of connection parameters to be applied when creating
|
||||
* new connection instances on the fly when they are not part of the initial
|
||||
* pool supplied upon cluster initialization.
|
||||
*
|
||||
* These parameters are not applied to connections added to the pool using
|
||||
* the add() method.
|
||||
*
|
||||
* @param array $parameters Array of connection parameters.
|
||||
*/
|
||||
public function setDefaultParameters(array $parameters)
|
||||
{
|
||||
$this->defaultParameters = array_merge(
|
||||
$this->defaultParameters,
|
||||
$parameters ?: array()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection\Aggregate;
|
||||
|
||||
use Predis\Connection\AggregateConnectionInterface;
|
||||
use Predis\Connection\NodeConnectionInterface;
|
||||
|
||||
/**
|
||||
* Defines a group of Redis nodes in a master / slave replication setup.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface ReplicationInterface extends AggregateConnectionInterface
|
||||
{
|
||||
/**
|
||||
* Switches the internal connection instance in use.
|
||||
*
|
||||
* @param string $connection Alias of a connection
|
||||
*/
|
||||
public function switchTo($connection);
|
||||
|
||||
/**
|
||||
* Returns the connection instance currently in use by the aggregate
|
||||
* connection.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getCurrent();
|
||||
|
||||
/**
|
||||
* Returns the connection instance for the master Redis node.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getMaster();
|
||||
|
||||
/**
|
||||
* Returns a list of connection instances to slave nodes.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getSlaves();
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
|
||||
/**
|
||||
* Defines a virtual connection composed of multiple connection instances to
|
||||
* single Redis nodes.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface AggregateConnectionInterface extends ConnectionInterface
|
||||
{
|
||||
/**
|
||||
* Adds a connection instance to the aggregate connection.
|
||||
*
|
||||
* @param NodeConnectionInterface $connection Connection instance.
|
||||
*/
|
||||
public function add(NodeConnectionInterface $connection);
|
||||
|
||||
/**
|
||||
* Removes the specified connection instance from the aggregate connection.
|
||||
*
|
||||
* @param NodeConnectionInterface $connection Connection instance.
|
||||
*
|
||||
* @return bool Returns true if the connection was in the pool.
|
||||
*/
|
||||
public function remove(NodeConnectionInterface $connection);
|
||||
|
||||
/**
|
||||
* Returns the connection instance in charge for the given command.
|
||||
*
|
||||
* @param CommandInterface $command Command instance.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function getConnection(CommandInterface $command);
|
||||
|
||||
/**
|
||||
* Returns a connection instance from the aggregate connection by its alias.
|
||||
*
|
||||
* @param string $connectionID Connection alias.
|
||||
*
|
||||
* @return NodeConnectionInterface|null
|
||||
*/
|
||||
public function getConnectionById($connectionID);
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
/**
|
||||
* Defines a connection to communicate with a single Redis server that leverages
|
||||
* an external protocol processor to handle pluggable protocol handlers.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface CompositeConnectionInterface extends NodeConnectionInterface
|
||||
{
|
||||
/**
|
||||
* Returns the protocol processor used by the connection.
|
||||
*/
|
||||
public function getProtocol();
|
||||
|
||||
/**
|
||||
* Writes the buffer containing over the connection.
|
||||
*
|
||||
* @param string $buffer String buffer to be sent over the connection.
|
||||
*/
|
||||
public function writeBuffer($buffer);
|
||||
|
||||
/**
|
||||
* Reads the given number of bytes from the connection.
|
||||
*
|
||||
* @param int $length Number of bytes to read from the connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function readBuffer($length);
|
||||
|
||||
/**
|
||||
* Reads a line from the connection.
|
||||
*
|
||||
* @param string
|
||||
*/
|
||||
public function readLine();
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\Protocol\ProtocolProcessorInterface;
|
||||
use Predis\Protocol\Text\ProtocolProcessor as TextProtocolProcessor;
|
||||
|
||||
/**
|
||||
* Connection abstraction to Redis servers based on PHP's stream that uses an
|
||||
* external protocol processor defining the protocol used for the communication.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class CompositeStreamConnection extends StreamConnection implements CompositeConnectionInterface
|
||||
{
|
||||
protected $protocol;
|
||||
|
||||
/**
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
* @param ProtocolProcessorInterface $protocol Protocol processor.
|
||||
*/
|
||||
public function __construct(
|
||||
ParametersInterface $parameters,
|
||||
ProtocolProcessorInterface $protocol = null
|
||||
) {
|
||||
$this->parameters = $this->assertParameters($parameters);
|
||||
$this->protocol = $protocol ?: new TextProtocolProcessor();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getProtocol()
|
||||
{
|
||||
return $this->protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeBuffer($buffer)
|
||||
{
|
||||
$this->write($buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readBuffer($length)
|
||||
{
|
||||
if ($length <= 0) {
|
||||
throw new \InvalidArgumentException('Length parameter must be greater than 0.');
|
||||
}
|
||||
|
||||
$value = '';
|
||||
$socket = $this->getResource();
|
||||
|
||||
do {
|
||||
$chunk = fread($socket, $length);
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
$this->onConnectionError('Error while reading bytes from the server.');
|
||||
}
|
||||
|
||||
$value .= $chunk;
|
||||
} while (($length -= strlen($chunk)) > 0);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readLine()
|
||||
{
|
||||
$value = '';
|
||||
$socket = $this->getResource();
|
||||
|
||||
do {
|
||||
$chunk = fgets($socket);
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
$this->onConnectionError('Error while reading line from the server.');
|
||||
}
|
||||
|
||||
$value .= $chunk;
|
||||
} while (substr($value, -2) !== "\r\n");
|
||||
|
||||
return substr($value, 0, -2);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$this->protocol->write($this, $command);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
return $this->protocol->read($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array_merge(parent::__sleep(), array('protocol'));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\CommunicationException;
|
||||
|
||||
/**
|
||||
* Exception class that identifies connection-related errors.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class ConnectionException extends CommunicationException
|
||||
{
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
|
||||
/**
|
||||
* Defines a connection object used to communicate with one or multiple
|
||||
* Redis servers.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface ConnectionInterface
|
||||
{
|
||||
/**
|
||||
* Opens the connection to Redis.
|
||||
*/
|
||||
public function connect();
|
||||
|
||||
/**
|
||||
* Closes the connection to Redis.
|
||||
*/
|
||||
public function disconnect();
|
||||
|
||||
/**
|
||||
* Checks if the connection to Redis is considered open.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isConnected();
|
||||
|
||||
/**
|
||||
* Writes the request for the given command over the connection.
|
||||
*
|
||||
* @param CommandInterface $command Command instance.
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command);
|
||||
|
||||
/**
|
||||
* Reads the response to the given command from the connection.
|
||||
*
|
||||
* @param CommandInterface $command Command instance.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function readResponse(CommandInterface $command);
|
||||
|
||||
/**
|
||||
* Writes a request for the given command over the connection and reads back
|
||||
* the response returned by Redis.
|
||||
*
|
||||
* @param CommandInterface $command Command instance.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command);
|
||||
}
|
||||
151
plugins/cache-redis/Predis/Connection/Factory.php
Normal file
151
plugins/cache-redis/Predis/Connection/Factory.php
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\RawCommand;
|
||||
|
||||
/**
|
||||
* Standard connection factory for creating connections to Redis nodes.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class Factory implements FactoryInterface
|
||||
{
|
||||
protected $schemes = array(
|
||||
'tcp' => 'Predis\Connection\StreamConnection',
|
||||
'unix' => 'Predis\Connection\StreamConnection',
|
||||
'redis' => 'Predis\Connection\StreamConnection',
|
||||
'http' => 'Predis\Connection\WebdisConnection',
|
||||
);
|
||||
|
||||
/**
|
||||
* Checks if the provided argument represents a valid connection class
|
||||
* implementing Predis\Connection\NodeConnectionInterface. Optionally,
|
||||
* callable objects are used for lazy initialization of connection objects.
|
||||
*
|
||||
* @param mixed $initializer FQN of a connection class or a callable for lazy initialization.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function checkInitializer($initializer)
|
||||
{
|
||||
if (is_callable($initializer)) {
|
||||
return $initializer;
|
||||
}
|
||||
|
||||
$class = new \ReflectionClass($initializer);
|
||||
|
||||
if (!$class->isSubclassOf('Predis\Connection\NodeConnectionInterface')) {
|
||||
throw new \InvalidArgumentException(
|
||||
'A connection initializer must be a valid connection class or a callable object.'
|
||||
);
|
||||
}
|
||||
|
||||
return $initializer;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function define($scheme, $initializer)
|
||||
{
|
||||
$this->schemes[$scheme] = $this->checkInitializer($initializer);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function undefine($scheme)
|
||||
{
|
||||
unset($this->schemes[$scheme]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function create($parameters)
|
||||
{
|
||||
if (!$parameters instanceof ParametersInterface) {
|
||||
$parameters = $this->createParameters($parameters);
|
||||
}
|
||||
|
||||
$scheme = $parameters->scheme;
|
||||
|
||||
if (!isset($this->schemes[$scheme])) {
|
||||
throw new \InvalidArgumentException("Unknown connection scheme: '$scheme'.");
|
||||
}
|
||||
|
||||
$initializer = $this->schemes[$scheme];
|
||||
|
||||
if (is_callable($initializer)) {
|
||||
$connection = call_user_func($initializer, $parameters, $this);
|
||||
} else {
|
||||
$connection = new $initializer($parameters);
|
||||
$this->prepareConnection($connection);
|
||||
}
|
||||
|
||||
if (!$connection instanceof NodeConnectionInterface) {
|
||||
throw new \UnexpectedValueException(
|
||||
'Objects returned by connection initializers must implement '.
|
||||
"'Predis\Connection\NodeConnectionInterface'."
|
||||
);
|
||||
}
|
||||
|
||||
return $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function aggregate(AggregateConnectionInterface $connection, array $parameters)
|
||||
{
|
||||
foreach ($parameters as $node) {
|
||||
$connection->add($node instanceof NodeConnectionInterface ? $node : $this->create($node));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a connection parameters instance from the supplied argument.
|
||||
*
|
||||
* @param mixed $parameters Original connection parameters.
|
||||
*
|
||||
* @return ParametersInterface
|
||||
*/
|
||||
protected function createParameters($parameters)
|
||||
{
|
||||
return Parameters::create($parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a connection instance after its initialization.
|
||||
*
|
||||
* @param NodeConnectionInterface $connection Connection instance.
|
||||
*/
|
||||
protected function prepareConnection(NodeConnectionInterface $connection)
|
||||
{
|
||||
$parameters = $connection->getParameters();
|
||||
|
||||
if (isset($parameters->password)) {
|
||||
$connection->addConnectCommand(
|
||||
new RawCommand(array('AUTH', $parameters->password))
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($parameters->database)) {
|
||||
$connection->addConnectCommand(
|
||||
new RawCommand(array('SELECT', $parameters->database))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
52
plugins/cache-redis/Predis/Connection/FactoryInterface.php
Normal file
52
plugins/cache-redis/Predis/Connection/FactoryInterface.php
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
/**
|
||||
* Interface for classes providing a factory of connections to Redis nodes.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface FactoryInterface
|
||||
{
|
||||
/**
|
||||
* Defines or overrides the connection class identified by a scheme prefix.
|
||||
*
|
||||
* @param string $scheme Target connection scheme.
|
||||
* @param mixed $initializer Fully-qualified name of a class or a callable for lazy initialization.
|
||||
*/
|
||||
public function define($scheme, $initializer);
|
||||
|
||||
/**
|
||||
* Undefines the connection identified by a scheme prefix.
|
||||
*
|
||||
* @param string $scheme Target connection scheme.
|
||||
*/
|
||||
public function undefine($scheme);
|
||||
|
||||
/**
|
||||
* Creates a new connection object.
|
||||
*
|
||||
* @param mixed $parameters Initialization parameters for the connection.
|
||||
*
|
||||
* @return NodeConnectionInterface
|
||||
*/
|
||||
public function create($parameters);
|
||||
|
||||
/**
|
||||
* Aggregates single connections into an aggregate connection instance.
|
||||
*
|
||||
* @param AggregateConnectionInterface $aggregate Aggregate connection instance.
|
||||
* @param array $parameters List of parameters for each connection.
|
||||
*/
|
||||
public function aggregate(AggregateConnectionInterface $aggregate, array $parameters);
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
|
||||
/**
|
||||
* Defines a connection used to communicate with a single Redis node.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface NodeConnectionInterface extends ConnectionInterface
|
||||
{
|
||||
/**
|
||||
* Returns a string representation of the connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString();
|
||||
|
||||
/**
|
||||
* Returns the underlying resource used to communicate with Redis.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getResource();
|
||||
|
||||
/**
|
||||
* Returns the parameters used to initialize the connection.
|
||||
*
|
||||
* @return ParametersInterface
|
||||
*/
|
||||
public function getParameters();
|
||||
|
||||
/**
|
||||
* Pushes the given command into a queue of commands executed when
|
||||
* establishing the actual connection to Redis.
|
||||
*
|
||||
* @param CommandInterface $command Instance of a Redis command.
|
||||
*/
|
||||
public function addConnectCommand(CommandInterface $command);
|
||||
|
||||
/**
|
||||
* Reads a response from the server.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function read();
|
||||
}
|
||||
176
plugins/cache-redis/Predis/Connection/Parameters.php
Normal file
176
plugins/cache-redis/Predis/Connection/Parameters.php
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
/**
|
||||
* Container for connection parameters used to initialize connections to Redis.
|
||||
*
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class Parameters implements ParametersInterface
|
||||
{
|
||||
private $parameters;
|
||||
|
||||
private static $defaults = array(
|
||||
'scheme' => 'tcp',
|
||||
'host' => '127.0.0.1',
|
||||
'port' => 6379,
|
||||
'timeout' => 5.0,
|
||||
);
|
||||
|
||||
/**
|
||||
* @param array $parameters Named array of connection parameters.
|
||||
*/
|
||||
public function __construct(array $parameters = array())
|
||||
{
|
||||
$this->parameters = $this->filter($parameters) + $this->getDefaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns some default parameters with their values.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getDefaults()
|
||||
{
|
||||
return self::$defaults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance by supplying the initial parameters either in the
|
||||
* form of an URI string or a named array.
|
||||
*
|
||||
* @param array|string $parameters Set of connection parameters.
|
||||
*
|
||||
* @return Parameters
|
||||
*/
|
||||
public static function create($parameters)
|
||||
{
|
||||
if (is_string($parameters)) {
|
||||
$parameters = static::parse($parameters);
|
||||
}
|
||||
|
||||
return new static($parameters ?: array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an URI string returning an array of connection parameters.
|
||||
*
|
||||
* When using the "redis" and "rediss" schemes the URI is parsed according
|
||||
* to the rules defined by the provisional registration documents approved
|
||||
* by IANA. If the URI has a password in its "user-information" part or a
|
||||
* database number in the "path" part these values override the values of
|
||||
* "password" and "database" if they are present in the "query" part.
|
||||
*
|
||||
* @link http://www.iana.org/assignments/uri-schemes/prov/redis
|
||||
* @link http://www.iana.org/assignments/uri-schemes/prov/redis
|
||||
*
|
||||
* @param string $uri URI string.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function parse($uri)
|
||||
{
|
||||
if (stripos($uri, 'unix') === 0) {
|
||||
// Hack to support URIs for UNIX sockets with minimal effort.
|
||||
$uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
|
||||
}
|
||||
|
||||
if (!$parsed = parse_url($uri)) {
|
||||
throw new \InvalidArgumentException("Invalid parameters URI: $uri");
|
||||
}
|
||||
|
||||
if (
|
||||
isset($parsed['host'])
|
||||
&& false !== strpos($parsed['host'], '[')
|
||||
&& false !== strpos($parsed['host'], ']')
|
||||
) {
|
||||
$parsed['host'] = substr($parsed['host'], 1, -1);
|
||||
}
|
||||
|
||||
if (isset($parsed['query'])) {
|
||||
parse_str($parsed['query'], $queryarray);
|
||||
unset($parsed['query']);
|
||||
|
||||
$parsed = array_merge($parsed, $queryarray);
|
||||
}
|
||||
|
||||
if (stripos($uri, 'redis') === 0) {
|
||||
if (isset($parsed['pass'])) {
|
||||
$parsed['password'] = $parsed['pass'];
|
||||
unset($parsed['pass']);
|
||||
}
|
||||
|
||||
if (isset($parsed['path']) && preg_match('/^\/(\d+)(\/.*)?/', $parsed['path'], $path)) {
|
||||
$parsed['database'] = $path[1];
|
||||
|
||||
if (isset($path[2])) {
|
||||
$parsed['path'] = $path[2];
|
||||
} else {
|
||||
unset($parsed['path']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and converts each value of the connection parameters array.
|
||||
*
|
||||
* @param array $parameters Connection parameters.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function filter(array $parameters)
|
||||
{
|
||||
return $parameters ?: array();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __get($parameter)
|
||||
{
|
||||
if (isset($this->parameters[$parameter])) {
|
||||
return $this->parameters[$parameter];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __isset($parameter)
|
||||
{
|
||||
return isset($this->parameters[$parameter]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function toArray()
|
||||
{
|
||||
return $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array('parameters');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
/**
|
||||
* Interface defining a container for connection parameters.
|
||||
*
|
||||
* The actual list of connection parameters depends on the features supported by
|
||||
* each connection backend class (please refer to their specific documentation),
|
||||
* but the most common parameters used through the library are:
|
||||
*
|
||||
* @property-read string scheme Connection scheme, such as 'tcp' or 'unix'.
|
||||
* @property-read string host IP address or hostname of Redis.
|
||||
* @property-read int port TCP port on which Redis is listening to.
|
||||
* @property-read string path Path of a UNIX domain socket file.
|
||||
* @property-read string alias Alias for the connection.
|
||||
* @property-read float timeout Timeout for the connect() operation.
|
||||
* @property-read float read_write_timeout Timeout for read() and write() operations.
|
||||
* @property-read bool async_connect Performs the connect() operation asynchronously.
|
||||
* @property-read bool tcp_nodelay Toggles the Nagle's algorithm for coalescing.
|
||||
* @property-read bool persistent Leaves the connection open after a GC collection.
|
||||
* @property-read string password Password to access Redis (see the AUTH command).
|
||||
* @property-read string database Database index (see the SELECT command).
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
interface ParametersInterface
|
||||
{
|
||||
/**
|
||||
* Checks if the specified parameters is set.
|
||||
*
|
||||
* @param string $parameter Name of the parameter.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function __isset($parameter);
|
||||
|
||||
/**
|
||||
* Returns the value of the specified parameter.
|
||||
*
|
||||
* @param string $parameter Name of the parameter.
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function __get($parameter);
|
||||
|
||||
/**
|
||||
* Returns an array representation of the connection parameters.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray();
|
||||
}
|
||||
|
|
@ -0,0 +1,393 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\NotSupportedException;
|
||||
use Predis\Response\Error as ErrorResponse;
|
||||
use Predis\Response\Status as StatusResponse;
|
||||
|
||||
/**
|
||||
* This class provides the implementation of a Predis connection that uses the
|
||||
* PHP socket extension for network communication and wraps the phpiredis C
|
||||
* extension (PHP bindings for hiredis) to parse the Redis protocol.
|
||||
*
|
||||
* This class is intended to provide an optional low-overhead alternative for
|
||||
* processing responses from Redis compared to the standard pure-PHP classes.
|
||||
* Differences in speed when dealing with short inline responses are practically
|
||||
* nonexistent, the actual speed boost is for big multibulk responses when this
|
||||
* protocol processor can parse and return responses very fast.
|
||||
*
|
||||
* For instructions on how to build and install the phpiredis extension, please
|
||||
* consult the repository of the project.
|
||||
*
|
||||
* The connection parameters supported by this class are:
|
||||
*
|
||||
* - scheme: it can be either 'redis', 'tcp' or 'unix'.
|
||||
* - host: hostname or IP address of the server.
|
||||
* - port: TCP port of the server.
|
||||
* - path: path of a UNIX domain socket when scheme is 'unix'.
|
||||
* - timeout: timeout to perform the connection.
|
||||
* - read_write_timeout: timeout of read / write operations.
|
||||
*
|
||||
* @link http://github.com/nrk/phpiredis
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class PhpiredisSocketConnection extends AbstractConnection
|
||||
{
|
||||
private $reader;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(ParametersInterface $parameters)
|
||||
{
|
||||
$this->assertExtensions();
|
||||
|
||||
parent::__construct($parameters);
|
||||
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server and destroys the underlying resource and the
|
||||
* protocol reader resource when PHP's garbage collector kicks in.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
phpiredis_reader_destroy($this->reader);
|
||||
|
||||
parent::__destruct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the socket and phpiredis extensions are loaded in PHP.
|
||||
*/
|
||||
protected function assertExtensions()
|
||||
{
|
||||
if (!extension_loaded('sockets')) {
|
||||
throw new NotSupportedException(
|
||||
'The "sockets" extension is required by this connection backend.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!extension_loaded('phpiredis')) {
|
||||
throw new NotSupportedException(
|
||||
'The "phpiredis" extension is required by this connection backend.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function assertParameters(ParametersInterface $parameters)
|
||||
{
|
||||
parent::assertParameters($parameters);
|
||||
|
||||
if (isset($parameters->persistent)) {
|
||||
throw new NotSupportedException(
|
||||
'Persistent connections are not supported by this connection backend.'
|
||||
);
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of the protocol reader resource.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
private function createReader()
|
||||
{
|
||||
$reader = phpiredis_reader_create();
|
||||
|
||||
phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
|
||||
phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
|
||||
|
||||
return $reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying protocol reader resource.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
protected function getReader()
|
||||
{
|
||||
return $this->reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for inline responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
private function getStatusHandler()
|
||||
{
|
||||
return function ($payload) {
|
||||
return StatusResponse::get($payload);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for error responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function getErrorHandler()
|
||||
{
|
||||
return function ($payload) {
|
||||
return new ErrorResponse($payload);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method used to throw exceptions on socket errors.
|
||||
*/
|
||||
private function emitSocketError()
|
||||
{
|
||||
$errno = socket_last_error();
|
||||
$errstr = socket_strerror($errno);
|
||||
|
||||
$this->disconnect();
|
||||
|
||||
$this->onConnectionError(trim($errstr), $errno);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the address of an host from connection parameters.
|
||||
*
|
||||
* @param ParametersInterface $parameters Parameters used to initialize the connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected static function getAddress(ParametersInterface $parameters)
|
||||
{
|
||||
if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
if ($host === $address = gethostbyname($host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $address;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function createResource()
|
||||
{
|
||||
$parameters = $this->parameters;
|
||||
|
||||
if ($parameters->scheme === 'unix') {
|
||||
$address = $parameters->path;
|
||||
$domain = AF_UNIX;
|
||||
$protocol = 0;
|
||||
} else {
|
||||
if (false === $address = self::getAddress($parameters)) {
|
||||
$this->onConnectionError("Cannot resolve the address of '$parameters->host'.");
|
||||
}
|
||||
|
||||
$domain = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? AF_INET6 : AF_INET;
|
||||
$protocol = SOL_TCP;
|
||||
}
|
||||
|
||||
$socket = @socket_create($domain, SOCK_STREAM, $protocol);
|
||||
|
||||
if (!is_resource($socket)) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
|
||||
$this->setSocketOptions($socket, $parameters);
|
||||
$this->connectWithTimeout($socket, $address, $parameters);
|
||||
|
||||
return $socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets options on the socket resource from the connection parameters.
|
||||
*
|
||||
* @param resource $socket Socket resource.
|
||||
* @param ParametersInterface $parameters Parameters used to initialize the connection.
|
||||
*/
|
||||
private function setSocketOptions($socket, ParametersInterface $parameters)
|
||||
{
|
||||
if ($parameters->scheme !== 'unix') {
|
||||
if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
|
||||
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($parameters->read_write_timeout)) {
|
||||
$rwtimeout = (float) $parameters->read_write_timeout;
|
||||
$timeoutSec = floor($rwtimeout);
|
||||
$timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
|
||||
|
||||
$timeout = array(
|
||||
'sec' => $timeoutSec,
|
||||
'usec' => $timeoutUsec,
|
||||
);
|
||||
|
||||
if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
|
||||
if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the actual connection to the server with a timeout.
|
||||
*
|
||||
* @param resource $socket Socket resource.
|
||||
* @param string $address IP address (DNS-resolved from hostname)
|
||||
* @param ParametersInterface $parameters Parameters used to initialize the connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function connectWithTimeout($socket, $address, ParametersInterface $parameters)
|
||||
{
|
||||
socket_set_nonblock($socket);
|
||||
|
||||
if (@socket_connect($socket, $address, (int) $parameters->port) === false) {
|
||||
$error = socket_last_error();
|
||||
|
||||
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
}
|
||||
|
||||
socket_set_block($socket);
|
||||
|
||||
$null = null;
|
||||
$selectable = array($socket);
|
||||
|
||||
$timeout = (float) $parameters->timeout;
|
||||
$timeoutSecs = floor($timeout);
|
||||
$timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
|
||||
|
||||
$selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
|
||||
|
||||
if ($selected === 2) {
|
||||
$this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED);
|
||||
}
|
||||
|
||||
if ($selected === 0) {
|
||||
$this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT);
|
||||
}
|
||||
|
||||
if ($selected === false) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
if (parent::connect() && $this->initCommands) {
|
||||
foreach ($this->initCommands as $command) {
|
||||
$this->executeCommand($command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
if ($this->isConnected()) {
|
||||
socket_close($this->getResource());
|
||||
parent::disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function write($buffer)
|
||||
{
|
||||
$socket = $this->getResource();
|
||||
|
||||
while (($length = strlen($buffer)) > 0) {
|
||||
$written = socket_write($socket, $buffer, $length);
|
||||
|
||||
if ($length === $written) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($written === false) {
|
||||
$this->onConnectionError('Error while writing bytes to the server.');
|
||||
}
|
||||
|
||||
$buffer = substr($buffer, $written);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
$socket = $this->getResource();
|
||||
$reader = $this->reader;
|
||||
|
||||
while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
|
||||
if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '' || $buffer === null) {
|
||||
$this->emitSocketError();
|
||||
}
|
||||
|
||||
phpiredis_reader_feed($reader, $buffer);
|
||||
}
|
||||
|
||||
if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
|
||||
return phpiredis_reader_get_reply($reader);
|
||||
} else {
|
||||
$this->onProtocolError(phpiredis_reader_get_error($reader));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$arguments = $command->getArguments();
|
||||
array_unshift($arguments, $command->getId());
|
||||
|
||||
$this->write(phpiredis_format_command($arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
$this->assertExtensions();
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,228 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\NotSupportedException;
|
||||
use Predis\Response\Error as ErrorResponse;
|
||||
use Predis\Response\Status as StatusResponse;
|
||||
|
||||
/**
|
||||
* This class provides the implementation of a Predis connection that uses PHP's
|
||||
* streams for network communication and wraps the phpiredis C extension (PHP
|
||||
* bindings for hiredis) to parse and serialize the Redis protocol.
|
||||
*
|
||||
* This class is intended to provide an optional low-overhead alternative for
|
||||
* processing responses from Redis compared to the standard pure-PHP classes.
|
||||
* Differences in speed when dealing with short inline responses are practically
|
||||
* nonexistent, the actual speed boost is for big multibulk responses when this
|
||||
* protocol processor can parse and return responses very fast.
|
||||
*
|
||||
* For instructions on how to build and install the phpiredis extension, please
|
||||
* consult the repository of the project.
|
||||
*
|
||||
* The connection parameters supported by this class are:
|
||||
*
|
||||
* - scheme: it can be either 'redis', 'tcp' or 'unix'.
|
||||
* - host: hostname or IP address of the server.
|
||||
* - port: TCP port of the server.
|
||||
* - path: path of a UNIX domain socket when scheme is 'unix'.
|
||||
* - timeout: timeout to perform the connection.
|
||||
* - read_write_timeout: timeout of read / write operations.
|
||||
* - async_connect: performs the connection asynchronously.
|
||||
* - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
|
||||
* - persistent: the connection is left intact after a GC collection.
|
||||
*
|
||||
* @link https://github.com/nrk/phpiredis
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class PhpiredisStreamConnection extends StreamConnection
|
||||
{
|
||||
private $reader;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(ParametersInterface $parameters)
|
||||
{
|
||||
$this->assertExtensions();
|
||||
|
||||
parent::__construct($parameters);
|
||||
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
phpiredis_reader_destroy($this->reader);
|
||||
|
||||
parent::__destruct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the phpiredis extension is loaded in PHP.
|
||||
*/
|
||||
private function assertExtensions()
|
||||
{
|
||||
if (!extension_loaded('phpiredis')) {
|
||||
throw new NotSupportedException(
|
||||
'The "phpiredis" extension is required by this connection backend.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function tcpStreamInitializer(ParametersInterface $parameters)
|
||||
{
|
||||
$uri = "tcp://[{$parameters->host}]:{$parameters->port}";
|
||||
$flags = STREAM_CLIENT_CONNECT;
|
||||
$socket = null;
|
||||
|
||||
if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
|
||||
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
|
||||
}
|
||||
|
||||
if (isset($parameters->persistent) && (bool) $parameters->persistent) {
|
||||
$flags |= STREAM_CLIENT_PERSISTENT;
|
||||
$uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
|
||||
}
|
||||
|
||||
$resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
|
||||
|
||||
if (!$resource) {
|
||||
$this->onConnectionError(trim($errstr), $errno);
|
||||
}
|
||||
|
||||
if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) {
|
||||
$rwtimeout = (float) $parameters->read_write_timeout;
|
||||
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
|
||||
|
||||
$timeout = array(
|
||||
'sec' => $timeoutSeconds = floor($rwtimeout),
|
||||
'usec' => ($rwtimeout - $timeoutSeconds) * 1000000,
|
||||
);
|
||||
|
||||
$socket = $socket ?: socket_import_stream($resource);
|
||||
@socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout);
|
||||
@socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
|
||||
}
|
||||
|
||||
if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
|
||||
$socket = $socket ?: socket_import_stream($resource);
|
||||
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of the protocol reader resource.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
private function createReader()
|
||||
{
|
||||
$reader = phpiredis_reader_create();
|
||||
|
||||
phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
|
||||
phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
|
||||
|
||||
return $reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying protocol reader resource.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
protected function getReader()
|
||||
{
|
||||
return $this->reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for inline responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function getStatusHandler()
|
||||
{
|
||||
return function ($payload) {
|
||||
return StatusResponse::get($payload);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for error responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function getErrorHandler()
|
||||
{
|
||||
return function ($errorMessage) {
|
||||
return new ErrorResponse($errorMessage);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
$socket = $this->getResource();
|
||||
$reader = $this->reader;
|
||||
|
||||
while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
|
||||
$buffer = stream_socket_recvfrom($socket, 4096);
|
||||
|
||||
if ($buffer === false || $buffer === '') {
|
||||
$this->onConnectionError('Error while reading bytes from the server.');
|
||||
}
|
||||
|
||||
phpiredis_reader_feed($reader, $buffer);
|
||||
}
|
||||
|
||||
if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
|
||||
return phpiredis_reader_get_reply($reader);
|
||||
} else {
|
||||
$this->onProtocolError(phpiredis_reader_get_error($reader));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$arguments = $command->getArguments();
|
||||
array_unshift($arguments, $command->getId());
|
||||
|
||||
$this->write(phpiredis_format_command($arguments));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
$this->assertExtensions();
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
}
|
||||
292
plugins/cache-redis/Predis/Connection/StreamConnection.php
Normal file
292
plugins/cache-redis/Predis/Connection/StreamConnection.php
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\Response\Error as ErrorResponse;
|
||||
use Predis\Response\Status as StatusResponse;
|
||||
|
||||
/**
|
||||
* Standard connection to Redis servers implemented on top of PHP's streams.
|
||||
* The connection parameters supported by this class are:.
|
||||
*
|
||||
* - scheme: it can be either 'redis', 'tcp' or 'unix'.
|
||||
* - host: hostname or IP address of the server.
|
||||
* - port: TCP port of the server.
|
||||
* - path: path of a UNIX domain socket when scheme is 'unix'.
|
||||
* - timeout: timeout to perform the connection.
|
||||
* - read_write_timeout: timeout of read / write operations.
|
||||
* - async_connect: performs the connection asynchronously.
|
||||
* - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
|
||||
* - persistent: the connection is left intact after a GC collection.
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class StreamConnection extends AbstractConnection
|
||||
{
|
||||
/**
|
||||
* Disconnects from the server and destroys the underlying resource when the
|
||||
* garbage collector kicks in only if the connection has not been marked as
|
||||
* persistent.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if (isset($this->parameters->persistent) && $this->parameters->persistent) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function createResource()
|
||||
{
|
||||
switch ($this->parameters->scheme) {
|
||||
case 'tcp':
|
||||
case 'redis':
|
||||
return $this->tcpStreamInitializer($this->parameters);
|
||||
|
||||
case 'unix':
|
||||
return $this->unixStreamInitializer($this->parameters);
|
||||
|
||||
default:
|
||||
throw new \InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes a TCP stream resource.
|
||||
*
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
protected function tcpStreamInitializer(ParametersInterface $parameters)
|
||||
{
|
||||
if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
||||
$uri = "tcp://$parameters->host:$parameters->port";
|
||||
} else {
|
||||
$uri = "tcp://[$parameters->host]:$parameters->port";
|
||||
}
|
||||
|
||||
$flags = STREAM_CLIENT_CONNECT;
|
||||
|
||||
if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
|
||||
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
|
||||
}
|
||||
|
||||
if (isset($parameters->persistent) && (bool) $parameters->persistent) {
|
||||
$flags |= STREAM_CLIENT_PERSISTENT;
|
||||
$uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
|
||||
}
|
||||
|
||||
$resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
|
||||
|
||||
if (!$resource) {
|
||||
$this->onConnectionError(trim($errstr), $errno);
|
||||
}
|
||||
|
||||
if (isset($parameters->read_write_timeout)) {
|
||||
$rwtimeout = (float) $parameters->read_write_timeout;
|
||||
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
|
||||
$timeoutSeconds = floor($rwtimeout);
|
||||
$timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
|
||||
stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
|
||||
}
|
||||
|
||||
if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
|
||||
$socket = socket_import_stream($resource);
|
||||
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes a UNIX stream resource.
|
||||
*
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
protected function unixStreamInitializer(ParametersInterface $parameters)
|
||||
{
|
||||
if (!isset($parameters->path)) {
|
||||
throw new InvalidArgumentException('Missing UNIX domain socket path.');
|
||||
}
|
||||
|
||||
$uri = "unix://{$parameters->path}";
|
||||
$flags = STREAM_CLIENT_CONNECT;
|
||||
|
||||
if ((bool) $parameters->persistent) {
|
||||
$flags |= STREAM_CLIENT_PERSISTENT;
|
||||
}
|
||||
|
||||
$resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
|
||||
|
||||
if (!$resource) {
|
||||
$this->onConnectionError(trim($errstr), $errno);
|
||||
}
|
||||
|
||||
if (isset($parameters->read_write_timeout)) {
|
||||
$rwtimeout = (float) $parameters->read_write_timeout;
|
||||
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
|
||||
$timeoutSeconds = floor($rwtimeout);
|
||||
$timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
|
||||
stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
if (parent::connect() && $this->initCommands) {
|
||||
foreach ($this->initCommands as $command) {
|
||||
$this->executeCommand($command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
if ($this->isConnected()) {
|
||||
fclose($this->getResource());
|
||||
parent::disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a write operation over the stream of the buffer containing a
|
||||
* command serialized with the Redis wire protocol.
|
||||
*
|
||||
* @param string $buffer Representation of a command in the Redis wire protocol.
|
||||
*/
|
||||
protected function write($buffer)
|
||||
{
|
||||
$socket = $this->getResource();
|
||||
|
||||
while (($length = strlen($buffer)) > 0) {
|
||||
$written = @fwrite($socket, $buffer);
|
||||
|
||||
if ($length === $written) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($written === false || $written === 0) {
|
||||
$this->onConnectionError('Error while writing bytes to the server.');
|
||||
}
|
||||
|
||||
$buffer = substr($buffer, $written);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
$socket = $this->getResource();
|
||||
$chunk = fgets($socket);
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
$this->onConnectionError('Error while reading line from the server.');
|
||||
}
|
||||
|
||||
$prefix = $chunk[0];
|
||||
$payload = substr($chunk, 1, -2);
|
||||
|
||||
switch ($prefix) {
|
||||
case '+':
|
||||
return StatusResponse::get($payload);
|
||||
|
||||
case '$':
|
||||
$size = (int) $payload;
|
||||
|
||||
if ($size === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
$bulkData = '';
|
||||
$bytesLeft = ($size += 2);
|
||||
|
||||
do {
|
||||
$chunk = fread($socket, min($bytesLeft, 4096));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
$this->onConnectionError('Error while reading bytes from the server.');
|
||||
}
|
||||
|
||||
$bulkData .= $chunk;
|
||||
$bytesLeft = $size - strlen($bulkData);
|
||||
} while ($bytesLeft > 0);
|
||||
|
||||
return substr($bulkData, 0, -2);
|
||||
|
||||
case '*':
|
||||
$count = (int) $payload;
|
||||
|
||||
if ($count === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
$multibulk = array();
|
||||
|
||||
for ($i = 0; $i < $count; ++$i) {
|
||||
$multibulk[$i] = $this->read();
|
||||
}
|
||||
|
||||
return $multibulk;
|
||||
|
||||
case ':':
|
||||
return (int) $payload;
|
||||
|
||||
case '-':
|
||||
return new ErrorResponse($payload);
|
||||
|
||||
default:
|
||||
$this->onProtocolError("Unknown response prefix: '$prefix'.");
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$commandID = $command->getId();
|
||||
$arguments = $command->getArguments();
|
||||
|
||||
$cmdlen = strlen($commandID);
|
||||
$reqlen = count($arguments) + 1;
|
||||
|
||||
$buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
|
||||
|
||||
for ($i = 0, $reqlen--; $i < $reqlen; ++$i) {
|
||||
$argument = $arguments[$i];
|
||||
$arglen = strlen($argument);
|
||||
$buffer .= "\${$arglen}\r\n{$argument}\r\n";
|
||||
}
|
||||
|
||||
$this->write($buffer);
|
||||
}
|
||||
}
|
||||
353
plugins/cache-redis/Predis/Connection/WebdisConnection.php
Normal file
353
plugins/cache-redis/Predis/Connection/WebdisConnection.php
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Predis package.
|
||||
*
|
||||
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Predis\Connection;
|
||||
|
||||
use Predis\Command\CommandInterface;
|
||||
use Predis\NotSupportedException;
|
||||
use Predis\Protocol\ProtocolException;
|
||||
use Predis\Response\Error as ErrorResponse;
|
||||
use Predis\Response\Status as StatusResponse;
|
||||
|
||||
/**
|
||||
* This class implements a Predis connection that actually talks with Webdis
|
||||
* instead of connecting directly to Redis. It relies on the cURL extension to
|
||||
* communicate with the web server and the phpiredis extension to parse the
|
||||
* protocol for responses returned in the http response bodies.
|
||||
*
|
||||
* Some features are not yet available or they simply cannot be implemented:
|
||||
* - Pipelining commands.
|
||||
* - Publish / Subscribe.
|
||||
* - MULTI / EXEC transactions (not yet supported by Webdis).
|
||||
*
|
||||
* The connection parameters supported by this class are:
|
||||
*
|
||||
* - scheme: must be 'http'.
|
||||
* - host: hostname or IP address of the server.
|
||||
* - port: TCP port of the server.
|
||||
* - timeout: timeout to perform the connection.
|
||||
* - user: username for authentication.
|
||||
* - pass: password for authentication.
|
||||
*
|
||||
* @link http://webd.is
|
||||
* @link http://github.com/nicolasff/webdis
|
||||
* @link http://github.com/seppo0010/phpiredis
|
||||
*
|
||||
* @author Daniele Alessandri <suppakilla@gmail.com>
|
||||
*/
|
||||
class WebdisConnection implements NodeConnectionInterface
|
||||
{
|
||||
private $parameters;
|
||||
private $resource;
|
||||
private $reader;
|
||||
|
||||
/**
|
||||
* @param ParametersInterface $parameters Initialization parameters for the connection.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function __construct(ParametersInterface $parameters)
|
||||
{
|
||||
$this->assertExtensions();
|
||||
|
||||
if ($parameters->scheme !== 'http') {
|
||||
throw new \InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'.");
|
||||
}
|
||||
|
||||
$this->parameters = $parameters;
|
||||
|
||||
$this->resource = $this->createCurl();
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the underlying cURL and protocol reader resources when the garbage
|
||||
* collector kicks in.
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
curl_close($this->resource);
|
||||
phpiredis_reader_destroy($this->reader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method used to throw on unsupported methods.
|
||||
*
|
||||
* @param string $method Name of the unsupported method.
|
||||
*
|
||||
* @throws NotSupportedException
|
||||
*/
|
||||
private function throwNotSupportedException($method)
|
||||
{
|
||||
$class = __CLASS__;
|
||||
throw new NotSupportedException("The method $class::$method() is not supported.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cURL and phpiredis extensions are loaded in PHP.
|
||||
*/
|
||||
private function assertExtensions()
|
||||
{
|
||||
if (!extension_loaded('curl')) {
|
||||
throw new NotSupportedException(
|
||||
'The "curl" extension is required by this connection backend.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!extension_loaded('phpiredis')) {
|
||||
throw new NotSupportedException(
|
||||
'The "phpiredis" extension is required by this connection backend.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes cURL.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
private function createCurl()
|
||||
{
|
||||
$parameters = $this->getParameters();
|
||||
|
||||
if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
|
||||
$host = "[$host]";
|
||||
}
|
||||
|
||||
$options = array(
|
||||
CURLOPT_FAILONERROR => true,
|
||||
CURLOPT_CONNECTTIMEOUT_MS => $parameters->timeout * 1000,
|
||||
CURLOPT_URL => "$parameters->scheme://$host:$parameters->port",
|
||||
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_WRITEFUNCTION => array($this, 'feedReader'),
|
||||
);
|
||||
|
||||
if (isset($parameters->user, $parameters->pass)) {
|
||||
$options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}";
|
||||
}
|
||||
|
||||
curl_setopt_array($resource = curl_init(), $options);
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the phpiredis protocol reader.
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
private function createReader()
|
||||
{
|
||||
$reader = phpiredis_reader_create();
|
||||
|
||||
phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
|
||||
phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
|
||||
|
||||
return $reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for inline responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function getStatusHandler()
|
||||
{
|
||||
return function ($payload) {
|
||||
return StatusResponse::get($payload);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the handler used by the protocol reader for error responses.
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
protected function getErrorHandler()
|
||||
{
|
||||
return function ($payload) {
|
||||
return new ErrorResponse($payload);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Feeds the phpredis reader resource with the data read from the network.
|
||||
*
|
||||
* @param resource $resource Reader resource.
|
||||
* @param string $buffer Buffer of data read from a connection.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function feedReader($resource, $buffer)
|
||||
{
|
||||
phpiredis_reader_feed($this->reader, $buffer);
|
||||
|
||||
return strlen($buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function connect()
|
||||
{
|
||||
// NOOP
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
// NOOP
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function isConnected()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the specified command is supported by this connection class.
|
||||
*
|
||||
* @param CommandInterface $command Command instance.
|
||||
*
|
||||
* @throws NotSupportedException
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCommandId(CommandInterface $command)
|
||||
{
|
||||
switch ($commandID = $command->getId()) {
|
||||
case 'AUTH':
|
||||
case 'SELECT':
|
||||
case 'MULTI':
|
||||
case 'EXEC':
|
||||
case 'WATCH':
|
||||
case 'UNWATCH':
|
||||
case 'DISCARD':
|
||||
case 'MONITOR':
|
||||
throw new NotSupportedException("Command '$commandID' is not allowed by Webdis.");
|
||||
|
||||
default:
|
||||
return $commandID;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function writeRequest(CommandInterface $command)
|
||||
{
|
||||
$this->throwNotSupportedException(__FUNCTION__);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function readResponse(CommandInterface $command)
|
||||
{
|
||||
$this->throwNotSupportedException(__FUNCTION__);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function executeCommand(CommandInterface $command)
|
||||
{
|
||||
$resource = $this->resource;
|
||||
$commandId = $this->getCommandId($command);
|
||||
|
||||
if ($arguments = $command->getArguments()) {
|
||||
$arguments = implode('/', array_map('urlencode', $arguments));
|
||||
$serializedCommand = "$commandId/$arguments.raw";
|
||||
} else {
|
||||
$serializedCommand = "$commandId.raw";
|
||||
}
|
||||
|
||||
curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand);
|
||||
|
||||
if (curl_exec($resource) === false) {
|
||||
$error = curl_error($resource);
|
||||
$errno = curl_errno($resource);
|
||||
|
||||
throw new ConnectionException($this, trim($error), $errno);
|
||||
}
|
||||
|
||||
if (phpiredis_reader_get_state($this->reader) !== PHPIREDIS_READER_STATE_COMPLETE) {
|
||||
throw new ProtocolException($this, phpiredis_reader_get_error($this->reader));
|
||||
}
|
||||
|
||||
return phpiredis_reader_get_reply($this->reader);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getResource()
|
||||
{
|
||||
return $this->resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getParameters()
|
||||
{
|
||||
return $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function addConnectCommand(CommandInterface $command)
|
||||
{
|
||||
$this->throwNotSupportedException(__FUNCTION__);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read()
|
||||
{
|
||||
$this->throwNotSupportedException(__FUNCTION__);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
return "{$this->parameters->host}:{$this->parameters->port}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array('parameters');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
$this->assertExtensions();
|
||||
|
||||
$this->resource = $this->createCurl();
|
||||
$this->reader = $this->createReader();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue