Drop the Queue module (#1777)

* Remove the Queue module and update massmailer

Queue module was only used by the massmailer module & it duplicated the functionality of the email service, resulting in added complexity for no real benefit.

This commit removes the Queue module outright and points the massmailer to the email service instead, which already implements queing, retires, and time limits.

* Added the ability to view the email queue

* Minor front-end improvements, added removal patch

* Cleanly handle a client being removed
This commit is contained in:
Belle Aerni authored and GitHub committed 2023-11-07 17:45:46 -08:00
1 parent b8de2c1dc9
commit f8d1e90d78
15 files changed
+169 -703

No files matched your search

+1 -1
View File
@@ -315,7 +315,7 @@ LOCK TABLES `setting` WRITE;
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
VALUES
(1,'last_patch','36',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(1,'last_patch','37',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(3,'company_email','company@email.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(4,'company_signature','FOSSBilling.org - Client Management, Invoice and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
+1 -1
View File
@@ -480,7 +480,7 @@ LOCK TABLES `setting` WRITE;
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
VALUES
(1,'last_patch','36',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(1,'last_patch','37',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(2,'company_name','FOSSBilling demo',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(3,'company_email','demo@fossbilling.org',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(4,'company_signature','FOSSBilling.org - Client Management, Invoice and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
+24
View File
@@ -334,6 +334,30 @@ class UpdatePatcher implements InjectionAwareInterface
];
$this->executeFileActions($fileActions);
},
37 => function () {
// Patch to complete remove the outdated queue module.
// @see https://github.com/FOSSBilling/FOSSBilling/pull/1777
// Drop the old queue tables.
$q = "DROP TABLE queue;";
$this->executeSql($q);
$q = "DROP TABLE queue_message;";
$this->executeSql($q);
$ext_service = $this->di['mod_service']('extension');
// If the queue extension exists, uninstall it.
$queue_ext = $ext_service->findExtension('mod', 'queue');
if ($queue_ext instanceof \Model_Extension) {
$ext_service->uninstall($queue_ext);
}
// Finally, remove old queue module from the disk.
$fileActions = [
PATH_MODS . DIRECTORY_SEPARATOR . 'Queue' => 'unlink',
];
$this->executeFileActions($fileActions);
},
];
ksort($patches, SORT_NATURAL);
+23
View File
@@ -406,4 +406,27 @@ class Admin extends \Api_Abstract
return true;
}
public function get_queue(array $data)
{
$per_page = $data['per_page'] ?? $this->di['pager']->getPer_page();
[$sql, $params] = $this->getService()->queueGetSearchQuery($data);
$pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page);
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = [
'id' => $item['id'] ?? '',
'recipient' => $item['recipient'] ?? '',
'subject' => $item['subject'] ?? '',
'content' => $item['content'] ?? '',
'to_name' => $item['to_name'] ?? '',
'status' => $item['status'] ?? '',
'tries' => $item['tries'] ?? '',
'created_at' => $item['created_at'] ?? '',
'updated_at' => $item['updated_at'] ?? '',
];
}
return $pager;
}
}
+29 -11
View File
@@ -389,6 +389,35 @@ class Service implements \FOSSBilling\InjectionAwareInterface
return [$query, $bindings];
}
public function queueGetSearchQuery($data)
{
$query = 'SELECT * FROM mod_email_queue';
$search = $data['search'] ?? null;
$where = [];
$bindings = [];
if ($search) {
$search = "%$search%";
$where[] = '(recipient LIKE :recipient OR subject LIKE :subject OR content LIKE :content OR to_name LIKE :to_name)';
$bindings[':recipient'] = $search;
$bindings[':subject'] = $search;
$bindings[':content'] = $search;
$bindings[':to_name'] = $search;
}
if (!empty($where)) {
$query = $query . ' WHERE ' . implode(' AND ', $where);
}
$query .= ' ORDER BY updated_at DESC';
return [$query, $bindings];
}
public function templateToApiArray(\Model_EmailTemplate $model, $deep = false)
{
$data = [
@@ -609,17 +638,6 @@ class Service implements \FOSSBilling\InjectionAwareInterface
$message = $e->getMessage();
error_log($message);
// Prevent mass retries of emails if one of them is "invalid"
if (str_contains($message, 'Invalid address:')) {
try {
$this->di['db']->trash($queue);
} catch (\Exception $e) {
error_log($e->getMessage());
}
return true;
}
if ($queue->priority) {
--$queue->priority;
}
@@ -21,6 +21,7 @@
{% set active_menu = 'system' %}
{% block content %}
{% set params = admin.extension_config_get({ 'ext': 'mod_email' }) %}
<div class="card-tabs">
<ul class="nav nav-tabs" role="tablist">
@@ -35,6 +36,9 @@
{{ 'New template'|trans }}
</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" href="#tab-queue" data-bs-toggle="tab">{{ 'Email queue'|trans }}</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" href="#tab-email" data-bs-toggle="tab">{{ 'Email settings'|trans }}</a>
</li>
@@ -65,7 +69,7 @@
</div>
{% include 'partial_search.html.twig' %}
<div class="table-responsive">
<table class="table card-table table-vcenter table-striped text-nowrap">
<table class="table card-table table-vcenter table-striped text-nowrap sortable">
<thead>
<tr>
<th class="w-1">{{ 'Subject'|trans }}</th>
@@ -92,7 +96,8 @@
{% if template.enabled == 0 %}
<span class="badge bg-danger me-1"></span>
{% endif %}
{{ mf.q(template.enabled) }}</td>
{{ mf.q(template.enabled) }}
</td>
<td>
<a class="btn btn-icon" href="{{ '/email/template'|alink }}/{{ template.id }}"
data-bs-toggle="tooltip" data-bs-title="{{ 'Edit'|trans }}">
@@ -175,7 +180,64 @@
</form>
</div>
{% set params = admin.extension_config_get({ 'ext': 'mod_email' }) %}
<div class="tab-pane fade show" id="tab-queue" role="tabpanel">
{% include 'partial_search.html.twig' %}
<div class="table-responsive">
<p>{{ 'FOSSBilling queues emails to have them be sent via cron in the background. Here you may find the list of queued emails and how many times the system has tried to send them.'|trans }}</p>
<p>{{ 'Emails that have been sent or that failed to be sent will not be listed here.'|trans }}</p>
<table class="table card-table table-vcenter table-striped text-nowrap sortable">
<thead>
<tr>
<th class="w-1">{{ 'Subject'|trans }}</th>
<th>{{ 'To'|trans }}</th>
<th>{{ 'To (Email)'|trans }}</th>
<th>{{ 'Status'|trans }}</th>
<th>{{ 'Tries'|trans }}</th>
<th>{{ 'Created at'|trans }}</th>
<th>{{ 'Updated at'|trans }}</th>
</tr>
</thead>
<tbody>
{% set queue = admin.email_get_queue({ 'per_page': 100, 'page': request.page }|merge(request)) %}
{% for i, queuedEmail in queue.list %}
<tr>
<td>
{{ queuedEmail.subject }}
</td>
<td>
{{ queuedEmail.to_name }}
</td>
<td>
<a href="mailto:{{ queuedEmail.recipient }}"> {{ queuedEmail.recipient }}</a>
</td>
<td>
{% if queuedEmail.status == 'unsent' %}
<span class="badge bg-danger me-1"></span>
{% else %}
<span class="badge bg-success me-1"></span>
{% endif %}
<span class="text-capitalize">{{ queuedEmail.status }}</span>
</td>
<td>
{{ queuedEmail.tries }} / {{ params.cancel_after|default('5') }}
</td>
<td>
{{ queuedEmail.created_at|format_date }}
</td>
<td>
{{ queuedEmail.updated_at|format_date }}
</td>
</tr>
{% else %}
<tr>
<td class="text-muted" colspan="5">{{ 'The list is empty.'|trans }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="tab-pane fade" id="tab-email" role="tabpanel">
<form method="post" action="{{ 'api/admin/extension/config_save'|link }}" class="api-form" data-api-msg="{{ 'Email settings updated'|trans }}">
<input type="hidden" name="CSRFToken" value="{{ CSRFToken }}"/>
@@ -188,15 +250,15 @@
<div class="col-md-6">
<div class="mb-2">
<small class="form-hint">{{ 'Send emails per cron run (0 = unlimited)'|trans }}</small>
<input class="form-control" type="text" name="queue_once" placeholder="0" value="{{ params.queue_once }}">
<input class="form-control" type="text" name="queue_once" placeholder="0" value="{{ params.queue_once|default('0') }}">
</div>
<div class="mb-2">
<small class="form-hint">{{ 'Max email sending time in minutes (0 = unlimited, default 5 min.)'|trans }}</small>
<input class="form-control" type="text" name="time_limit" placeholder="5" value="{% if params.time_limit %}{{ params.time_limit }}{% else %}5{% endif %}">
<input class="form-control" type="text" name="time_limit" placeholder="5" value="{{ params.time_limit|default('5') }}">
</div>
<div class="mb-2">
<small class="form-hint">{{ 'Cancel sending email after unsuccessful tries (0 = do not cancel)'|trans }}</small>
<input class="form-control" type="text" name="cancel_after" placeholder="5" value="{{ params.cancel_after }}">
<input class="form-control" type="text" name="cancel_after" placeholder="5" value="{{ params.cancel_after|default('5') }}">
</div>
</div>
</div>
+18 -15
View File
@@ -154,7 +154,7 @@ Order our services at {{ "order"|link }}
throw new \FOSSBilling\InformationException('Add some content before sending message');
}
$this->getService()->sendMessage($model, $client_id);
$this->getService()->sendMessage($model, $client_id, true);
$this->di['logger']->info('Sent test mail message #%s to client ', $model->id);
@@ -175,22 +175,9 @@ Order our services at {{ "order"|link }}
throw new \FOSSBilling\InformationException('Add some content before sending message');
}
$mod = $this->di['mod']('massmailer');
$c = $mod->getConfig();
$interval = isset($c['interval']) ? (int) $c['interval'] : 30;
$max = isset($c['limit']) ? (int) $c['limit'] : 25;
$clients = $this->getService()->getMessageReceivers($model, $data);
foreach ($clients as $c) {
$d = [
'queue' => 'massmailer',
'mod' => 'massmailer',
'handler' => 'sendMail',
'max' => $max,
'interval' => $interval,
'params' => ['msg_id' => $model->id, 'client_id' => $c['id']],
];
$this->di['api_admin']->queue_message_add($d);
$this->getService()->sendMail(['msg_id' => $model->id, 'client_id' => $c['id']]);
}
$model->status = 'sent';
@@ -274,6 +261,22 @@ Order our services at {{ "order"|link }}
];
}
/**
* Returns the email associated with the test client
*
* @return string
*/
public function get_test_client(): string
{
try {
$client = $this->di['mod_service']('client')->get(['id' => $this->_getTestClientId()]);
} catch (\Exception) {
return 'Unknown';
}
return $client->email;
}
private function _getTestClientId()
{
$mod = $this->di['mod']('massmailer');
+3 -37
View File
@@ -138,7 +138,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
return [$ps, $pc];
}
public function sendMessage($model, $client_id)
public function sendMessage($model, $client_id, $sendNow = false)
{
[$ps, $pc] = $this->getParsed($model, $client_id);
@@ -169,32 +169,8 @@ class Service implements \FOSSBilling\InjectionAwareInterface
return true;
}
// Setup the email settings & recipients
$settings = $this->di['mod']('email')->getConfig();
$transport = $settings['mailer'] ?? 'sendmail';
$customDSN = $settings['custom_dsn'] ?? null;
$sender = [
'email' => $data['from'],
'name' => $data['from_name'],
];
$recipient = [
'email' => $data['to'],
'name' => $data['to_name'],
];
try {
// Send the email
$mail = new \FOSSBilling\Mail($sender, $recipient, $data['subject'], $data['content'], $transport, $customDSN);
$mail->send($settings);
} catch (\Exception $e) {
error_log($e->getMessage());
}
// Log the email activity to the database if enabled
if (isset($settings['log_enabled']) && $settings['log_enabled']) {
$activityService = $this->di['mod_service']('activity');
$activityService->logEmail($data['subject'], $client_id, $data['from'], $data['to'], $data['content']);
}
$emailService = $this->di['mod_service']('email');
$emailService->sendMail($data['to'], $data['from'], $data['subject'], $data['content'], $data['to_name'], $data['from_name'], $data['client_id'], null, $sendNow);
return true;
}
@@ -214,16 +190,6 @@ class Service implements \FOSSBilling\InjectionAwareInterface
return $row;
}
public static function onAfterAdminCronRun(\Box_Event $event)
{
try {
$di = $event->getDi();
$di['api_admin']->queue_execute(['queue' => 'massmailer']);
} catch (\Exception $e) {
error_log('Error executing massmailer queue: ' . $e->getMessage());
}
}
public function sendMail($params)
{
$model = $this->di['db']->load('mod_massmailer', $params['msg_id']);
@@ -115,32 +115,9 @@
</div>
{% set params = admin.extension_config_get({"ext":"mod_massmailer"}) %}
<form method="post" action="admin/extension/config_save" class="api-form"
data-api-msg="{{ 'Configuration updated'|trans }}">
data-api-reload="1">
<input type="hidden" name="CSRFToken" value="{{ CSRFToken }}">
<input type="hidden" name="ext" value="mod_massmailer">
<div class="card-body">
<div class="row">
<div class="d-flex flex-row gap-2">
<div class="col-auto d-flex align-items-center">
<label>Send</label>
</div>
<div class="col-auto d-flex align-items-center">
<input class="w-5 form-control" type="text" name="limit"
value="{{ params.limit }}" placeholder="25">
</div>
<div class="col-auto d-flex align-items-center">
<label>emails every</label>
</div>
<div class="col-auto d-flex align-items-center">
<input class="w-5 form-control" type="text" name="interval"
value="{{ params.interval }}" placeholder="30">
</div>
<div class="col-auto d-flex align-items-center">
<label>seconds until complete</label>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="mb-3 row">
<label class="col-md-3 col-form-label" for="test_client_id">{{ 'Client to send test email'|trans }}</label>
@@ -159,6 +136,7 @@
<input type="hidden" name="test_client_id" value="{{ request.test_client_id }}" />
{% endif %}
</div>
<span class="text-muted">{{ 'Test emails will be sent to: '|trans }} {{ admin.massmailer_get_test_client }}</span>
</div>
</div>
<div class="card-footer text-end">
-299
View File
@@ -1,299 +0,0 @@
<?php
/**
* Copyright 2022-2023 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
/**
* Queue is a powerful tool to execute long running tasks in the background.
*/
namespace Box\Mod\Queue\Api;
use FOSSBilling\Environment;
class Admin extends \Api_Abstract
{
/**
* Returns paginated list of queues.
*
* @optional string $mod - filter results by mod
* @optional string $name - filter results by name
*
* @return array
*/
public function get_list($data)
{
[$sql, $params] = $this->getService()->getSearchQuery($data);
$per_page = $data['per_page'] ?? $this->di['pager']->getPer_page();
$pager = $this->di['pager']->getSimpleResultSet($sql, $params, $per_page);
foreach ($pager['list'] as $key => $item) {
$pager['list'][$key] = $this->getService()->toApiArray($item);
}
return $pager;
}
/**
* Get queue details.
*
* @return array
*/
public function get($data)
{
$q = $this->_getQueue($data);
$service = $this->getService();
return $service->toApiArray($q);
}
/**
* Remove message from queue.
*
* @return bool
*/
public function message_delete($data)
{
$required = [
'id' => 'Queue message ID is required',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
$msg = $this->di['db']->getExistingModelById('queue_message', $data['id'], 'Queue message not found');
$this->di['db']->trash($msg);
return true;
}
/**
* Add message to queue to be executed later.
*
* @optional string $execute_at - Message execution time. Schedule message to be executed later, ie: 2022-12-29 14:53:51
* @optional mixed $params - queue message params. Any serializable param
* @optional string $handler - function handler. Static function name in extensions service class - default $queue name
* @optional int $interval - Interval to execute messages in the queue. Default 30
* @optional int $max - Maximum amount of messages to be executed per interval. Default 25
*
* @return int - message id
*/
public function message_add($data)
{
$required = [
'queue' => 'Queue name not provided',
'mod' => 'Module name not provided',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
$mod = $this->di['mod']($data['mod']);
$service = $mod->getService();
$handler = $data['handler'] ?? $data['queue'];
if (!method_exists($service, $handler)) {
throw new \FOSSBilling\Exception('Message handler function :method does not exists', [':ext' => $data['mod'], ':method' => $service::class . ':' . $handler]);
}
$interval = isset($data['interval']) ? (int) $data['interval'] : 30;
$max = isset($data['max']) ? (int) $data['max'] : 25;
$q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]);
if (!$q) {
$q = $this->di['db']->dispense('queue');
$q->name = $data['queue'];
$q->module = $data['mod'];
$q->created_at = date('Y-m-d H:i:s');
}
$q->timeout = $interval;
$q->iteration = $max;
$q->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($q);
$params = $data['params'] ?? null;
$body = base64_encode(json_encode($params));
$msg = $this->di['db']->dispense('queue_message');
$msg->queue_id = $q->id;
$msg->handler = $handler;
$msg->body = $body;
$msg->hash = hash('sha256', $body);
$msg->created_at = date('Y-m-d H:i:s');
$msg->updated_at = date('Y-m-d H:i:s');
if (isset($data['execute_at'])) {
$msg->execute_at = date('Y-m-d H:i:s', strtotime($data['execute_at']));
}
$this->di['db']->store($msg);
return (int) $msg->id;
}
/**
* Execute queue.
* For example: Send 25 emails every 30 seconds until complete
* Executing queue is locked until finished.
*
* @optional int $max - Maximum amount of messages to be executed per interval. Default is queue max amount
* @optional int $interval - interval in seconds for message to be executed. Default is queue timeout
* @optional bool $until_complete - Execute until all messages in queue are executed. Default true
*
* @return bool - returns true when queue finished executing
*/
public function execute($data)
{
$required = [
'queue' => 'Queue name not provided',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
$q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]);
if (!$q) {
throw new \Exception('Queue not found');
}
$lock_file = PATH_LOG . '/queue_' . $q->id . '.lock';
touch($lock_file);
$file_handle = fopen($lock_file, 'r+');
if (!flock($file_handle, LOCK_EX | LOCK_NB)) {
$this->di['logger']->info(sprintf('Queue %s is being executed by other process.', $q->id));
throw new \Exception('This queue is being executed by other process.');
}
$this->di['logger']->info('Locked queue: ' . $q->id);
$max = isset($data['max']) ? (int) $data['max'] : $q->iteration;
$interval = isset($data['interval']) ? (int) $data['interval'] : $q->timeout;
$until_complete = isset($data['until_complete']) ? (bool) $data['until_complete'] : true;
$this->di['logger']->info(sprintf('Started executing %s queue by selecting %s messages every %s seconds', $q->name, $max, $interval));
$iterate = true;
while ($iterate) {
$start = (int) array_sum(explode(' ', microtime()));
$r = $this->_execute($q, $max, $interval);
$end = (int) array_sum(explode(' ', microtime()));
$wait_for = $interval - ($end - $start);
if ($wait_for > 0.000001) {
$this->di['logger']->info('Waiting for ' . $wait_for . ' seconds to continue iteration');
if (!Environment::isTesting()) {
sleep($wait_for);
}
}
if (!$until_complete) {
$iterate = false;
} else {
$iterate = !empty($r);
}
}
fclose($file_handle);
$this->di['logger']->info('Unlocked queue: ' . $q->id);
unlink($lock_file);
$this->di['logger']->info(sprintf('Finished executing queue %s', $q->name));
return true;
}
private function _execute($q, $max, $interval)
{
$lsql = 'UPDATE queue_message SET log = :log, updated_at = :u WHERE id = :id;';
$dsql = 'DELETE FROM queue_message WHERE id = :id;';
$mod = $this->di['mod']($q->module);
$service = $mod->getService();
$msgs = $this->receiveQueueMessages($q->id, $max, $interval);
$result = [];
foreach ($msgs as $msg) {
try {
$this->di['logger']->info(sprintf('Executing %s queue message #%s with handler %s(%s)', $q->name, $msg['id'], $service::class . ':' . $msg['handler'], $msg['json']));
call_user_func([$service, $msg['handler']], $msg['params']);
$this->di['db']->exec($dsql, ['id' => $msg['id']]);
$result[$msg['id']] = ['status' => 'executed', 'error' => null];
} catch (\Exception $e) {
$this->di['db']->exec($lsql, ['log' => $e->getMessage() . ' ' . $e->getCode(), 'id' => $msg['id'], 'u' => date('Y-m-d H:i:s')]);
$this->di['logger']->info(sprintf('Error executing queue %s message #%s %s', $q->name, $msg['id'], $e->getMessage()));
$result[$msg['id']] = ['status' => 'fail', 'error' => $e->getMessage()];
}
}
return $result;
}
private function _getQueue($data)
{
$required = [
'queue' => 'Queue name not provided',
];
$this->di['validator']->checkRequiredParamsForArray($required, $data);
$q = $this->di['db']->findOne('queue', 'name = :name', ['name' => $data['queue']]);
if (!$q) {
throw new \Exception('Queue not found');
}
return $q;
}
/**
* Select unselected messages from queue.
*
* @param int $max
* @param int $timeout
*
* @return array
*/
private function receiveQueueMessages($qid, $max, $timeout)
{
// start transaction handling
if ($max < 0) {
return [];
}
$qid = (int) $qid;
$max = (int) $max;
$msgs = [];
$microtime = microtime(true); // cache microtime
$db = $this->di['pdo'];
$sql = "SELECT id, handler, body
FROM queue_message
WHERE queue_id = $qid
AND (handle IS NULL OR timeout+" . (int) $timeout . ' < ' . (int) $microtime . ")
AND (execute_at IS NULL OR UNIX_TIMESTAMP(execute_at) > UNIX_TIMESTAMP() )
LIMIT $max";
$sql2 = 'UPDATE queue_message
SET
handle = :handle,
timeout = :timeout
WHERE
id = :id
AND
(handle IS NULL OR timeout+' . (int) $timeout . ' < ' . (int) $microtime . ')';
$stmt1 = $db->prepare($sql);
$stmt1->execute();
foreach ($stmt1->fetchAll() as $data) {
$stmt = $db->prepare($sql2);
$stmt->bindValue('handle', hash('sha256', random_bytes(23)), \PDO::PARAM_STR);
$stmt->bindValue('id', $data['id'], \PDO::PARAM_INT);
$stmt->bindValue('timeout', $microtime);
if ($stmt->execute()) {
$msgs[] = [
'id' => $data['id'],
'handler' => $data['handler'],
'json' => base64_decode($data['body']),
'params' => json_decode(base64_decode($data['body']), 1),
];
}
}
return $msgs;
}
}
-136
View File
@@ -1,136 +0,0 @@
<?php
/**
* Copyright 2022-2023 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Queue;
class Service implements \FOSSBilling\InjectionAwareInterface
{
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function uninstall()
{
$this->di['db']->exec('DROP TABLE queue;');
$this->di['db']->exec('DROP TABLE queue_message;');
}
public function install()
{
$sql = '
CREATE TABLE IF NOT EXISTS `queue` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`module` varchar(255) DEFAULT NULL,
`timeout` bigint(20) DEFAULT NULL,
`iteration` int(10) DEFAULT NULL,
`created_at` varchar(35) DEFAULT NULL,
`updated_at` varchar(35) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
';
$this->di['db']->exec($sql);
$sql = '
CREATE TABLE IF NOT EXISTS `queue_message` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`queue_id` bigint(20) DEFAULT NULL,
`handle` char(32) DEFAULT NULL,
`handler` varchar(255) DEFAULT NULL,
`body` longblob,
`hash` char(32) DEFAULT NULL,
`timeout` double(18,2) DEFAULT NULL,
`log` text,
`execute_at` varchar(35) DEFAULT NULL,
`created_at` varchar(35) DEFAULT NULL,
`updated_at` varchar(35) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `queue_id_idx` (`queue_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
';
$this->di['db']->exec($sql);
$columns = $this->di['db']->getColumns('queue');
if (!array_key_exists('module', $columns)) {
$this->di['db']->exec('ALTER TABLE `queue` ADD `module` VARCHAR( 255 ) NULL AFTER `name`;');
}
if (!array_key_exists('iteration', $columns)) {
$this->di['db']->exec('ALTER TABLE `queue` ADD `iteration` VARCHAR( 255 ) NULL AFTER `timeout`;');
}
$columns = $this->di['db']->getColumns('queue_message');
if (!array_key_exists('handler', $columns)) {
$this->di['db']->exec('ALTER TABLE `queue_message` ADD `handler` VARCHAR( 255 ) NULL AFTER `handle`;');
}
if (!array_key_exists('execute_at', $columns)) {
$this->di['db']->exec('ALTER TABLE `queue_message` ADD `execute_at` VARCHAR( 255 ) NULL AFTER `log`;');
}
}
public function getSearchQuery($data)
{
$sql = 'SELECT *
FROM queue
WHERE 1 ';
$params = [];
$search = $data['search'] ?? null;
$name = $data['name'] ?? null;
$mod = $data['mod'] ?? null;
if ($mod) {
$sql .= ' AND mod = :mod ';
$params['mod'] = $mod;
}
if ($name) {
$sql .= ' AND name = :name ';
$params['name'] = $name;
}
if ($search) {
$sql .= ' AND (name LIKE :search)';
$params['search'] = '%' . $search . '%';
}
$sql .= ' ORDER BY id DESC';
return [$sql, $params];
}
public function toApiArray($row)
{
if ($row instanceof \RedBeanPHP\OODBBean) {
$row = $row->export();
}
$sql = 'SELECT COUNT(id) FROM queue_message WHERE queue_id = :id GROUP BY queue_id';
$count = $this->di['db']->getCell($sql, ['id' => $row['id']]);
$row['messages_count'] = $count ?: 0;
return $row;
}
public static function dummy($params)
{
throw new \Exception('Received params: ' . var_export($params, 1));
}
}
@@ -1,83 +0,0 @@
{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %}
{% import 'macro_functions.html.twig' as mf %}
{% block meta_title %}{{ 'Queues'|trans }}{% endblock %}
{% set active_menu = 'system' %}
{% block breadcrumbs %}
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{{ '/'|alink }}">
<svg class="icon">
<use xlink:href="#home" />
</svg>
</a>
</li>
<li class="breadcrumb-item">
<a href="{{ 'system'|alink }}">{{ 'Settings'|trans }}</a>
</li>
<li class="breadcrumb-item active" aria-current="page">{{ 'Queues'|trans }}</li>
</ol>
{% endblock %}
{% block content %}
<div class="card">
<div class="card-header">
<h3 class="card-title">{{ 'Queues'|trans }}</h3>
</div>
{% include 'partial_search.html.twig' %}
<div class="table-responsive">
<table class="table card-table table-vcenter table-striped text-nowrap">
<thead>
<tr>
<th>{{ 'Name'|trans }}</th>
<th>{{ 'Extension'|trans }}</th>
<th class="text-center">{{ 'Messages'|trans }}</th>
<th>{{ 'Created'|trans }}</th>
<th class="w-1"></th>
</tr>
</thead>
<tbody>
{% set queues = admin.queue_get_list({ "per_page": 100, "page": request.page }|merge(request)) %}
{% for i, queue in queues.list %}
<tr>
<td>{{ queue.name }}</td>
<td>{{ queue.mod }}</td>
<td class="text-center">{{ queue.messages_count }}</td>
<td>{{ queue.created_at|format_date }}</td>
<td class="actions">
<a class="btn btn-icon api-link"
href="{{ 'api/admin/queue/execute'|link({ 'queue': queue.name, 'CSRFToken': CSRFToken }) }}"
data-api-confirm="{{ 'Are you sure?'|trans }}"
data-api-confirm-btn="{{ 'Execute'|trans }}"
data-api-reload="1"
data-bs-toggle="tooltip" data-bs-title="{{ 'Execute'|trans }}">
<svg class="icon">
<use xlink:href="#cog-play" />
</svg>
</a>
{# <a class="btn btn-icon api-link"
href="{{ 'api/admin/queue/queue_delete'|link({ 'id': queue.name, 'CSRFToken': CSRFToken }) }}"
data-api-type="danger"
data-api-confirm-btn="{{ 'Delete'|trans }}"
data-api-confirm="{{ 'Are you sure?'|trans }}"
data-api-reload="1"
data-bs-toggle="tooltip" data-bs-title="{{ 'Delete'|trans }}">
<svg class="icon">
<use xlink:href="#delete" />
</svg>
</a> #}
</td>
</tr>
{% else %}
<tr>
<td class="text-muted" colspan="5">{{ 'The list is empty'|trans }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24"><path d="M5 6C3.9 6 3 6.9 3 8S3.9 10 5 10 7 9.11 7 8 6.11 6 5 6M12 4C10.9 4 10 4.89 10 6S10.9 8 12 8 14 7.11 14 6 13.11 4 12 4M19 2C17.9 2 17 2.9 17 4S17.9 6 19 6 21 5.11 21 4 20.11 2 19 2M3.5 11C2.67 11 2 11.67 2 12.5V17H3V22H7V17H8V12.5C8 11.67 7.33 11 6.5 11H3.5M10.5 9C9.67 9 9 9.67 9 10.5V15H10V20H14V15H15V10.5C15 9.67 14.33 9 13.5 9H10.5M17.5 7C16.67 7 16 7.67 16 8.5V13H17V18H21V13H22V8.5C22 7.67 21.33 7 20.5 7H17.5Z"/></svg>

Before

Width:  |  Height:  |  Size: 514 B

-12
View File
@@ -1,12 +0,0 @@
{
"id": "queue",
"type": "mod",
"name": "Queue Manager",
"description": "Execute long running tasks in queue",
"icon_url": "icon.svg",
"homepage_url": "https://github.com/FOSSBilling",
"author": "FOSSBilling",
"author_url": "http://extensions.fossbilling.org/",
"license": "https://github.com/FOSSBilling/FOSSBilling/blob/main/LICENSE",
"version": "1.0.0"
}
@@ -1,77 +0,0 @@
<?php
/**
* @group Core
*/
class Box_Mod_Queue_Api_AdminTest extends BBModTestCase
{
protected $_mod = 'queue';
protected $_initialSeedFile = 'mod_queue.xml';
public function testQueue()
{
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit', 'mod'=>'queue', 'handler'=>'dummy', 'params'=>'value'));
$this->assertIsInt($int);
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit', 'mod'=>'queue', 'handler'=>'dummy', 'params'=>'value2'));
$this->assertIsInt($int);
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit2', 'mod'=>'queue', 'handler'=>'dummy', 'params'=>array('value2', 'lll'=>'ss')));
$this->assertIsInt($int);
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit2', 'mod'=>'queue', 'handler'=>'dummy', 'params'=>array('value2')));
$this->assertIsInt($int);
$bool = $this->api_admin->queue_message_delete(array('id'=>$int));
$this->assertTrue($bool);
$array = $this->api_admin->queue_get(array('queue'=>'phpunit2'));
$this->assertIsArray($array);
$this->assertTrue(isset($array['messages_count']));
$this->assertEquals(1, $array['messages_count']);
$array = $this->api_admin->queue_get_list();
$this->assertIsArray($array);
$this->assertEquals(2, $array['total']);
$bool = $this->api_admin->queue_execute(array('queue'=>'phpunit'));
$this->assertTrue($bool);
}
public function testLater()
{
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit', 'mod'=>'queue', 'handler'=>'dummy', 'params'=>'right now'));
$this->assertIsInt($int);
$int = $this->api_admin->queue_message_add(array('queue'=>'phpunit', 'mod'=>'queue', 'handler'=>'dummy', 'execute_at'=>date('Y-m-d H:i:s', strtotime('+10 seconds')), 'params'=>'later'));
$this->assertIsInt($int);
$bool = $this->api_admin->queue_execute(array('queue'=>'phpunit'));
$this->assertTrue($bool);
}
public function testQueueGetList()
{
$int = $this->api_admin->queue_message_add(array('queue' => 'phpunit', 'mod' => 'queue', 'handler' => 'dummy', 'params' => 'right now'));
$this->assertIsInt($int);
$array = $this->api_admin->queue_get_list();
$this->assertIsArray($array);
$this->assertEquals(1, $array['total']);
$this->assertArrayHasKey('list', $array);
$list = $array['list'];
$this->assertIsArray($list);
$item = $list[0];
$this->assertArrayHasKey('id', $item);
$this->assertArrayHasKey('name', $item);
$this->assertArrayHasKey('module', $item);
$this->assertArrayHasKey('timeout', $item);
$this->assertArrayHasKey('iteration', $item);
$this->assertArrayHasKey('timeout', $item);
$this->assertArrayHasKey('created_at', $item);
$this->assertArrayHasKey('updated_at', $item);
$this->assertArrayHasKey('messages_count', $item);
}
}