diff --git a/lib/Cron/CronHelper.php b/lib/Cron/CronHelper.php index 7767c91ea9..c215e42297 100644 --- a/lib/Cron/CronHelper.php +++ b/lib/Cron/CronHelper.php @@ -84,6 +84,26 @@ class CronHelper { return WPFunctions::wpRemoteRetrieveBody($result); } + /** + * @return boolean|null + */ + static function isDaemonAccessible() { + $daemon = self::getDaemon(); + if(!$daemon || $daemon['run_accessed_at'] === null) { + return null; + } + if($daemon['run_accessed_at'] <= (int)$daemon['run_started_at']) { + return true; + } + if( + $daemon['run_accessed_at'] + self::DAEMON_REQUEST_TIMEOUT < time() && + $daemon['run_accessed_at'] > (int)$daemon['run_started_at'] + ) { + return false; + } + return null; + } + static function queryCronUrl($url) { $args = WPHooks::applyFilters( 'mailpoet_cron_request_args', diff --git a/tests/unit/Cron/CronHelperTest.php b/tests/unit/Cron/CronHelperTest.php index a6f13028c4..b19825c1d6 100644 --- a/tests/unit/Cron/CronHelperTest.php +++ b/tests/unit/Cron/CronHelperTest.php @@ -125,6 +125,77 @@ class CronHelperTest extends \MailPoetTest { } } + function testItDetectsNotAccessibleDaemon() { + $time = time(); + $run_start_values = [null, $time - 20]; + foreach($run_start_values as $run_start) { + $daemon = [ + 'token' => 'some_token', + 'updated_at' => 12345678, + 'run_accessed_at' => $time - 10, + 'run_started_at' => $run_start, + 'run_completed_at' => null, + 'last_error' => null, + ]; + Setting::setValue( + CronHelper::DAEMON_SETTING, + $daemon + ); + expect(CronHelper::isDaemonAccessible())->false(); + } + } + + function testItDetectsAccessibleDaemon() { + $time = time(); + $daemon = [ + 'token' => 'some_token', + 'updated_at' => 12345678, + 'run_accessed_at' => $time - 5, + 'run_started_at' => $time - 4, + 'run_completed_at' => null, + 'last_error' => null, + ]; + Setting::setValue( + CronHelper::DAEMON_SETTING, + $daemon + ); + expect(CronHelper::isDaemonAccessible())->true(); + } + + function testItDetectsUnknownStateOfTheDaemon() { + $time = time(); + $test_inputs = [ + [ + 'run_access' => null, + 'run_start' => null, + ], + [ + 'run_access' => $time - 4, + 'run_start' => null, + ], + [ + 'run_access' => $time - 4, + 'run_start' => $time - 10, + ], + null, + ]; + foreach($test_inputs as $test_input) { + $daemon = [ + 'token' => 'some_token', + 'updated_at' => 12345678, + 'run_accessed_at' => $test_input['run_access'], + 'run_started_at' => $test_input['run_start'], + 'run_completed_at' => null, + 'last_error' => null, + ]; + Setting::setValue( + CronHelper::DAEMON_SETTING, + $daemon + ); + expect(CronHelper::isDaemonAccessible())->null(); + } + } + function testItCreatesRandomToken() { // random token is a string of 5 characters $token1 = CronHelper::createToken();