diff --git a/lib/Cron/Daemon.php b/lib/Cron/Daemon.php index 0f67cbda5a..b30c42dcf0 100644 --- a/lib/Cron/Daemon.php +++ b/lib/Cron/Daemon.php @@ -26,7 +26,7 @@ class Daemon { $errors = []; foreach ($this->getWorkers() as $worker) { try { - $worker->process(); + $worker->process($this->timer); } catch (\Exception $e) { $worker_class_name_parts = explode('\\', get_class($worker)); $errors[] = [ @@ -45,21 +45,21 @@ class Daemon { } private function getWorkers() { - yield $this->workers_factory->createMigrationWorker($this->timer); - yield $this->workers_factory->createStatsNotificationsWorker($this->timer); - yield $this->workers_factory->createScheduleWorker($this->timer); - yield $this->workers_factory->createQueueWorker($this->timer); - yield $this->workers_factory->createSendingServiceKeyCheckWorker($this->timer); - yield $this->workers_factory->createPremiumKeyCheckWorker($this->timer); - yield $this->workers_factory->createBounceWorker($this->timer); - yield $this->workers_factory->createExportFilesCleanupWorker($this->timer); - yield $this->workers_factory->createBeamerkWorker($this->timer); - yield $this->workers_factory->createInactiveSubscribersWorker($this->timer); - yield $this->workers_factory->createUnsubscribeTokensWorker($this->timer); - yield $this->workers_factory->createWooCommerceSyncWorker($this->timer); - yield $this->workers_factory->createAuthorizedSendingEmailsCheckWorker($this->timer); - yield $this->workers_factory->createWooCommercePastOrdersWorker($this->timer); - yield $this->workers_factory->createStatsNotificationsWorkerForAutomatedEmails($this->timer); - yield $this->workers_factory->createSubscriberLinkTokensWorker($this->timer); + yield $this->workers_factory->createMigrationWorker(); + yield $this->workers_factory->createStatsNotificationsWorker(); + yield $this->workers_factory->createScheduleWorker(); + yield $this->workers_factory->createQueueWorker(); + yield $this->workers_factory->createSendingServiceKeyCheckWorker(); + yield $this->workers_factory->createPremiumKeyCheckWorker(); + yield $this->workers_factory->createBounceWorker(); + yield $this->workers_factory->createExportFilesCleanupWorker(); + yield $this->workers_factory->createBeamerkWorker(); + yield $this->workers_factory->createInactiveSubscribersWorker(); + yield $this->workers_factory->createUnsubscribeTokensWorker(); + yield $this->workers_factory->createWooCommerceSyncWorker(); + yield $this->workers_factory->createAuthorizedSendingEmailsCheckWorker(); + yield $this->workers_factory->createWooCommercePastOrdersWorker(); + yield $this->workers_factory->createStatsNotificationsWorkerForAutomatedEmails(); + yield $this->workers_factory->createSubscriberLinkTokensWorker(); } } diff --git a/lib/Cron/Workers/AuthorizedSendingEmailsCheck.php b/lib/Cron/Workers/AuthorizedSendingEmailsCheck.php index 737c60c3b2..7be82b8afc 100644 --- a/lib/Cron/Workers/AuthorizedSendingEmailsCheck.php +++ b/lib/Cron/Workers/AuthorizedSendingEmailsCheck.php @@ -13,16 +13,16 @@ class AuthorizedSendingEmailsCheck extends SimpleWorker { /** @var AuthorizedEmailsController */ private $authorized_emails_controller; - function __construct(AuthorizedEmailsController $authorized_emails_controller, $timer = false) { + function __construct(AuthorizedEmailsController $authorized_emails_controller) { $this->authorized_emails_controller = $authorized_emails_controller; - parent::__construct($timer); + parent::__construct(); } function checkProcessingRequirements() { return Bridge::isMPSendingServiceEnabled(); } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $this->authorized_emails_controller->checkAuthorizedEmailAddresses(); return true; } diff --git a/lib/Cron/Workers/Beamer.php b/lib/Cron/Workers/Beamer.php index 2de8a55b2e..f84f3f6334 100644 --- a/lib/Cron/Workers/Beamer.php +++ b/lib/Cron/Workers/Beamer.php @@ -18,13 +18,13 @@ class Beamer extends SimpleWorker { /** @var WPFunctions */ private $wp; - function __construct(SettingsController $settings, WPFunctions $wp, $timer = false) { - parent::__construct($timer); + function __construct(SettingsController $settings, WPFunctions $wp) { + parent::__construct(); $this->settings = $settings; $this->wp = $wp; } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { return $this->setLastAnnouncementDate(); } diff --git a/lib/Cron/Workers/Bounce.php b/lib/Cron/Workers/Bounce.php index b1af7db916..7360856230 100644 --- a/lib/Cron/Workers/Bounce.php +++ b/lib/Cron/Workers/Bounce.php @@ -29,9 +29,9 @@ class Bounce extends SimpleWorker { /** @var SettingsController */ private $settings; - function __construct(SettingsController $settings, $timer = false) { + function __construct(SettingsController $settings) { $this->settings = $settings; - parent::__construct($timer); + parent::__construct(); } function init() { @@ -44,7 +44,7 @@ class Bounce extends SimpleWorker { return Bridge::isMPSendingServiceEnabled(); } - function prepareTaskStrategy(ScheduledTask $task) { + function prepareTaskStrategy(ScheduledTask $task, $timer) { BounceTask::prepareSubscribers($task); if (!ScheduledTaskSubscriber::getUnprocessedCount($task->id)) { @@ -54,7 +54,7 @@ class Bounce extends SimpleWorker { return true; } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $subscriber_batches = new BatchIterator($task->id, self::BATCH_SIZE); if (count($subscriber_batches) === 0) { @@ -66,7 +66,7 @@ class Bounce extends SimpleWorker { foreach ($subscriber_batches as $subscribers_to_process_ids) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); $subscriber_emails = Subscriber::select('email') ->whereIn('id', $subscribers_to_process_ids) diff --git a/lib/Cron/Workers/ExportFilesCleanup.php b/lib/Cron/Workers/ExportFilesCleanup.php index eea4e24c84..d72331c823 100644 --- a/lib/Cron/Workers/ExportFilesCleanup.php +++ b/lib/Cron/Workers/ExportFilesCleanup.php @@ -10,7 +10,7 @@ class ExportFilesCleanup extends SimpleWorker { const TASK_TYPE = 'export_files_cleanup'; const DELETE_FILES_AFTER_X_DAYS = 1; - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $iterator = new \GlobIterator(Export::getExportPath() . '/' . Export::getFilePrefix() . '*.*'); foreach ($iterator as $file) { if (is_string($file)) { diff --git a/lib/Cron/Workers/InactiveSubscribers.php b/lib/Cron/Workers/InactiveSubscribers.php index 36d966243d..f649bdf764 100644 --- a/lib/Cron/Workers/InactiveSubscribers.php +++ b/lib/Cron/Workers/InactiveSubscribers.php @@ -21,16 +21,15 @@ class InactiveSubscribers extends SimpleWorker { function __construct( InactiveSubscribersController $inactive_subscribers_controller, - SettingsController $settings, - $timer = false + SettingsController $settings ) { $this->inactive_subscribers_controller = $inactive_subscribers_controller; $this->settings = $settings; - parent::__construct($timer); + parent::__construct(); } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $tracking_enabled = (bool)$this->settings->get('tracking.enabled'); if (!$tracking_enabled) { $this->schedule(); @@ -55,10 +54,10 @@ class InactiveSubscribers extends SimpleWorker { $last_subscriber_id += self::BATCH_SIZE; $task->meta = ['last_subscriber_id' => $last_subscriber_id]; $task->save(); - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); }; while ($this->inactive_subscribers_controller->markActiveSubscribers($days_to_inactive, self::BATCH_SIZE) === self::BATCH_SIZE) { - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); }; $this->schedule(); return true; diff --git a/lib/Cron/Workers/KeyCheck/KeyCheckWorker.php b/lib/Cron/Workers/KeyCheck/KeyCheckWorker.php index 51d5534b10..82d88ea4ac 100644 --- a/lib/Cron/Workers/KeyCheck/KeyCheckWorker.php +++ b/lib/Cron/Workers/KeyCheck/KeyCheckWorker.php @@ -15,7 +15,7 @@ abstract class KeyCheckWorker extends SimpleWorker { } } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { try { $result = $this->checkKey(); } catch (\Exception $e) { diff --git a/lib/Cron/Workers/KeyCheck/PremiumKeyCheck.php b/lib/Cron/Workers/KeyCheck/PremiumKeyCheck.php index 74dd948e0f..4d1441a323 100644 --- a/lib/Cron/Workers/KeyCheck/PremiumKeyCheck.php +++ b/lib/Cron/Workers/KeyCheck/PremiumKeyCheck.php @@ -11,9 +11,9 @@ class PremiumKeyCheck extends KeyCheckWorker { /** @var SettingsController */ private $settings; - function __construct(SettingsController $settings, $timer = false) { + function __construct(SettingsController $settings) { $this->settings = $settings; - parent::__construct($timer); + parent::__construct(); } diff --git a/lib/Cron/Workers/KeyCheck/SendingServiceKeyCheck.php b/lib/Cron/Workers/KeyCheck/SendingServiceKeyCheck.php index f3c8448195..68e2bd7f57 100644 --- a/lib/Cron/Workers/KeyCheck/SendingServiceKeyCheck.php +++ b/lib/Cron/Workers/KeyCheck/SendingServiceKeyCheck.php @@ -12,9 +12,9 @@ class SendingServiceKeyCheck extends KeyCheckWorker { /** @var SettingsController */ private $settings; - function __construct(SettingsController $settings, $timer = false) { + function __construct(SettingsController $settings) { $this->settings = $settings; - parent::__construct($timer); + parent::__construct(); } function checkProcessingRequirements() { diff --git a/lib/Cron/Workers/Scheduler.php b/lib/Cron/Workers/Scheduler.php index 9082a6d380..4849e3150c 100644 --- a/lib/Cron/Workers/Scheduler.php +++ b/lib/Cron/Workers/Scheduler.php @@ -20,8 +20,6 @@ use MailPoetVendor\Monolog\Logger; class Scheduler { const TASK_BATCH_SIZE = 5; - public $timer; - /** @var SubscribersFinder */ private $subscribers_finder; @@ -34,18 +32,19 @@ class Scheduler { function __construct( SubscribersFinder $subscribers_finder, LoggerFactory $logger_factory, - CronHelper $cron_helper, - $timer = false + CronHelper $cron_helper ) { - $this->timer = ($timer) ? $timer : microtime(true); - // abort if execution limit is reached $this->cron_helper = $cron_helper; - $this->cron_helper->enforceExecutionLimit($this->timer); $this->subscribers_finder = $subscribers_finder; $this->logger_factory = $logger_factory; } - function process() { + function process($timer = false) { + $timer = $timer ?: microtime(true); + + // abort if execution limit is reached + $this->cron_helper->enforceExecutionLimit($timer); + $scheduled_queues = self::getScheduledQueues(); if (!count($scheduled_queues)) return false; $this->updateTasks($scheduled_queues); @@ -64,7 +63,7 @@ class Scheduler { } elseif ($newsletter->type === Newsletter::TYPE_AUTOMATIC) { $this->processScheduledAutomaticEmail($newsletter, $queue); } - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); } } diff --git a/lib/Cron/Workers/SendingQueue/Migration.php b/lib/Cron/Workers/SendingQueue/Migration.php index 0d4f734d73..1cc4113935 100644 --- a/lib/Cron/Workers/SendingQueue/Migration.php +++ b/lib/Cron/Workers/SendingQueue/Migration.php @@ -21,7 +21,7 @@ class Migration extends SimpleWorker { return empty($completed_tasks); } - function prepareTaskStrategy(ScheduledTask $task) { + function prepareTaskStrategy(ScheduledTask $task, $timer) { $unmigrated_columns = $this->checkUnmigratedColumnsExist(); $unmigrated_queues_count = 0; $unmigrated_queue_subscribers = []; @@ -73,9 +73,9 @@ class Migration extends SimpleWorker { } } - function processTaskStrategy(ScheduledTask $task) { - $this->migrateSendingQueues(); - $this->migrateSubscribers(); + function processTaskStrategy(ScheduledTask $task, $timer) { + $this->migrateSendingQueues($timer); + $this->migrateSubscribers($timer); $this->resumeSending(); return true; } @@ -108,7 +108,7 @@ class Migration extends SimpleWorker { /* * Migrate all sending queues without converting subscriber data */ - function migrateSendingQueues() { + function migrateSendingQueues($timer) { global $wpdb; $queues = $this->getUnmigratedQueues() @@ -128,7 +128,7 @@ class Migration extends SimpleWorker { if (!empty($queues)) { foreach (array_chunk($queues, self::BATCH_SIZE) as $queue_batch) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); foreach ($queue_batch as $queue) { // create a new scheduled task of type "sending" @@ -158,7 +158,7 @@ class Migration extends SimpleWorker { /* * Migrate subscribers for in-progress sending tasks from the `subscribers` field to a separate table */ - function migrateSubscribers() { + function migrateSubscribers($timer) { global $wpdb; // find in-progress queues that have serialized subscribers @@ -177,16 +177,16 @@ class Migration extends SimpleWorker { if (!empty($task_ids)) { foreach ($task_ids as $task_id) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); - $this->migrateTaskSubscribers($task_id); + $this->migrateTaskSubscribers($task_id, $timer); } } return true; } - function migrateTaskSubscribers($task_id) { + function migrateTaskSubscribers($task_id, $timer) { global $wpdb; $migrated_unprocessed_count = ScheduledTaskSubscriber::getUnprocessedCount($task_id); @@ -212,7 +212,7 @@ class Migration extends SimpleWorker { $subscribers_to_migrate = array_slice($subscribers['to_process'], $migrated_unprocessed_count); foreach ($subscribers_to_migrate as $sub_id) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); ScheduledTaskSubscriber::createOrUpdate([ 'task_id' => $task_id, @@ -226,7 +226,7 @@ class Migration extends SimpleWorker { $subscribers_to_migrate = array_slice($subscribers['processed'], $migrated_processed_count); foreach ($subscribers_to_migrate as $sub_id) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); ScheduledTaskSubscriber::createOrUpdate([ 'task_id' => $task_id, diff --git a/lib/Cron/Workers/SendingQueue/SendingQueue.php b/lib/Cron/Workers/SendingQueue/SendingQueue.php index 60283f2e7f..e2e82cb9ce 100644 --- a/lib/Cron/Workers/SendingQueue/SendingQueue.php +++ b/lib/Cron/Workers/SendingQueue/SendingQueue.php @@ -25,7 +25,6 @@ use function MailPoet\Util\array_column; class SendingQueue { public $mailer_task; public $newsletter_task; - public $timer; public $batch_size; const BATCH_SIZE = 20; const TASK_BATCH_SIZE = 5; @@ -54,7 +53,6 @@ class SendingQueue { LoggerFactory $logger_factory, NewslettersRepository $newsletters_repository, CronHelper $cron_helper, - $timer = false, $mailer_task = false, $newsletter_task = false ) { @@ -62,7 +60,6 @@ class SendingQueue { $this->stats_notifications_scheduler = $stats_notifications_scheduler; $this->mailer_task = ($mailer_task) ? $mailer_task : new MailerTask(); $this->newsletter_task = ($newsletter_task) ? $newsletter_task : new NewsletterTask(); - $this->timer = ($timer) ? $timer : microtime(true); $this->mailerMetaInfo = new MetaInfo; $wp = new WPFunctions; $this->batch_size = $wp->applyFilters('mailpoet_cron_worker_sending_queue_batch_size', self::BATCH_SIZE); @@ -71,8 +68,9 @@ class SendingQueue { $this->cron_helper = $cron_helper; } - function process() { - $this->enforceSendingAndExecutionLimits(); + function process($timer = false) { + $timer = $timer ?: microtime(true); + $this->enforceSendingAndExecutionLimits($timer); foreach (self::getRunningQueues() as $queue) { if (!$queue instanceof SendingTask) continue; ScheduledTaskModel::touchAllByIds([$queue->task_id]); @@ -147,7 +145,8 @@ class SendingQueue { $queue = $this->processQueue( $queue, $_newsletter, - $found_subscribers + $found_subscribers, + $timer ); $this->logger_factory->getLogger(LoggerFactory::TOPIC_NEWSLETTERS)->addInfo( 'after queue chunk processing', @@ -161,12 +160,12 @@ class SendingQueue { $this->newsletter_task->markNewsletterAsSent($newsletter, $queue); $this->stats_notifications_scheduler->schedule($this->newsletters_repository->findOneById($newsletter->id)); } - $this->enforceSendingAndExecutionLimits(); + $this->enforceSendingAndExecutionLimits($timer); } } } - function processQueue($queue, $newsletter, $subscribers) { + function processQueue($queue, $newsletter, $subscribers, $timer) { // determine if processing is done in bulk or individually $processing_method = $this->mailer_task->getProcessingMethod(); $prepared_newsletters = []; @@ -204,6 +203,7 @@ class SendingQueue { $prepared_newsletters[0], $prepared_subscribers[0], $statistics[0], + $timer, ['unsubscribe_url' => $unsubscribe_urls[0], 'meta' => $metas[0]] ); $prepared_newsletters = []; @@ -220,6 +220,7 @@ class SendingQueue { $prepared_newsletters, $prepared_subscribers, $statistics, + $timer, ['unsubscribe_url' => $unsubscribe_urls, 'meta' => $metas] ); } @@ -228,7 +229,7 @@ class SendingQueue { function sendNewsletter( SendingTask $sending_task, $prepared_subscriber_id, $prepared_newsletter, - $prepared_subscriber, $statistics, $extra_params = [] + $prepared_subscriber, $statistics, $timer, $extra_params = [] ) { // send newsletter $send_result = $this->mailer_task->send( @@ -241,13 +242,14 @@ class SendingQueue { $send_result, [$prepared_subscriber], [$prepared_subscriber_id], - [$statistics] + [$statistics], + $timer ); } function sendNewsletters( SendingTask $sending_task, $prepared_subscribers_ids, $prepared_newsletters, - $prepared_subscribers, $statistics, $extra_params = [] + $prepared_subscribers, $statistics, $timer, $extra_params = [] ) { // send newsletters $send_result = $this->mailer_task->sendBulk( @@ -260,7 +262,8 @@ class SendingQueue { $send_result, $prepared_subscribers, $prepared_subscribers_ids, - $statistics + $statistics, + $timer ); } @@ -269,7 +272,8 @@ class SendingQueue { $send_result, array $prepared_subscribers, array $prepared_subscribers_ids, - array $statistics + array $statistics, + $timer ) { // log error message and schedule retry/pause sending if ($send_result['response'] === false) { @@ -292,14 +296,14 @@ class SendingQueue { $this->mailer_task->updateSentCount(); // enforce execution limits if queue is still being processed if ($sending_task->status !== ScheduledTaskModel::STATUS_COMPLETED) { - $this->enforceSendingAndExecutionLimits(); + $this->enforceSendingAndExecutionLimits($timer); } return $sending_task; } - function enforceSendingAndExecutionLimits() { + function enforceSendingAndExecutionLimits($timer) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); // abort if sending limit has been reached MailerLog::enforceExecutionRequirements(); } diff --git a/lib/Cron/Workers/SimpleWorker.php b/lib/Cron/Workers/SimpleWorker.php index 706cdb8283..043fd540d9 100644 --- a/lib/Cron/Workers/SimpleWorker.php +++ b/lib/Cron/Workers/SimpleWorker.php @@ -10,7 +10,6 @@ use MailPoet\Models\ScheduledTask; use MailPoet\WP\Functions as WPFunctions; abstract class SimpleWorker { - public $timer; private $wp; const TASK_TYPE = null; const TASK_BATCH_SIZE = 5; @@ -26,15 +25,13 @@ abstract class SimpleWorker { /** @var CronWorkerScheduler */ protected $cron_worker_scheduler; - function __construct($timer = false) { + function __construct() { if (static::TASK_TYPE === null) { throw new \Exception('Constant TASK_TYPE is not defined on subclass ' . get_class($this)); } - $this->timer = ($timer) ? $timer : microtime(true); - // abort if execution limit is reached - $this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class); - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->wp = new WPFunctions(); + $this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class); $this->cron_worker_scheduler = ContainerWrapper::getInstance()->get(CronWorkerScheduler::class); } @@ -45,7 +42,12 @@ abstract class SimpleWorker { function init() { } - function process() { + function process($timer = false) { + $timer = $timer ?: microtime(true); + + // abort if execution limit is reached + $this->cron_helper->enforceExecutionLimit($timer); + if (!$this->checkProcessingRequirements()) { return false; } @@ -65,10 +67,10 @@ abstract class SimpleWorker { $task = null; try { foreach ($scheduled_tasks as $i => $task) { - $this->prepareTask($task); + $this->prepareTask($task, $timer); } foreach ($running_tasks as $i => $task) { - $this->processTask($task); + $this->processTask($task, $timer); } } catch (\Exception $e) { if ($task && $e->getCode() !== CronHelper::DAEMON_EXECUTION_LIMIT_REACHED) { @@ -84,20 +86,20 @@ abstract class SimpleWorker { $this->cron_worker_scheduler->schedule(static::TASK_TYPE, static::getNextRunDate()); } - function prepareTask(ScheduledTask $task) { + function prepareTask(ScheduledTask $task, $timer) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); - $prepare_completed = $this->prepareTaskStrategy($task); + $prepare_completed = $this->prepareTaskStrategy($task, $timer); if ($prepare_completed) { $task->status = null; $task->save(); } } - function processTask(ScheduledTask $task) { + function processTask(ScheduledTask $task, $timer) { // abort if execution limit is reached - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); if (!static::SUPPORT_MULTIPLE_INSTANCES) { if ($this->rescheduleOutdated($task)) { @@ -111,7 +113,7 @@ abstract class SimpleWorker { $this->startProgress($task); try { - $completed = $this->processTaskStrategy($task); + $completed = $this->processTaskStrategy($task, $timer); } catch (\Exception $e) { $this->stopProgress($task); throw $e; @@ -126,11 +128,11 @@ abstract class SimpleWorker { return (bool)$completed; } - function prepareTaskStrategy(ScheduledTask $task) { + function prepareTaskStrategy(ScheduledTask $task, $timer) { return true; } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { return true; } diff --git a/lib/Cron/Workers/StatsNotifications/AutomatedEmails.php b/lib/Cron/Workers/StatsNotifications/AutomatedEmails.php index 409d7710fa..4953254b84 100644 --- a/lib/Cron/Workers/StatsNotifications/AutomatedEmails.php +++ b/lib/Cron/Workers/StatsNotifications/AutomatedEmails.php @@ -31,9 +31,6 @@ class AutomatedEmails extends SimpleWorker { /** @var MetaInfo */ private $mailerMetaInfo; - /** @var float */ - public $timer; - /** @var NewslettersRepository */ private $repository; @@ -46,15 +43,13 @@ class AutomatedEmails extends SimpleWorker { SettingsController $settings, NewslettersRepository $repository, NewsletterStatisticsRepository $newsletter_statistics_repository, - MetaInfo $mailerMetaInfo, - $timer = false + MetaInfo $mailerMetaInfo ) { - parent::__construct($timer); + parent::__construct(); $this->mailer = $mailer; $this->settings = $settings; $this->renderer = $renderer; $this->mailerMetaInfo = $mailerMetaInfo; - $this->timer = $timer ?: microtime(true); $this->repository = $repository; $this->newsletter_statistics_repository = $newsletter_statistics_repository; } @@ -79,7 +74,7 @@ class AutomatedEmails extends SimpleWorker { return (bool)$settings['automated']; } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { try { $settings = $this->settings->get(Worker::SETTINGS_KEY); $newsletters = $this->getNewsletters(); diff --git a/lib/Cron/Workers/StatsNotifications/Worker.php b/lib/Cron/Workers/StatsNotifications/Worker.php index 536e423d64..493857e4e0 100644 --- a/lib/Cron/Workers/StatsNotifications/Worker.php +++ b/lib/Cron/Workers/StatsNotifications/Worker.php @@ -24,9 +24,6 @@ class Worker { const TASK_TYPE = 'stats_notification'; const SETTINGS_KEY = 'stats_notifications'; - /** @var float */ - public $timer; - /** @var Renderer */ private $renderer; @@ -63,10 +60,8 @@ class Worker { StatsNotificationsRepository $repository, NewsletterLinkRepository $newsletter_link_repository, NewsletterStatisticsRepository $newsletter_statistics_repository, - EntityManager $entity_manager, - $timer = false + EntityManager $entity_manager ) { - $this->timer = $timer ?: microtime(true); $this->renderer = $renderer; $this->mailer = $mailer; $this->settings = $settings; @@ -79,7 +74,8 @@ class Worker { } /** @throws \Exception */ - function process() { + function process($timer = false) { + $timer = $timer ?: microtime(true); $settings = $this->settings->get(self::SETTINGS_KEY); foreach ($this->repository->findScheduled(Sending::RESULT_BATCH_SIZE) as $stats_notification_entity) { try { @@ -94,7 +90,7 @@ class Worker { } finally { $this->markTaskAsFinished($stats_notification_entity->getTask()); } - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); } } diff --git a/lib/Cron/Workers/SubscriberLinkTokens.php b/lib/Cron/Workers/SubscriberLinkTokens.php index 5c65fc6087..de7f854220 100644 --- a/lib/Cron/Workers/SubscriberLinkTokens.php +++ b/lib/Cron/Workers/SubscriberLinkTokens.php @@ -14,7 +14,7 @@ class SubscriberLinkTokens extends SimpleWorker { const BATCH_SIZE = 10000; const AUTOMATIC_SCHEDULING = false; - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $count = Subscriber::whereNull('link_token')->count(); if ($count) { $auth_key = defined('AUTH_KEY') ? AUTH_KEY : ''; diff --git a/lib/Cron/Workers/UnsubscribeTokens.php b/lib/Cron/Workers/UnsubscribeTokens.php index 5434702154..f621da0807 100644 --- a/lib/Cron/Workers/UnsubscribeTokens.php +++ b/lib/Cron/Workers/UnsubscribeTokens.php @@ -15,16 +15,16 @@ class UnsubscribeTokens extends SimpleWorker { const BATCH_SIZE = 1000; const AUTOMATIC_SCHEDULING = false; - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $meta = $task->getMeta(); do { - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); $subscribers_count = $this->addTokens(Subscriber::class, $meta['last_subscriber_id']); $task->meta = $meta; $task->save(); } while ($subscribers_count === self::BATCH_SIZE); do { - $this->cron_helper->enforceExecutionLimit($this->timer); + $this->cron_helper->enforceExecutionLimit($timer); $newsletters_count = $this->addTokens(Newsletter::class, $meta['last_newsletter_id']); $task->meta = $meta; $task->save(); diff --git a/lib/Cron/Workers/WooCommercePastOrders.php b/lib/Cron/Workers/WooCommercePastOrders.php index b4245202fe..a35322e3ea 100644 --- a/lib/Cron/Workers/WooCommercePastOrders.php +++ b/lib/Cron/Workers/WooCommercePastOrders.php @@ -22,19 +22,18 @@ class WooCommercePastOrders extends SimpleWorker { function __construct( WCHelper $woocommerce_helper, - WooCommercePurchases $woocommerce_purchases, - $timer = false + WooCommercePurchases $woocommerce_purchases ) { $this->woocommerce_helper = $woocommerce_helper; $this->woocommerce_purchases = $woocommerce_purchases; - parent::__construct($timer); + parent::__construct(); } function checkProcessingRequirements() { return $this->woocommerce_helper->isWooCommerceActive() && empty($this->getCompletedTasks()); // run only once } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $oldest_click = StatisticsClicks::orderByAsc('created_at')->limit(1)->findOne(); if (!$oldest_click instanceof StatisticsClicks) { return true; diff --git a/lib/Cron/Workers/WooCommerceSync.php b/lib/Cron/Workers/WooCommerceSync.php index a63345904e..8ce010bfb2 100644 --- a/lib/Cron/Workers/WooCommerceSync.php +++ b/lib/Cron/Workers/WooCommerceSync.php @@ -18,17 +18,17 @@ class WooCommerceSync extends SimpleWorker { /** @var WooCommerceHelper */ private $woocommerce_helper; - function __construct(WooCommerceSegment $woocommerce_segment, WooCommerceHelper $woocommerce_helper, $timer = false) { + function __construct(WooCommerceSegment $woocommerce_segment, WooCommerceHelper $woocommerce_helper) { $this->woocommerce_segment = $woocommerce_segment; $this->woocommerce_helper = $woocommerce_helper; - parent::__construct($timer); + parent::__construct(); } function checkProcessingRequirements() { return $this->woocommerce_helper->isWooCommerceActive(); } - function processTaskStrategy(ScheduledTask $task) { + function processTaskStrategy(ScheduledTask $task, $timer) { $this->woocommerce_segment->synchronizeCustomers(); return true; } diff --git a/lib/Cron/Workers/WorkersFactory.php b/lib/Cron/Workers/WorkersFactory.php index c03068ccaf..7f12e64b5d 100644 --- a/lib/Cron/Workers/WorkersFactory.php +++ b/lib/Cron/Workers/WorkersFactory.php @@ -136,24 +136,23 @@ class WorkersFactory { } /** @return SchedulerWorker */ - function createScheduleWorker($timer) { - return new SchedulerWorker($this->subscribers_finder, $this->logger_factory, $this->cron_helper, $timer); + function createScheduleWorker() { + return new SchedulerWorker($this->subscribers_finder, $this->logger_factory, $this->cron_helper); } /** @return SendingQueueWorker */ - function createQueueWorker($timer) { + function createQueueWorker() { return new SendingQueueWorker( $this->sending_error_handler, $this->statsNotificationsScheduler, $this->logger_factory, $this->newsletters_repository, - $this->cron_helper, - $timer + $this->cron_helper ); } /** @return StatsNotificationsWorker */ - function createStatsNotificationsWorker($timer) { + function createStatsNotificationsWorker() { return new StatsNotificationsWorker( $this->mailer, $this->renderer, @@ -163,81 +162,79 @@ class WorkersFactory { $this->stats_notifications_repository, $this->newsletter_link_repository, $this->newsletter_statistics_repository, - $this->entity_manager, - $timer + $this->entity_manager ); } /** @return StatsNotificationsWorkerForAutomatedEmails */ - function createStatsNotificationsWorkerForAutomatedEmails($timer) { + function createStatsNotificationsWorkerForAutomatedEmails() { return new StatsNotificationsWorkerForAutomatedEmails( $this->mailer, $this->renderer, $this->settings, $this->newsletters_repository, $this->newsletter_statistics_repository, - $this->mailerMetaInfo, - $timer + $this->mailerMetaInfo ); } /** @return SendingServiceKeyCheckWorker */ - function createSendingServiceKeyCheckWorker($timer) { - return new SendingServiceKeyCheckWorker($this->settings, $timer); + function createSendingServiceKeyCheckWorker() { + return new SendingServiceKeyCheckWorker($this->settings); } /** @return PremiumKeyCheckWorker */ - function createPremiumKeyCheckWorker($timer) { - return new PremiumKeyCheckWorker($this->settings, $timer); + function createPremiumKeyCheckWorker() { + return new PremiumKeyCheckWorker($this->settings); } /** @return BounceWorker */ - function createBounceWorker($timer) { - return new BounceWorker($this->settings, $timer); + function createBounceWorker() { + return new BounceWorker($this->settings); } /** @return MigrationWorker */ - function createMigrationWorker($timer) { - return new MigrationWorker($timer); + function createMigrationWorker() { + return new MigrationWorker(); } /** @return WooCommerceSyncWorker */ - function createWooCommerceSyncWorker($timer) { - return new WooCommerceSyncWorker($this->woocommerce_segment, $this->woocommerce_helper, $timer); + function createWooCommerceSyncWorker() { + return new WooCommerceSyncWorker($this->woocommerce_segment, $this->woocommerce_helper); } /** @return ExportFilesCleanup */ - function createExportFilesCleanupWorker($timer) { - return new ExportFilesCleanup($timer); + function createExportFilesCleanupWorker() { + return new ExportFilesCleanup(); } /** @return Beamer */ - function createBeamerkWorker($timer) { - return new Beamer($this->settings, WPFunctions::get(), $timer); + function createBeamerkWorker() { + return new Beamer($this->settings, WPFunctions::get()); } /** @return InactiveSubscribers */ - function createInactiveSubscribersWorker($timer) { - return new InactiveSubscribers($this->inactive_subscribers_controller, $this->settings, $timer); + function createInactiveSubscribersWorker() { + return new InactiveSubscribers($this->inactive_subscribers_controller, $this->settings); } /** @return UnsubscribeTokens */ - function createUnsubscribeTokensWorker($timer) { - return new UnsubscribeTokens($timer); + function createUnsubscribeTokensWorker() { + return new UnsubscribeTokens(); } /** @return SubscriberLinkTokens */ - function createSubscriberLinkTokensWorker($timer) { - return new SubscriberLinkTokens($timer); + function createSubscriberLinkTokensWorker() { + return new SubscriberLinkTokens(); } /** @return AuthorizedSendingEmailsCheck */ - function createAuthorizedSendingEmailsCheckWorker($timer) { - return new AuthorizedSendingEmailsCheck($this->authorized_emails_controller, $timer); + function createAuthorizedSendingEmailsCheckWorker() { + return new AuthorizedSendingEmailsCheck($this->authorized_emails_controller); } /** @return WooCommercePastOrders */ - function createWooCommercePastOrdersWorker($timer) { - return new WooCommercePastOrders($this->woocommerce_helper, $this->woocommerce_purchases, $timer); + function createWooCommercePastOrdersWorker() { + return new WooCommercePastOrders($this->woocommerce_helper, $this->woocommerce_purchases); } } diff --git a/tests/integration/Cron/Workers/AuthorizedSendingEmailsCheckTest.php b/tests/integration/Cron/Workers/AuthorizedSendingEmailsCheckTest.php index 998d17c479..b413bdb411 100644 --- a/tests/integration/Cron/Workers/AuthorizedSendingEmailsCheckTest.php +++ b/tests/integration/Cron/Workers/AuthorizedSendingEmailsCheckTest.php @@ -22,7 +22,7 @@ class AuthorizedSendingEmailsCheckTest extends \MailPoetTest { function testItRunsCheckOnBridge() { $bridge_mock = $this->makeEmpty(AuthorizedEmailsController::class, ['checkAuthorizedEmailAddresses' => Stub\Expected::once()]); $worker = new AuthorizedSendingEmailsCheck($bridge_mock); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true)); } function testItDoesNotScheduleAutomatically() { diff --git a/tests/integration/Cron/Workers/BounceTest.php b/tests/integration/Cron/Workers/BounceTest.php index 9f3bf241d7..e4600ac3ed 100644 --- a/tests/integration/Cron/Workers/BounceTest.php +++ b/tests/integration/Cron/Workers/BounceTest.php @@ -56,20 +56,20 @@ class BounceTest extends \MailPoetTest { function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenPreparingTask() { // 1st run - subscribers will be processed $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty(); // 2nd run - nothing more to process, ScheduledTaskSubscriber will be cleaned up Subscriber::deleteMany(); $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty(); } function testItPreparesTask() { $task = $this->createScheduledTask(); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->isEmpty(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect($task->status)->null(); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty(); } @@ -77,21 +77,21 @@ class BounceTest extends \MailPoetTest { function testItDeletesAllSubscribersIfThereAreNoSubscribersToProcessWhenProcessingTask() { // prepare subscribers $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->notEmpty(); // process - no subscribers found, ScheduledTaskSubscriber will be cleaned up Subscriber::deleteMany(); $task = $this->createScheduledTask(); - $this->worker->processTask($task); + $this->worker->processTask($task, microtime(true)); expect(ScheduledTaskSubscriber::where('task_id', $task->id)->findMany())->isEmpty(); } function testItProcessesTask() { $task = $this->createRunningTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(ScheduledTaskSubscriber::getUnprocessedCount($task->id))->notEmpty(); - $this->worker->processTask($task); + $this->worker->processTask($task, microtime(true)); expect(ScheduledTaskSubscriber::getProcessedCount($task->id))->notEmpty(); } diff --git a/tests/integration/Cron/Workers/ExportFilesCleanupTest.php b/tests/integration/Cron/Workers/ExportFilesCleanupTest.php index 46027d22db..875033e15c 100644 --- a/tests/integration/Cron/Workers/ExportFilesCleanupTest.php +++ b/tests/integration/Cron/Workers/ExportFilesCleanupTest.php @@ -15,7 +15,7 @@ class ExportFilesCleanupTest extends \MailPoetTest { touch($new_file_path); $cleanup = new ExportFilesCleanup(); - $cleanup->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $cleanup->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true)); $this->assertFileExists($new_file_path); $this->assertFileNotExists($old_file_path); diff --git a/tests/integration/Cron/Workers/InactiveSubscribersTest.php b/tests/integration/Cron/Workers/InactiveSubscribersTest.php index 92fcde86f8..83201b078b 100644 --- a/tests/integration/Cron/Workers/InactiveSubscribersTest.php +++ b/tests/integration/Cron/Workers/InactiveSubscribersTest.php @@ -33,7 +33,7 @@ class InactiveSubscribersTest extends \MailPoetTest { ], $this); $worker = new InactiveSubscribers($controller_mock, $this->settings); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true)); $task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE) ->where('status', ScheduledTask::STATUS_SCHEDULED) @@ -53,7 +53,7 @@ class InactiveSubscribersTest extends \MailPoetTest { ], $this); $worker = new InactiveSubscribers($controller_mock, $this->settings); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true)); } function testItSchedulesNextRunWhenFinished() { @@ -65,7 +65,7 @@ class InactiveSubscribersTest extends \MailPoetTest { ], $this); $worker = new InactiveSubscribers($controller_mock, $this->settings); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true)); $task = ScheduledTask::where('type', InactiveSubscribers::TASK_TYPE) ->where('status', ScheduledTask::STATUS_SCHEDULED) @@ -86,7 +86,7 @@ class InactiveSubscribersTest extends \MailPoetTest { $worker = new InactiveSubscribers($controller_mock, $this->settings); $worker->processTaskStrategy(ScheduledTask::createOrUpdate( ['meta' => ['max_subscriber_id' => 2001 /* 3 iterations of BATCH_SIZE in markInactiveSubscribers */]] - )); + ), microtime(true)); expect($controller_mock->markInactiveSubscribers(5, 1000))->equals('ok'); expect($controller_mock->markActiveSubscribers(5, 1000))->equals('ok'); @@ -103,7 +103,7 @@ class InactiveSubscribersTest extends \MailPoetTest { $task = ScheduledTask::createOrUpdate([]); $worker = new InactiveSubscribers($controller_mock, $this->settings); - $worker->processTaskStrategy($task); + $worker->processTaskStrategy($task, microtime(true)); $meta = $task->getMeta(); expect(isset($meta['last_subscriber_id']))->equals(false); @@ -117,9 +117,8 @@ class InactiveSubscribersTest extends \MailPoetTest { 'reactivateInactiveSubscribers' => Stub\Expected::never(), ], $this); - $worker = new InactiveSubscribers($controller_mock, $this->settings, microtime(true) - ($this->cron_helper->getDaemonExecutionLimit() - 1)); - sleep(1); + $worker = new InactiveSubscribers($controller_mock, $this->settings); $this->setExpectedException(\Exception::class, 'Maximum execution time has been reached.'); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate([])); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate([]), microtime(true) - $this->cron_helper->getDaemonExecutionLimit()); } } diff --git a/tests/integration/Cron/Workers/KeyCheck/KeyCheckWorkerTest.php b/tests/integration/Cron/Workers/KeyCheck/KeyCheckWorkerTest.php index b1159057de..610c12287b 100644 --- a/tests/integration/Cron/Workers/KeyCheck/KeyCheckWorkerTest.php +++ b/tests/integration/Cron/Workers/KeyCheck/KeyCheckWorkerTest.php @@ -25,7 +25,7 @@ class KeyCheckWorkerTest extends \MailPoetTest { function testItReturnsTrueOnSuccessfulKeyCheck() { $task = $this->createRunningTask(); - $result = $this->worker->processTaskStrategy($task); + $result = $this->worker->processTaskStrategy($task, microtime(true)); expect($result)->true(); } @@ -44,7 +44,7 @@ class KeyCheckWorkerTest extends \MailPoetTest { ['rescheduleProgressively' => Expected::once()], $this ); - $result = $worker->processTaskStrategy($task); + $result = $worker->processTaskStrategy($task, microtime(true)); expect($result)->false(); } @@ -61,7 +61,7 @@ class KeyCheckWorkerTest extends \MailPoetTest { ['rescheduleProgressively' => Expected::once()], $this ); - $result = $worker->processTaskStrategy($task); + $result = $worker->processTaskStrategy($task, microtime(true)); expect($result)->false(); } diff --git a/tests/integration/Cron/Workers/SchedulerTest.php b/tests/integration/Cron/Workers/SchedulerTest.php index 8bb389112c..f8b79fc76f 100644 --- a/tests/integration/Cron/Workers/SchedulerTest.php +++ b/tests/integration/Cron/Workers/SchedulerTest.php @@ -34,17 +34,10 @@ class SchedulerTest extends \MailPoetTest { $this->cron_helper = ContainerWrapper::getInstance()->get(CronHelper::class); } - function testItConstructs() { - $scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper); - expect($scheduler->timer)->greaterOrEquals(5); - $timer = microtime(true) - 2; - $scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper, $timer); - expect($scheduler->timer)->equals($timer); - } - function testItThrowsExceptionWhenExecutionLimitIsReached() { try { - $scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper, microtime(true) - $this->cron_helper->getDaemonExecutionLimit()); + $scheduler = new Scheduler($this->makeEmpty(SubscribersFinder::class), $this->logger_factory, $this->cron_helper); + $scheduler->process(microtime(true) - $this->cron_helper->getDaemonExecutionLimit()); self::fail('Maximum execution time limit exception was not thrown.'); } catch (\Exception $e) { expect($e->getMessage())->equals('Maximum execution time has been reached.'); @@ -556,15 +549,11 @@ class SchedulerTest extends \MailPoetTest { $queue->save(); $scheduler = Stub::make(Scheduler::class, [ 'processPostNotificationNewsletter' => Expected::exactly(1), - 'cron_helper' => $this->cron_helper, + 'cron_helper' => $this->make(CronHelper::class, [ + 'enforceExecutionLimit' => Expected::exactly(2), // call at start + during processing + ]), ], $this); - $scheduler->timer = microtime(true) - $this->cron_helper->getDaemonExecutionLimit(); - try { - $scheduler->process(); - self::fail('Maximum execution time limit exception was not thrown.'); - } catch (\Exception $e) { - expect($e->getMessage())->equals('Maximum execution time has been reached.'); - } + $scheduler->process(); } function testItDoesNotProcessScheduledJobsWhenNewsletterIsNotActive() { diff --git a/tests/integration/Cron/Workers/SendingQueue/MigrationTest.php b/tests/integration/Cron/Workers/SendingQueue/MigrationTest.php index 9c50693518..8f00defea0 100644 --- a/tests/integration/Cron/Workers/SendingQueue/MigrationTest.php +++ b/tests/integration/Cron/Workers/SendingQueue/MigrationTest.php @@ -56,7 +56,7 @@ class MigrationTest extends \MailPoetTest { function testItPausesSendingWhenPreparingATask() { $task = $this->createScheduledTask(); expect(MailerLog::isSendingPaused())->false(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect($task->status)->null(); expect(MailerLog::isSendingPaused())->true(); } @@ -66,14 +66,14 @@ class MigrationTest extends \MailPoetTest { $this->worker->pauseSending(); expect(MailerLog::isSendingPaused())->true(); $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(MailerLog::isSendingPaused())->false(); } function testItCompletesTaskIfThereIsNothingToMigrate() { SendingQueue::deleteMany(); $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect(ScheduledTask::findOne($task->id)->status)->equals(ScheduledTask::STATUS_COMPLETED); } @@ -83,7 +83,7 @@ class MigrationTest extends \MailPoetTest { expect(ScheduledTaskSubscriber::whereGt('task_id', 0)->count())->equals(0); $task = $this->createRunningTask(); - $this->worker->processTask($task); + $this->worker->processTask($task, microtime(true)); expect($this->worker->getUnmigratedQueues()->count())->equals(0); expect(ScheduledTask::where('type', SendingTask::TASK_TYPE)->findMany())->count(4); @@ -105,7 +105,7 @@ class MigrationTest extends \MailPoetTest { $this->worker->pauseSending(); expect(MailerLog::isSendingPaused())->true(); $task = $this->createRunningTask(); - $this->worker->processTask($task); + $this->worker->processTask($task, microtime(true)); expect(MailerLog::isSendingPaused())->false(); } diff --git a/tests/integration/Cron/Workers/SendingQueue/SendingQueueTest.php b/tests/integration/Cron/Workers/SendingQueue/SendingQueueTest.php index 31fe3abae9..87e539db9d 100644 --- a/tests/integration/Cron/Workers/SendingQueue/SendingQueueTest.php +++ b/tests/integration/Cron/Workers/SendingQueue/SendingQueueTest.php @@ -134,19 +134,6 @@ class SendingQueueTest extends \MailPoetTest { expect($this->sending_queue_worker->batch_size)->equals(SendingQueueWorker::BATCH_SIZE); expect($this->sending_queue_worker->mailer_task instanceof MailerTask); expect($this->sending_queue_worker->newsletter_task instanceof NewsletterTask); - expect(strlen($this->sending_queue_worker->timer))->greaterOrEquals(5); - - // constructor accepts timer argument - $timer = microtime(true) - 5; - $sending_queue_worker = new SendingQueueWorker( - $this->sending_error_handler, - $this->stats_notifications_worker, - $this->logger_factory, - Stub::makeEmpty(NewslettersRepository::class), - $this->cron_helper, - $timer - ); - expect($sending_queue_worker->timer)->equals($timer); } function testItEnforcesExecutionLimitsBeforeQueueProcessing() { @@ -185,7 +172,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -202,7 +188,8 @@ class SendingQueueTest extends \MailPoetTest { 'newsletter_id' => 1, 'subscriber_id' => 1, 'queue_id' => $this->queue->id, - ] + ], + microtime(true) ); } @@ -223,7 +210,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -240,7 +226,8 @@ class SendingQueueTest extends \MailPoetTest { 'newsletter_id' => 1, 'subscriber_id' => 1, 'queue_id' => $queue->id, - ] + ], + microtime(true) ); } @@ -282,7 +269,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -313,7 +299,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -342,7 +327,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -390,7 +374,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -441,7 +424,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -499,7 +481,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class), $this->cron_helper, - $timer = false, Stub::makeEmpty(new MailerTask(), [], $this) ); $sending_queue_worker->process(); @@ -518,7 +499,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -571,7 +551,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -746,7 +725,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ @@ -760,7 +738,8 @@ class SendingQueueTest extends \MailPoetTest { $prepared_subscribers = [], $prepared_newsletters = [], $prepared_subscribers = [], - $statistics = [] + $statistics = [], + microtime(true) ); $this->fail('Paused sending exception was not thrown.'); } catch (\Exception $e) { @@ -783,7 +762,6 @@ class SendingQueueTest extends \MailPoetTest { $this->logger_factory, Stub::makeEmpty(NewslettersRepository::class, ['findOneById' => new NewsletterEntity()]), $this->cron_helper, - $timer = false, Stub::make( new MailerTask(), [ diff --git a/tests/integration/Cron/Workers/SimpleWorkerTest.php b/tests/integration/Cron/Workers/SimpleWorkerTest.php index 33fff17e26..273e90f54b 100644 --- a/tests/integration/Cron/Workers/SimpleWorkerTest.php +++ b/tests/integration/Cron/Workers/SimpleWorkerTest.php @@ -35,15 +35,9 @@ class SimpleWorkerTest extends \MailPoetTest { } } - function testItConstructs() { - expect($this->worker->timer)->notEmpty(); - } - function testItThrowsExceptionWhenExecutionLimitIsReached() { try { - new MockSimpleWorker( - microtime(true) - $this->cron_helper->getDaemonExecutionLimit() - ); + $this->worker->process(microtime(true) - $this->cron_helper->getDaemonExecutionLimit()); self::fail('Maximum execution time limit exception was not thrown.'); } catch (\Exception $e) { expect($e->getMessage())->equals('Maximum execution time has been reached.'); @@ -115,6 +109,7 @@ class SimpleWorkerTest extends \MailPoetTest { ['checkProcessingRequirements' => false], $this ); + $worker->__construct(); expect($worker->process())->false(); } @@ -127,6 +122,7 @@ class SimpleWorkerTest extends \MailPoetTest { ], $this ); + $worker->__construct(); $worker->process(); } @@ -138,13 +134,13 @@ class SimpleWorkerTest extends \MailPoetTest { function testItPreparesTask() { $task = $this->createScheduledTask(); - $this->worker->prepareTask($task); + $this->worker->prepareTask($task, microtime(true)); expect($task->status)->null(); } function testItProcessesTask() { $task = $this->createRunningTask(); - $result = $this->worker->processTask($task); + $result = $this->worker->processTask($task, microtime(true)); expect($task->status)->equals(ScheduledTask::STATUS_COMPLETED); expect($result)->equals(true); } @@ -157,7 +153,7 @@ class SimpleWorkerTest extends \MailPoetTest { ['processTaskStrategy' => false], $this ); - $result = $worker->processTask($task); + $result = $worker->processTask($task, microtime(true)); expect($task->status)->equals(null); expect($result)->equals(false); } @@ -229,9 +225,9 @@ class SimpleWorkerTest extends \MailPoetTest { ->willReturn(true); $task = $this->createRunningTask(); expect(empty($task->in_progress))->equals(true); - expect($worker->processTask($task))->equals(true); + expect($worker->processTask($task, microtime(true)))->equals(true); $task->in_progress = true; - expect($worker->processTask($task))->equals(false); + expect($worker->processTask($task, microtime(true)))->equals(false); } function testItWillResetTheInProgressFlagOnFail() { @@ -243,7 +239,7 @@ class SimpleWorkerTest extends \MailPoetTest { ->willThrowException(new \Exception('test error')); $task = $this->createRunningTask(); try { - $worker->processTask($task); + $worker->processTask($task, microtime(true)); $this->fail('An exception should be thrown'); } catch (\Exception $e) { expect($e->getMessage())->equals('test error'); @@ -260,11 +256,11 @@ class SimpleWorkerTest extends \MailPoetTest { ->willReturn(true); $task = $this->createRunningTask(); $task = ScheduledTask::findOne($task->id); // make sure `updated_at` is set by the DB - expect($worker->processTask($task))->equals(true); + expect($worker->processTask($task, microtime(true)))->equals(true); $scheduled_at = $task->scheduled_at; $task->updated_at = Carbon::createFromTimestamp(strtotime($task->updated_at)) ->subMinutes(MockSimpleWorker::TASK_RUN_TIMEOUT + 1); - expect($worker->processTask($task))->equals(false); + expect($worker->processTask($task, microtime(true)))->equals(false); $task = ScheduledTask::findOne($task->id); expect($scheduled_at < $task->scheduled_at)->true(); expect($task->status)->equals(ScheduledTask::STATUS_SCHEDULED); diff --git a/tests/integration/Cron/Workers/UnsubscribeTokensTest.php b/tests/integration/Cron/Workers/UnsubscribeTokensTest.php index 9fa251228c..0eab0ff2ff 100644 --- a/tests/integration/Cron/Workers/UnsubscribeTokensTest.php +++ b/tests/integration/Cron/Workers/UnsubscribeTokensTest.php @@ -48,7 +48,7 @@ class UnsubscribeTokensTest extends \MailPoetTest { function testItAddsTokensToSubscribers() { $worker = new UnsubscribeTokens(); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate()); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate(), microtime(true)); $this->subscriber_with_token = Subscriber::findOne($this->subscriber_with_token->id); $this->subscriber_without_token = Subscriber::findOne($this->subscriber_without_token->id); expect($this->subscriber_with_token->unsubscribe_token)->equals('aaabbbcccdddeee'); @@ -57,7 +57,7 @@ class UnsubscribeTokensTest extends \MailPoetTest { function testItAddsTokensToNewsletters() { $worker = new UnsubscribeTokens(); - $worker->processTaskStrategy(ScheduledTask::createOrUpdate()); + $worker->processTaskStrategy(ScheduledTask::createOrUpdate(), microtime(true)); $this->newsletter_with_token = Newsletter::findOne($this->newsletter_with_token->id); $this->newsletter_without_token = Newsletter::findOne($this->newsletter_without_token->id); expect($this->newsletter_with_token->unsubscribe_token)->equals('aaabbbcccdddeee'); diff --git a/tests/integration/Cron/Workers/WooCommerceSyncTest.php b/tests/integration/Cron/Workers/WooCommerceSyncTest.php index 0b75910ecb..3f6c6eb4f1 100644 --- a/tests/integration/Cron/Workers/WooCommerceSyncTest.php +++ b/tests/integration/Cron/Workers/WooCommerceSyncTest.php @@ -31,7 +31,7 @@ class WooCommerceSyncTest extends \MailPoetTest { $this->woocommerce_segment->expects($this->once()) ->method('synchronizeCustomers'); $task = $this->createScheduledTask(); - expect($this->worker->processTaskStrategy($task))->equals(true); + expect($this->worker->processTaskStrategy($task, microtime(true)))->equals(true); } private function createScheduledTask() {