Refactored \Tamer to \TamerLib
This commit is contained in:
parent
1b8d2fb40a
commit
7eea383ce9
25 changed files with 81 additions and 81 deletions
464
src/TamerLib/Protocols/Gearman/Client.php
Normal file
464
src/TamerLib/Protocols/Gearman/Client.php
Normal file
|
@ -0,0 +1,464 @@
|
|||
<?php
|
||||
|
||||
/** @noinspection PhpMissingFieldTypeInspection */
|
||||
|
||||
namespace TamerLib\Protocols\Gearman;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use GearmanClient;
|
||||
use GearmanTask;
|
||||
use LogLib\Log;
|
||||
use TamerLib\Abstracts\TaskPriority;
|
||||
use TamerLib\Exceptions\ConnectionException;
|
||||
use TamerLib\Interfaces\ClientProtocolInterface;
|
||||
use TamerLib\Objects\Job;
|
||||
use TamerLib\Objects\JobResults;
|
||||
use TamerLib\Objects\Task;
|
||||
|
||||
class Client implements ClientProtocolInterface
|
||||
{
|
||||
/**
|
||||
* The Gearman Client object
|
||||
*
|
||||
* @var GearmanClient|null $client
|
||||
*/
|
||||
private $client;
|
||||
|
||||
/**
|
||||
* An array of servers that have been defined
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $defined_servers;
|
||||
|
||||
/**
|
||||
* Used for tracking the current execution of tasks and run callbacks on completion
|
||||
*
|
||||
* @var Task[]
|
||||
*/
|
||||
private $tasks;
|
||||
|
||||
/**
|
||||
* Indicates if the client should automatically reconnect to the server if the connection is lost
|
||||
* (default: true)
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $automatic_reconnect;
|
||||
|
||||
/**
|
||||
* The Unix timestamp of the next time the client should attempt to reconnect to the server
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $next_reconnect;
|
||||
|
||||
/**
|
||||
* The options to use when connecting to the server
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
* @param string|null $username
|
||||
* @param string|null $password
|
||||
*/
|
||||
public function __construct(?string $username=null, ?string $password=null)
|
||||
{
|
||||
$this->client = null;
|
||||
$this->tasks = [];
|
||||
$this->automatic_reconnect = false;
|
||||
$this->next_reconnect = time() + 1800;
|
||||
$this->defined_servers = [];
|
||||
$this->options = [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a server to the list of servers to use
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanclient.addserver.php
|
||||
* @param string $host (127.0.0.1)
|
||||
* @param int $port (default: 4730)
|
||||
* @return void
|
||||
*/
|
||||
public function addServer(string $host, int $port): void
|
||||
{
|
||||
if(!isset($this->defined_servers[$host]))
|
||||
{
|
||||
$this->defined_servers[$host] = [];
|
||||
}
|
||||
|
||||
if(in_array($port, $this->defined_servers[$host]))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
$this->defined_servers[$host][] = $port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a list of servers to the list of servers to use
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanclient.addservers.php
|
||||
* @param array $servers (host:port, host:port, ...)
|
||||
* @return void
|
||||
*/
|
||||
public function addServers(array $servers): void
|
||||
{
|
||||
foreach($servers as $server)
|
||||
{
|
||||
$server = explode(':', $server);
|
||||
$this->addServer($server[0], (int)$server[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the server(s)
|
||||
*
|
||||
* @return void
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function connect(): void
|
||||
{
|
||||
if($this->isConnected())
|
||||
return;
|
||||
|
||||
$this->client = new GearmanClient();
|
||||
|
||||
// Parse $options combination via bitwise OR operator
|
||||
$options = array_reduce($this->options, function($carry, $item)
|
||||
{
|
||||
return $carry | $item;
|
||||
});
|
||||
|
||||
$this->client->addOptions($options);
|
||||
|
||||
foreach($this->defined_servers as $host => $ports)
|
||||
{
|
||||
foreach($ports as $port)
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->client->addServer($host, $port);
|
||||
Log::debug('net.nosial.tamerlib', 'connected to gearman server: ' . $host . ':' . $port);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
throw new ConnectionException('Failed to connect to Gearman server: ' . $host . ':' . $port, 0, $e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->client->setCompleteCallback([$this, 'callbackHandler']);
|
||||
$this->client->setFailCallback([$this, 'callbackHandler']);
|
||||
$this->client->setDataCallback([$this, 'callbackHandler']);
|
||||
$this->client->setStatusCallback([$this, 'callbackHandler']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server(s)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function disconnect(): void
|
||||
{
|
||||
if(!$this->isConnected())
|
||||
return;
|
||||
|
||||
Log::debug('net.nosial.tamerlib', 'disconnecting from gearman server(s)');
|
||||
$this->client->clearCallbacks();
|
||||
unset($this->client);
|
||||
$this->client = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconnects to the server(s)
|
||||
*
|
||||
* @return void
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function reconnect(): void
|
||||
{
|
||||
Log::debug('net.nosial.tamerlib', 'reconnecting to gearman server(s)');
|
||||
|
||||
$this->disconnect();
|
||||
$this->connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current status of the client
|
||||
*
|
||||
* @inheritDoc
|
||||
* @return bool
|
||||
*/
|
||||
public function isConnected(): bool
|
||||
{
|
||||
if($this->client === null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The automatic reconnect process
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function preformAutoreconf(): void
|
||||
{
|
||||
if($this->automatic_reconnect && $this->next_reconnect < time())
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->reconnect();
|
||||
}
|
||||
catch (Exception $e)
|
||||
{
|
||||
Log::error('net.nosial.tamerlib', 'Failed to reconnect to Gearman server: ' . $e->getMessage());
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->next_reconnect = time() + 1800;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds client options
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanclient.addoptions.php
|
||||
* @param int[] $options (GEARMAN_CLIENT_NON_BLOCKING, GEARMAN_CLIENT_UNBUFFERED_RESULT, GEARMAN_CLIENT_FREE_TASKS)
|
||||
* @return void
|
||||
*/
|
||||
public function setOptions(array $options): void
|
||||
{
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current client options
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the current client options
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearOptions(): void
|
||||
{
|
||||
$this->options = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a closure in the background
|
||||
*
|
||||
* @param Closure $closure
|
||||
* @return void
|
||||
*/
|
||||
public function doClosure(Closure $closure): void
|
||||
{
|
||||
$closure_task = new Task('tamer_closure', $closure);
|
||||
$closure_task->setClosure(true);
|
||||
$this->do($closure_task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a task in the background
|
||||
*
|
||||
* @param Task $task
|
||||
* @return void
|
||||
*/
|
||||
public function do(Task $task): void
|
||||
{
|
||||
$this->preformAutoreconf();
|
||||
|
||||
$this->tasks[] = $task;
|
||||
$job = new Job($task);
|
||||
|
||||
switch($task->getPriority())
|
||||
{
|
||||
case TaskPriority::High:
|
||||
$this->client->doHighBackground($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
|
||||
case TaskPriority::Low:
|
||||
$this->client->doLowBackground($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
|
||||
default:
|
||||
case TaskPriority::Normal:
|
||||
$this->client->doBackground($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a task to the list of tasks to run
|
||||
*
|
||||
* @param Task $task
|
||||
* @return void
|
||||
*/
|
||||
public function queue(Task $task): void
|
||||
{
|
||||
$this->preformAutoreconf();
|
||||
|
||||
$this->tasks[] = $task;
|
||||
$job = new Job($task);
|
||||
|
||||
switch($task->getPriority())
|
||||
{
|
||||
case TaskPriority::High:
|
||||
$this->client->addTaskHigh($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
|
||||
case TaskPriority::Low:
|
||||
$this->client->addTaskLow($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
|
||||
default:
|
||||
case TaskPriority::Normal:
|
||||
$this->client->addTask($task->getFunctionName(), msgpack_pack($job->toArray()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a closure task to the list of tasks to run
|
||||
*
|
||||
* @param Closure $closure
|
||||
* @param Closure|null $callback
|
||||
* @return void
|
||||
*/
|
||||
public function queueClosure(Closure $closure, ?Closure $callback=null): void
|
||||
{
|
||||
$closure_task = new Task('tamer_closure', $closure, $callback);
|
||||
$closure_task->setClosure(true);
|
||||
$this->queue($closure_task);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function run(): bool
|
||||
{
|
||||
if(!$this->isConnected())
|
||||
return false;
|
||||
|
||||
$this->preformAutoreconf();
|
||||
|
||||
if(!$this->client->runTasks())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a task callback in the foreground
|
||||
*
|
||||
* @param GearmanTask $task
|
||||
* @return void
|
||||
*/
|
||||
public function callbackHandler(GearmanTask $task): void
|
||||
{
|
||||
$job_result = JobResults::fromArray(msgpack_unpack($task->data()));
|
||||
$internal_task = $this->getTaskById($job_result->getId());
|
||||
|
||||
Log::debug('net.nosial.tamerlib', 'callback for task ' . $internal_task->getId() . ' with status ' . $job_result->getStatus() . ' and data size ' . strlen($task->data()) . ' bytes');
|
||||
|
||||
try
|
||||
{
|
||||
if($internal_task->isClosure())
|
||||
{
|
||||
// If the task is a closure, we need to run the callback with the closure's return value
|
||||
// instead of the job result object
|
||||
$internal_task->runCallback($job_result->getData());
|
||||
return;
|
||||
}
|
||||
|
||||
$internal_task->runCallback($job_result);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
Log::error('net.nosial.tamerlib', 'Failed to run callback for task ' . $internal_task->getId() . ': ' . $e->getMessage(), $e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->removeTask($internal_task);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id
|
||||
* @return Task|null
|
||||
*/
|
||||
private function getTaskById(string $id): ?Task
|
||||
{
|
||||
foreach($this->tasks as $task)
|
||||
{
|
||||
if($task->getId() === $id)
|
||||
{
|
||||
return $task;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a task from the list of tasks
|
||||
*
|
||||
* @param Task $task
|
||||
* @return void
|
||||
*/
|
||||
private function removeTask(Task $task): void
|
||||
{
|
||||
$this->tasks = array_filter($this->tasks, function($item) use ($task)
|
||||
{
|
||||
return $item->getId() !== $task->getId();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function automaticReconnectionEnabled(): bool
|
||||
{
|
||||
return $this->automatic_reconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $enable
|
||||
*/
|
||||
public function enableAutomaticReconnection(bool $enable): void
|
||||
{
|
||||
$this->automatic_reconnect = $enable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all remaining tasks and closes the connection
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->disconnect();
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
}
|
||||
}
|
371
src/TamerLib/Protocols/Gearman/Worker.php
Normal file
371
src/TamerLib/Protocols/Gearman/Worker.php
Normal file
|
@ -0,0 +1,371 @@
|
|||
<?php
|
||||
|
||||
/** @noinspection PhpMissingFieldTypeInspection */
|
||||
|
||||
namespace TamerLib\Protocols\Gearman;
|
||||
|
||||
use Exception;
|
||||
use GearmanJob;
|
||||
use GearmanWorker;
|
||||
use LogLib\Log;
|
||||
use Opis\Closure\SerializableClosure;
|
||||
use TamerLib\Abstracts\JobStatus;
|
||||
use TamerLib\Exceptions\ConnectionException;
|
||||
use TamerLib\Interfaces\WorkerProtocolInterface;
|
||||
use TamerLib\Objects\Job;
|
||||
use TamerLib\Objects\JobResults;
|
||||
|
||||
class Worker implements WorkerProtocolInterface
|
||||
{
|
||||
/**
|
||||
* The Gearman Worker Instance (if connected)
|
||||
*
|
||||
* @var GearmanWorker|null
|
||||
*/
|
||||
private $worker;
|
||||
|
||||
/**
|
||||
* The list of servers that have been added
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $defined_servers;
|
||||
|
||||
/**
|
||||
* Indicates if the worker should automatically reconnect to the server
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $automatic_reconnect;
|
||||
|
||||
/**
|
||||
* The Unix Timestamp of when the next reconnect should occur (if automatic_reconnect is true)
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $next_reconnect;
|
||||
|
||||
/**
|
||||
* The options to use when connecting to the server
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Public Constructor with optional username and password
|
||||
*
|
||||
* @param string|null $username
|
||||
* @param string|null $password
|
||||
*/
|
||||
public function __construct(?string $username=null, ?string $password=null)
|
||||
{
|
||||
$this->worker = null;
|
||||
$this->defined_servers = [];
|
||||
$this->automatic_reconnect = false;
|
||||
$this->next_reconnect = time() + 1800;
|
||||
$this->options = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a server to the list of servers to use
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanworker.addserver.php
|
||||
* @param string $host (
|
||||
* @param int $port (default: 4730)
|
||||
* @return void
|
||||
*/
|
||||
public function addServer(string $host, int $port): void
|
||||
{
|
||||
if(!isset($this->defined_servers[$host]))
|
||||
{
|
||||
$this->defined_servers[$host] = [];
|
||||
}
|
||||
|
||||
if(in_array($port, $this->defined_servers[$host]))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
$this->defined_servers[$host][] = $port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a list of servers to the list of servers to use
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanworker.addservers.php
|
||||
* @param string[] $servers (host:port, host:port, ...)
|
||||
* @return void
|
||||
*/
|
||||
public function addServers(array $servers): void
|
||||
{
|
||||
foreach($servers as $server)
|
||||
{
|
||||
$server = explode(':', $server);
|
||||
$this->addServer($server[0], (int)$server[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the server
|
||||
*
|
||||
* @return void
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function connect(): void
|
||||
{
|
||||
if($this->isConnected())
|
||||
return;
|
||||
|
||||
$this->worker = new GearmanWorker();
|
||||
$this->worker->addOptions(GEARMAN_WORKER_GRAB_UNIQ);
|
||||
|
||||
foreach($this->defined_servers as $host => $ports)
|
||||
{
|
||||
foreach($ports as $port)
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->worker->addServer($host, $port);
|
||||
Log::debug('net.nosial.tamerlib', 'connected to gearman server: ' . $host . ':' . $port);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
throw new ConnectionException('Failed to connect to Gearman server: ' . $host . ':' . $port, 0, $e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->worker->addFunction('tamer_closure', function(GearmanJob $job)
|
||||
{
|
||||
$received_job = Job::fromArray(msgpack_unpack($job->workload()));
|
||||
Log::debug('net.nosial.tamerlib', 'received closure: ' . $received_job->getId());
|
||||
|
||||
try
|
||||
{
|
||||
/** @var SerializableClosure $closure */
|
||||
$closure = $received_job->getData();
|
||||
$result = $closure($received_job);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
$job->sendFail();
|
||||
unset($e);
|
||||
return;
|
||||
}
|
||||
|
||||
$job_results = new JobResults($received_job, JobStatus::Success, $result);
|
||||
$job->sendComplete(msgpack_pack($job_results->toArray()));
|
||||
Log::debug('net.nosial.tamerlib', 'completed closure: ' . $received_job->getId());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function disconnect(): void
|
||||
{
|
||||
if(!$this->isConnected())
|
||||
return;
|
||||
|
||||
$this->worker->unregisterAll();
|
||||
unset($this->worker);
|
||||
$this->worker = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconnects to the server if the connection has been lost
|
||||
*
|
||||
* @return void
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function reconnect(): void
|
||||
{
|
||||
$this->disconnect();
|
||||
$this->connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the worker is connected to the server
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isConnected(): bool
|
||||
{
|
||||
return $this->worker !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The automatic reconnect process
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function preformAutoreconf(): void
|
||||
{
|
||||
if($this->automatic_reconnect && $this->next_reconnect < time())
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->reconnect();
|
||||
}
|
||||
catch (Exception $e)
|
||||
{
|
||||
Log::error('net.nosial.tamerlib', 'Failed to reconnect to Gearman server: ' . $e->getMessage());
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->next_reconnect = time() + 1800;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the options to use when connecting to the server
|
||||
*
|
||||
* @param array $options
|
||||
* @return bool
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOptions(array $options): void
|
||||
{
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the options to use when connecting to the server
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the options to use when connecting to the server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearOptions(): void
|
||||
{
|
||||
$this->options = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function automaticReconnectionEnabled(): bool
|
||||
{
|
||||
return $this->automatic_reconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $enable
|
||||
* @return void
|
||||
*/
|
||||
public function enableAutomaticReconnection(bool $enable): void
|
||||
{
|
||||
$this->automatic_reconnect = $enable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a function to the list of functions to call
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanworker.addfunction.php
|
||||
* @param string $name The name of the function to register with the job server
|
||||
* @param callable $callable The callback function to call when the job is received
|
||||
* @return void
|
||||
*/
|
||||
public function addFunction(string $name, callable $callable): void
|
||||
{
|
||||
$this->worker->addFunction($name, function(GearmanJob $job) use ($callable)
|
||||
{
|
||||
$received_job = Job::fromArray(msgpack_unpack($job->workload()));
|
||||
Log::debug('net.nosial.tamerlib', 'received job: ' . $received_job->getId());
|
||||
|
||||
try
|
||||
{
|
||||
$result = $callable($received_job);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
$job->sendFail();
|
||||
unset($e);
|
||||
return;
|
||||
}
|
||||
|
||||
$job_results = new JobResults($received_job, JobStatus::Success, $result);
|
||||
$job->sendComplete(msgpack_pack($job_results->toArray()));
|
||||
Log::debug('net.nosial.tamerlib', 'completed job: ' . $received_job->getId());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a function from the list of functions to call
|
||||
*
|
||||
* @param string $function_name The name of the function to unregister
|
||||
* @return void
|
||||
*/
|
||||
public function removeFunction(string $function_name): void
|
||||
{
|
||||
$this->worker->unregister($function_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a job and calls the appropriate callback function
|
||||
*
|
||||
* @link http://php.net/manual/en/gearmanworker.work.php
|
||||
* @param bool $blocking (default: true) Whether to block until a job is received
|
||||
* @param int $timeout (default: 500) The timeout in milliseconds (if $blocking is false)
|
||||
* @param bool $throw_errors (default: false) Whether to throw exceptions on errors
|
||||
* @return void Returns nothing
|
||||
* @throws ConnectionException
|
||||
*/
|
||||
public function work(bool $blocking=true, int $timeout=500, bool $throw_errors=false): void
|
||||
{
|
||||
$this->worker->setTimeout($timeout);
|
||||
|
||||
while(true)
|
||||
{
|
||||
@$this->preformAutoreconf();
|
||||
@$this->worker->work();
|
||||
|
||||
if($this->worker->returnCode() == GEARMAN_COULD_NOT_CONNECT)
|
||||
{
|
||||
throw new ConnectionException('Could not connect to Gearman server');
|
||||
}
|
||||
|
||||
if($this->worker->returnCode() == GEARMAN_TIMEOUT && !$blocking)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if($this->worker->returnCode() != GEARMAN_SUCCESS && $throw_errors)
|
||||
{
|
||||
Log::error('net.nosial.tamerlib', 'Gearman worker error: ' . $this->worker->error());
|
||||
}
|
||||
|
||||
if($blocking)
|
||||
{
|
||||
usleep($timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all remaining tasks and closes the connection
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
try
|
||||
{
|
||||
$this->disconnect();
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
}
|
||||
}
|
401
src/TamerLib/Protocols/RabbitMq/Client.php
Normal file
401
src/TamerLib/Protocols/RabbitMq/Client.php
Normal file
|
@ -0,0 +1,401 @@
|
|||
<?php
|
||||
|
||||
/** @noinspection PhpMissingFieldTypeInspection */
|
||||
|
||||
namespace TamerLib\Protocols\RabbitMq;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use PhpAmqpLib\Channel\AMQPChannel;
|
||||
use PhpAmqpLib\Connection\AMQPStreamConnection;
|
||||
use PhpAmqpLib\Message\AMQPMessage;
|
||||
use TamerLib\Abstracts\TaskPriority;
|
||||
use TamerLib\Exceptions\ServerException;
|
||||
use TamerLib\Interfaces\ClientProtocolInterface;
|
||||
use TamerLib\Objects\Job;
|
||||
use TamerLib\Objects\JobResults;
|
||||
use TamerLib\Objects\Task;
|
||||
|
||||
class Client implements ClientProtocolInterface
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $server_cache;
|
||||
|
||||
/**
|
||||
* Used for tracking the current execution of tasks and run callbacks on completion
|
||||
*
|
||||
* @var Task[]
|
||||
*/
|
||||
private $tasks;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $automatic_reconnect;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $next_reconnect;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $username;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $password;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* @var AMQPStreamConnection|null
|
||||
*/
|
||||
private $connection;
|
||||
|
||||
/**
|
||||
* @var AMQPChannel|null
|
||||
*/
|
||||
private $channel;
|
||||
|
||||
/***
|
||||
* @param string|null $username
|
||||
* @param string|null $password
|
||||
*/
|
||||
public function __construct(?string $username=null, ?string $password=null)
|
||||
{
|
||||
$this->tasks = [];
|
||||
$this->automatic_reconnect = false;
|
||||
$this->next_reconnect = time() + 1800;
|
||||
$this->server_cache = [];
|
||||
$this->options = [];
|
||||
$this->connection = null;
|
||||
$this->username = $username;
|
||||
$this->password = $password;
|
||||
|
||||
try
|
||||
{
|
||||
$this->reconnect();
|
||||
}
|
||||
catch(ServerException $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
}
|
||||
|
||||
public function setOptions(array $options): bool
|
||||
{
|
||||
$this->options = $options;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function addServer(string $host, int $port): bool
|
||||
{
|
||||
if(!isset($this->server_cache[$host]))
|
||||
{
|
||||
$this->server_cache[$host] = [];
|
||||
}
|
||||
|
||||
if(in_array($port, $this->server_cache[$host]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->server_cache[$host][] = $port;
|
||||
$this->reconnect();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a list of servers to the list of servers to use
|
||||
*
|
||||
* @param array $servers (host:port, host:port, ...)
|
||||
* @return bool
|
||||
*/
|
||||
public function addServers(array $servers): bool
|
||||
{
|
||||
foreach($servers as $server)
|
||||
{
|
||||
$server = explode(':', $server);
|
||||
$this->addServer($server[0], $server[1]);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the priority for a task based on the priority level
|
||||
*
|
||||
* @param int $priority
|
||||
* @return int
|
||||
*/
|
||||
private static function calculatePriority(int $priority): int
|
||||
{
|
||||
if($priority < TaskPriority::Low)
|
||||
return 0;
|
||||
|
||||
if($priority > TaskPriority::High)
|
||||
return 255;
|
||||
|
||||
return (int) round(($priority / TaskPriority::High) * 255);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Task $task
|
||||
* @return void
|
||||
*/
|
||||
public function do(Task $task): void
|
||||
{
|
||||
$job = new Job($task);
|
||||
|
||||
$message = new AMQPMessage(msgpack_pack($job->toArray()), [
|
||||
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
|
||||
'priority' => self::calculatePriority($task->getPriority()),
|
||||
]);
|
||||
|
||||
$this->channel->basic_publish($message, '', 'tamer_queue');
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a closure in the background
|
||||
*
|
||||
* @param Closure $closure
|
||||
* @return void
|
||||
*/
|
||||
public function doClosure(Closure $closure): void
|
||||
{
|
||||
$closure_task = new Task('tamer_closure', $closure);
|
||||
$closure_task->setClosure(true);
|
||||
$this->do($closure_task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues a task to be executed
|
||||
*
|
||||
* @param Task $task
|
||||
* @return void
|
||||
*/
|
||||
public function queue(Task $task): void
|
||||
{
|
||||
$this->tasks[] = $task;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a closure task to the list of tasks to run
|
||||
*
|
||||
* @param Closure $closure
|
||||
* @param $callback
|
||||
* @return void
|
||||
*/
|
||||
public function queueClosure(Closure $closure, $callback): void
|
||||
{
|
||||
$closure_task = new Task('tamer_closure', $closure, $callback);
|
||||
$closure_task->setClosure(true);
|
||||
$this->queue($closure_task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the tasks that has been added
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function run(): bool
|
||||
{
|
||||
if(count($this->tasks) === 0)
|
||||
return false;
|
||||
|
||||
$correlationIds = [];
|
||||
|
||||
/** @var Task $task */
|
||||
foreach($this->tasks as $task)
|
||||
{
|
||||
$correlationIds[] = $task->getId();
|
||||
|
||||
$job = new Job($task);
|
||||
|
||||
$message = new AMQPMessage(msgpack_pack($job->toArray()), [
|
||||
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
|
||||
'correlation_id' => $task->getId(),
|
||||
'reply_to' => 'tamer_queue',
|
||||
'priority' => self::calculatePriority($task->getPriority()),
|
||||
]);
|
||||
|
||||
$this->channel->basic_publish($message, '', 'tamer_queue');
|
||||
}
|
||||
|
||||
// Register callback for each task
|
||||
$callback = function($msg) use (&$correlationIds)
|
||||
{
|
||||
$job_result = JobResults::fromArray(msgpack_unpack($msg->body));
|
||||
$task = $this->getTaskById($job_result->getId());
|
||||
|
||||
try
|
||||
{
|
||||
$task->runCallback($job_result);
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
// Remove the processed correlation_id
|
||||
$index = array_search($msg->get('correlation_id'), $correlationIds);
|
||||
if ($index !== false) {
|
||||
unset($correlationIds[$index]);
|
||||
}
|
||||
|
||||
$this->channel->basic_ack($msg->delivery_info['delivery_tag']);
|
||||
|
||||
// Stop consuming when all tasks are processed
|
||||
if(count($correlationIds) === 0)
|
||||
{
|
||||
$this->channel->basic_cancel($msg->delivery_info['consumer_tag']);
|
||||
}
|
||||
};
|
||||
|
||||
$this->channel->basic_consume('tamer_queue', '', false, false, false, false, $callback);
|
||||
|
||||
// Start consuming messages
|
||||
while(count($this->channel->callbacks))
|
||||
{
|
||||
$this->channel->wait();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id
|
||||
* @return Task|null
|
||||
*/
|
||||
private function getTaskById(string $id): ?Task
|
||||
{
|
||||
foreach($this->tasks as $task)
|
||||
{
|
||||
if($task->getId() === $id)
|
||||
{
|
||||
return $task;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns True if the client is automatically reconnecting to the server
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function automaticReconnectionEnabled(): bool
|
||||
{
|
||||
return $this->automatic_reconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables or disables automatic reconnecting to the server
|
||||
*
|
||||
* @param bool $enable
|
||||
* @return void
|
||||
*/
|
||||
public function enableAutomaticReconnection(bool $enable): void
|
||||
{
|
||||
$this->automatic_reconnect = $enable;
|
||||
}
|
||||
|
||||
private function reconnect()
|
||||
{
|
||||
$connections = [];
|
||||
|
||||
if(count($this->server_cache) === 0)
|
||||
return;
|
||||
|
||||
foreach($this->server_cache as $host => $ports)
|
||||
{
|
||||
foreach($ports as $port)
|
||||
{
|
||||
$host = [
|
||||
'host' => $host,
|
||||
'port' => $port
|
||||
];
|
||||
|
||||
if($this->username !== null)
|
||||
$host['username'] = $this->username;
|
||||
|
||||
if($this->password !== null)
|
||||
$host['password'] = $this->password;
|
||||
|
||||
$connections[] = $host;
|
||||
}
|
||||
}
|
||||
|
||||
// Can only connect to one server for now, so we'll just use the first one
|
||||
$selected_connection = $connections[0];
|
||||
$this->disconnect();
|
||||
$this->connection = new AMQPStreamConnection(
|
||||
$selected_connection['host'],
|
||||
$selected_connection['port'],
|
||||
$selected_connection['username'] ?? null,
|
||||
$selected_connection['password'] ?? null
|
||||
);
|
||||
|
||||
$this->channel = $this->connection->channel();
|
||||
$this->channel->queue_declare('tamer_queue', false, true, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function disconnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!is_null($this->channel))
|
||||
{
|
||||
$this->channel->close();
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->channel = null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if(!is_null($this->connection))
|
||||
{
|
||||
$this->connection->close();
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server when the object is destroyed
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
}
|
324
src/TamerLib/Protocols/RabbitMq/Worker.php
Normal file
324
src/TamerLib/Protocols/RabbitMq/Worker.php
Normal file
|
@ -0,0 +1,324 @@
|
|||
<?php
|
||||
|
||||
/** @noinspection PhpMissingFieldTypeInspection */
|
||||
|
||||
namespace TamerLib\Protocols\RabbitMq;
|
||||
|
||||
use Exception;
|
||||
use PhpAmqpLib\Channel\AMQPChannel;
|
||||
use PhpAmqpLib\Connection\AMQPStreamConnection;
|
||||
use PhpAmqpLib\Message\AMQPMessage;
|
||||
use TamerLib\Abstracts\JobStatus;
|
||||
use TamerLib\Interfaces\WorkerProtocolInterface;
|
||||
use TamerLib\Objects\Job;
|
||||
use TamerLib\Objects\JobResults;
|
||||
|
||||
class Worker implements WorkerProtocolInterface
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $server_cache;
|
||||
|
||||
/**
|
||||
* @var false
|
||||
*/
|
||||
private $automatic_reconnect;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $next_reconnect;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $functions;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $username;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $password;
|
||||
|
||||
/**
|
||||
* @var AMQPStreamConnection|null
|
||||
*/
|
||||
private $connection;
|
||||
|
||||
/**
|
||||
* @var AMQPChannel|null
|
||||
*/
|
||||
private $channel;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __construct(?string $username = null, ?string $password = null)
|
||||
{
|
||||
$this->server_cache = [];
|
||||
$this->functions = [];
|
||||
$this->automatic_reconnect = false;
|
||||
$this->next_reconnect = time() + 1800;
|
||||
$this->username = $username;
|
||||
$this->password = $password;
|
||||
|
||||
try
|
||||
{
|
||||
$this->reconnect();
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function addServer(string $host, int $port): bool
|
||||
{
|
||||
if(!isset($this->server_cache[$host]))
|
||||
{
|
||||
$this->server_cache[$host] = [];
|
||||
}
|
||||
|
||||
if(in_array($port, $this->server_cache[$host]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->server_cache[$host][] = $port;
|
||||
$this->reconnect();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function addServers(array $servers): void
|
||||
{
|
||||
foreach($servers as $server)
|
||||
{
|
||||
$server = explode(':', $server);
|
||||
$this->addServer($server[0], $server[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function setOptions(array $options): bool
|
||||
{
|
||||
$this->options = $options;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function automaticReconnectionEnabled(): bool
|
||||
{
|
||||
return $this->automatic_reconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function enableAutomaticReconnection(bool $enable): void
|
||||
{
|
||||
$this->automatic_reconnect = $enable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function addFunction(string $name, callable $callable, mixed $context = null): void
|
||||
{
|
||||
$this->functions[$name] = [
|
||||
'function' => $callable,
|
||||
'context' => $context
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function removeFunction(string $function_name): void
|
||||
{
|
||||
unset($this->functions[$function_name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function work(bool $blocking = true, int $timeout = 500, bool $throw_errors = false): void
|
||||
{
|
||||
$callback = function($message) use ($throw_errors)
|
||||
{
|
||||
var_dump($message->body);
|
||||
$job = Job::fromArray(msgpack_unpack($message->body));
|
||||
|
||||
$job_results = new JobResults($job, JobStatus::Success, 'Hello from worker!');
|
||||
|
||||
try
|
||||
{
|
||||
// Return $job_results
|
||||
$this->channel->basic_publish(
|
||||
new AMQPMessage(
|
||||
msgpack_pack($job_results->toArray()),
|
||||
[
|
||||
'correlation_id' => $job->getId()
|
||||
]
|
||||
)
|
||||
);
|
||||
|
||||
$this->channel->basic_ack($message->delivery_info['delivery_tag']);
|
||||
}
|
||||
catch (Exception $e)
|
||||
{
|
||||
if ($throw_errors)
|
||||
{
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$job_results = new JobResults($job, JobStatus::Exception, $e->getMessage());
|
||||
|
||||
// Return $job_results
|
||||
$this->channel->basic_publish(
|
||||
new AMQPMessage(
|
||||
msgpack_pack($job_results->toArray()),
|
||||
[
|
||||
'correlation_id' => $job->getId()
|
||||
]
|
||||
)
|
||||
);
|
||||
|
||||
$this->channel->basic_ack($message->delivery_info['delivery_tag']);
|
||||
}
|
||||
};
|
||||
|
||||
$this->channel->basic_consume('tamer_queue', '', false, false, false, false, $callback);
|
||||
|
||||
if ($blocking)
|
||||
{
|
||||
while(true)
|
||||
{
|
||||
$this->channel->wait();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$start = microtime(true);
|
||||
while (true)
|
||||
{
|
||||
if (microtime(true) - $start >= $timeout / 1000)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
$this->channel->wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function reconnect()
|
||||
{
|
||||
$connections = [];
|
||||
|
||||
if(count($this->server_cache) === 0)
|
||||
return;
|
||||
|
||||
foreach($this->server_cache as $host => $ports)
|
||||
{
|
||||
foreach($ports as $port)
|
||||
{
|
||||
$host = [
|
||||
'host' => $host,
|
||||
'port' => $port
|
||||
];
|
||||
|
||||
if($this->username !== null)
|
||||
$host['username'] = $this->username;
|
||||
|
||||
if($this->password !== null)
|
||||
$host['password'] = $this->password;
|
||||
|
||||
$connections[] = $host;
|
||||
}
|
||||
}
|
||||
|
||||
// Can only connect to one server for now, so we'll just use the first one
|
||||
$selected_connection = $connections[0];
|
||||
$this->disconnect();
|
||||
$this->connection = new AMQPStreamConnection(
|
||||
$selected_connection['host'],
|
||||
$selected_connection['port'],
|
||||
$selected_connection['username'] ?? null,
|
||||
$selected_connection['password'] ?? null
|
||||
);
|
||||
|
||||
$this->channel = $this->connection->channel();
|
||||
$this->channel->queue_declare('tamer_queue', false, true, false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function disconnect()
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!is_null($this->channel))
|
||||
{
|
||||
$this->channel->close();
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->channel = null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if(!is_null($this->connection))
|
||||
{
|
||||
$this->connection->close();
|
||||
}
|
||||
}
|
||||
catch(Exception $e)
|
||||
{
|
||||
unset($e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$this->connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects from the server when the object is destroyed
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->disconnect();
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue