[TikiWiki-commits] [Git][tikiwiki/tiki][master] [NEW][ENH][REF] QueuedTasks: Add preference to disable JS processing while...

Benoit Grégoire (@benoitg) via TikiWiki-cvs <[email protected]>
Newsgroups gmane.comp.cms.tiki.cvs
Message-ID <6966a1f1abd7d_2c18149c5475d@gitlab-sidekiq-low-urgency-cpu-bound-v2-78c7665866-td56w.mail>

Benoit Grégoire pushed to branch master at Tiki Wiki CMS Groupware / Tiki


Commits:
9b826f4f by Sandeep D at 2026-01-13T19:41:27+00:00
[NEW][ENH][REF] QueuedTasks: Add preference to disable JS processing while maintaining status polling
---
* [ENH] Improve check for "queued_tasks_has_pending" flag in JavaScript.php

* [NEW][ENH][REF] QueuedTasks: Add preference to disable JS processing while maintaining status polling

**Summary**
- Add new preference `queued_tasks_js_processing_disabled` to disable web polling for queue processing while keeping task status polling active for user feedback
- Implement early returns in both PHP and JavaScript when `feature_queued_tasks` is disabled to prevent any polling or processing
- Implement smart polling that automatically stops status polling when users have no active tasks, reducing unnecessary server requests

**Changes**
– Add `queued_tasks_js_processing_disabled` preference with dependency on `feature_queued_tasks`, defaults to 'n' (web processing enabled by default)
– Inject three config flags to JavaScript: `feature_queued_tasks`, `queued_tasks_js_processing_disabled`, and `queued_tasks_has_pending` for client-side decision making
- Add early return in `actionProcessPendingTasks()` when web processing is disabled (similar to `webcron_enabled` pattern)
- Add early return in `actionUpdateQueuedJobsLiveStatus()` when feature is disabled, returning `disabled` flag to stop client-side polling
- Implement separate polling intervals for status (7 seconds) and processing (60 seconds)
- Check `queued_tasks_js_processing_disabled` before triggering task processing
- Implement smart status polling that auto-stops when `user_active_jobs` reaches 0, only start status polling on page load if `queued_tasks_has_pending` is true

See merge request tikiwiki/tiki!9353

- - - - -


11 changed files:

- lib/core/Search/SearchIndexRebuilder.php
- lib/core/Services/Manager/Controller.php
- lib/core/Services/QueueManager/QueueManagerController.php
- lib/core/TaskQueue/QueuedTaskSettings.php
- lib/jquery_tiki/tiki-jquery.js
- + lib/prefs/queued.php
- lib/setup/javascript.php
- templates/admin/include_general.tpl
- templates/queuedtasks/tiki-admin_queued_banner.tpl
- templates/queuedtasks/tiki-admin_queued_tasks.tpl
- tiki-print.php


Changes:

=====================================
lib/core/Search/SearchIndexRebuilder.php
=====================================
@@ -54,7 +54,7 @@ class SearchIndexRebuilder
                         'id' => $taskId,
                         'page' => 'index_rebuild',
                         'status' => tr('Pending'),
-                        'mes' => tr("Your index rebuild task (#%0) has been queued successfully and will be executed shortly. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.", $taskId)
+                        'mes' => tr("Your index rebuild task (#%0) has been queued successfully. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.", $taskId)
                     ]);
                 } else {
                     Feedback::error(tr("Failed to add index rebuild into queue"));


=====================================
lib/core/Services/Manager/Controller.php
=====================================
@@ -480,7 +480,7 @@ class Services_Manager_Controller
                             'id' => $taskId,
                             'page' => 'manager_create',
                             'status' => tr('Pending'),
-                            'mes' => tr("Your instance creation task (#%0) has been queued successfully and will be executed shortly. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.", $taskId)
+                            'mes' => tr("Your instance creation task (#%0) has been queued successfully. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.", $taskId)
                         ]);
                     } else {
                         Feedback::error(tr("Failed to add Instance creation into queue"));


=====================================
lib/core/Services/QueueManager/QueueManagerController.php
=====================================
@@ -25,43 +25,59 @@ class QueueManagerController
     public function actionUpdateQueuedJobsLiveStatus($input)
     {
         global $prefs;
-        $response = [];
 
-        if ($prefs['feature_queued_tasks'] !== 'y') {
-            return $response;
+        // Return flag to stop polling if feature is disabled
+        if (($prefs['feature_queued_tasks'] ?? 'n') !== 'y') {
+            return ['disabled' => true];
         }
 
+        $response = [
+            'jobs' => [],
+            'user_active_jobs' => 0,
+        ];
+
         $jobsTobeUpdatedIds = array_column(QueuedTaskBanner::get(), 'id');
 
         if (empty($jobsTobeUpdatedIds)) {
             return $response;
         }
 
-        if (! empty($jobsTobeUpdatedIds)) {
-            $jobs = $this->lib->getQueuedTasksByIds(['id', 'status', 'type'], $jobsTobeUpdatedIds);
-            foreach ($jobs as $job) {
-                $tempArray = [];
-                if (! in_array($job['id'], $jobsTobeUpdatedIds)) {
-                    QueuedTaskBanner::clear($job['id']);
-                }
-                $tempArray['id'] = $job['id'];
-                $tempArray['status'] = $job['status'];
-                $tempArray['page'] = QueuedTaskSettings::getPageByJobType($job['type']);
-
-                // Render the status message using Smarty template
-                $smarty = TikiLib::lib('smarty');
-                $smarty->assign('jobId', $job['id']);
-                $smarty->assign('status', $job['status']);
-                $tempArray['mes'] = $smarty->fetch('queuedtasks/tiki-admin_queued_banner.tpl');
-
-                QueuedTaskBanner::update($job['id'], [
-                    'status' => $job['status'],
-                    'mes' => $tempArray['mes']
-                ]);
-                $response[] = $tempArray;
+        $jobs = $this->lib->getQueuedTasksByIds(['id', 'status', 'type'], $jobsTobeUpdatedIds);
+        $foundJobIds = array_column($jobs, 'id');
+
+        // Clear banners for jobs that no longer exist in the database
+        foreach ($jobsTobeUpdatedIds as $jobId) {
+            if (! in_array($jobId, $foundJobIds)) {
+                QueuedTaskBanner::clear($jobId);
             }
         }
 
+        foreach ($jobs as $job) {
+            $tempArray = [];
+            $tempArray['id'] = $job['id'];
+            $tempArray['status'] = $job['status'];
+            $tempArray['page'] = QueuedTaskSettings::getPageByJobType($job['type']);
+
+            // Render the status message using Smarty template
+            $smarty = TikiLib::lib('smarty');
+            $smarty->assign('jobId', $job['id']);
+            $smarty->assign('status', $job['status']);
+            $smarty->assign('webProcessingDisabled', ($prefs['queued_tasks_js_processing_disabled'] ?? 'n') === 'y');
+            $tempArray['mes'] = $smarty->fetch('queuedtasks/tiki-admin_queued_banner.tpl');
+
+            // Update session with current status
+            QueuedTaskBanner::update($job['id'], [
+                'status' => $job['status'],
+                'mes' => $tempArray['mes']
+            ]);
+
+            if ($job['status'] === 'Pending' || $job['status'] === 'InProgress') {
+                $response['user_active_jobs']++;
+            }
+
+            $response['jobs'][] = $tempArray;
+        }
+
         return $response;
     }
 
@@ -69,7 +85,13 @@ class QueueManagerController
     {
         global $prefs;
 
-        if ($prefs['feature_queued_tasks'] !== 'y') {
+        // Check if feature is enabled
+        if (($prefs['feature_queued_tasks'] ?? 'n') !== 'y') {
+            return false;
+        }
+
+        // Check if web processing is disabled (use CLI instead)
+        if (($prefs['queued_tasks_js_processing_disabled'] ?? 'n') === 'y') {
             return false;
         }
 


=====================================
lib/core/TaskQueue/QueuedTaskSettings.php
=====================================
@@ -16,9 +16,9 @@ class QueuedTaskSettings
     private static $statuses = null;
 
     private static $jobTypePageMapping = [
-        'CreateInstance' => 'manager_create',
-        'RebuildIndex' => 'index_rebuild',
-        'PdfGeneration' => 'pdf_generation',
+        'CreateInstanceTask' => 'manager_create',
+        'RebuildIndexTask' => 'index_rebuild',
+        'PdfGenerationTask' => 'pdf_generation',
     ];
 
     /**


=====================================
lib/jquery_tiki/tiki-jquery.js
=====================================
@@ -4333,6 +4333,7 @@ $.fn.toastNotification = function (options) {
 };
 
 $(document).ready(function() {
+    // Update the live task queued alert with the given jobs.
     const updateLiveTaskQueuedAlert = function(jobs) {
         let html = '';
         if (Object.keys(jobs).length) {
@@ -4353,53 +4354,86 @@ $(document).ready(function() {
     };
 
     let lastUpdatedStatus = 0;
-    let lastExecutionTime = 0;
+    let lastProcessingTime = 0;
     let isProcessingPendingTasks = false;
+    let statusPollingInterval = null;
+    let processingPollingInterval = null;
 
-    const pollingLiveTaskQueuedStatus = () => {
+    // Process pending tasks (for ALL users, not just this user)
+    const processPendingTasks = () => {
+        if (isProcessingPendingTasks || jqueryTiki.queued_tasks_js_processing_disabled) {
+            return;
+        }
         const now = Date.now();
-        if (now - lastUpdatedStatus < 7000) {
+        // Rate limit to once every 60 seconds
+        if (now - lastProcessingTime < 60000) {
             return;
         }
-        lastUpdatedStatus = now;
+        lastProcessingTime = now;
+        isProcessingPendingTasks = true;
         $.ajax({
-            url: $.service("queued_tasks", "UpdateQueuedJobsLiveStatus"),
-            success: function (res) {
-                let html = updateLiveTaskQueuedAlert(res);
-                $('#tiki_queued_tasks_banner').html(html);
+            url: $.service("queued_tasks", "ProcessPendingTasks"),
+            success: function (res) {},
+            error: function (req, status, error) {
+                console.error('Queued tasks processing error:', error);
             },
-            error: function(req, status, error) {
-                alert(error);
+            complete: function () {
+                isProcessingPendingTasks = false;
             },
-            complete: function () {},
         });
     };
 
-    const pollingProcessPendingTasks = () => {
-        if (isProcessingPendingTasks) {
-            return;
-        }
+    // Poll the live task queued status (for THIS user's tasks)
+    const pollingLiveTaskQueuedStatus = () => {
         const now = Date.now();
-        if (now - lastExecutionTime < 60000) {
+        if (now - lastUpdatedStatus < 7000) {
             return;
         }
-        lastExecutionTime = now;
-        isProcessingPendingTasks = true;
+        lastUpdatedStatus = now;
         $.ajax({
-            url: $.service("queued_tasks", "ProcessPendingTasks"),
-            success: function (res) {},
-            error: function (req, status, error) {
-                alert(error);
+            url: $.service("queued_tasks", "UpdateQueuedJobsLiveStatus"),
+            success: function (res) {
+                if (!res) return;
+                // Stop status polling if feature is disabled
+                if (res.disabled) {
+                    if (statusPollingInterval) {
+                        clearInterval(statusPollingInterval);
+                        statusPollingInterval = null;
+                    }
+                    $('#tiki_queued_tasks_banner').html('');
+                    return;
+                }
+
+                // Update the banner with job status
+                let html = updateLiveTaskQueuedAlert(res.jobs || []);
+                $('#tiki_queued_tasks_banner').html(html);
+
+                // Smart polling: stop status polling when this user has no more jobs to track
+                if (res.user_active_jobs === 0 && statusPollingInterval) {
+                    clearInterval(statusPollingInterval);
+                    statusPollingInterval = null;
+                }
             },
-            complete: function () {
-                isProcessingPendingTasks = false;
+            error: function(req, status, error) {
+                console.error('Queued tasks status polling error:', error);
             },
+            complete: function () {},
         });
     };
 
+    // Initialize polling when feature is enabled
     if (jqueryTiki.feature_queued_tasks) {
-        setInterval(pollingLiveTaskQueuedStatus, 7000);
-        setInterval(pollingProcessPendingTasks, 60000);
+        // Status polling: Start when feature is enabled, auto-stops when this user has no tasks
+        // Purpose: Track and display THIS user's task progress in the banner
+        if (jqueryTiki.queued_tasks_has_pending) {
+            statusPollingInterval = setInterval(pollingLiveTaskQueuedStatus, 7000);
+        }
+
+        // Processing polling: Always run when web processing is enabled, never stops
+        // Purpose: Process ANY pending task from ANY user at regular intervals
+        if (!jqueryTiki.queued_tasks_js_processing_disabled) {
+            processingPollingInterval = setInterval(processPendingTasks, 60000);
+        }
     }
 });
 


=====================================
lib/prefs/queued.php
=====================================
@@ -0,0 +1,20 @@
+<?php
+
+// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
+//
+// All Rights Reserved. See copyright.txt for details and a complete list of authors.
+// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
+
+function prefs_queued_list()
+{
+    return [
+        'queued_tasks_js_processing_disabled' => [
+            'name' => tra('Disable Web Queue Processing using AJAX calls to trigger background task processing'),
+            'description' => tra('When enabled, queued tasks will only be processed via CLI command (taskqueue:process). Web-based processing via JavaScript polling will be disabled, but status polling remains active.'),
+            'type' => 'flag',
+            'default' => 'n',
+            'dependencies' => ['feature_queued_tasks'],
+            'tags' => ['advanced'],
+        ],
+    ];
+}


=====================================
lib/setup/javascript.php
=====================================
@@ -8,6 +8,7 @@
 use Tiki\Lib\CookieConsent\CookieConsentLib;
 use Tiki\Lib\Theme\ThemeLib;
 use Tiki\Lib\TikiDate;
+use Tiki\TaskQueue\QueuedTaskBanner;
 
 if (basename($_SERVER['SCRIPT_NAME']) === basename(__FILE__)) {
     die('This script may only be included.');
@@ -245,7 +246,17 @@ $jqueryTiki['cookie_consent_categories'] = json_encode(array_keys(CookieConsentL
 $jqueryTiki['cookie_consent_value'] = json_encode(CookieConsentLib::getConsentPreferences(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
 $jqueryTiki['BUILTIN_COOKIE_CATEGORY_ESSENTIAL'] = json_encode(CookieConsentLib::BUILTIN_COOKIE_CATEGORY_ESSENTIAL);
 $jqueryTiki['wiki_url_scheme'] = $prefs['wiki_url_scheme'];
-$jqueryTiki['feature_queued_tasks'] = $prefs['feature_queued_tasks'] === 'y';
+$jqueryTiki['feature_queued_tasks'] = ($prefs['feature_queued_tasks'] ?? 'n') === 'y';
+$jqueryTiki['queued_tasks_js_processing_disabled'] = ($prefs['queued_tasks_js_processing_disabled'] ?? 'n') === 'y';
+// Check if user has active tasks (Pending or InProgress) to enable smart polling
+$hasActiveJobs = false;
+if (($prefs['feature_queued_tasks'] ?? 'n') === 'y') {
+    $activeJobs = QueuedTaskBanner::get(function ($job) {
+        return isset($job['status']) && ($job['status'] === 'Pending' || $job['status'] === 'InProgress');
+    });
+    $hasActiveJobs = ! empty($activeJobs);
+}
+$jqueryTiki['queued_tasks_has_pending'] = $hasActiveJobs;
 
 //set at 4 hours if empty
 $jqueryTiki['securityTimeout'] = ! empty($prefs['site_security_timeout']) ? $prefs['site_security_timeout']


=====================================
templates/admin/include_general.tpl
=====================================
@@ -185,6 +185,9 @@
             <fieldset id="QueuedTasks">
                 <legend>{tr}Queued Tasks{/tr}</legend>
                 {preference name=feature_queued_tasks}
+                <div class="adminoptionboxchild" id="feature_queued_tasks_childcontainer">
+                    {preference name=queued_tasks_js_processing_disabled}
+                </div>
             </fieldset>
             <fieldset>
                 <legend>{tr}Maintenance{/tr}</legend>


=====================================
templates/queuedtasks/tiki-admin_queued_banner.tpl
=====================================
@@ -1,12 +1,12 @@
 {if $status == 'InProgress'}
-    {tr}Task (#{$jobId}) is executing...{/tr} 
+    {tr}Task (#{$jobId}) is executing...{/tr}
 {elseif $status == 'Completed'}
-    {tr}Task (#{$jobId}) execution has been completed.{/tr} 
+    {tr}Task (#{$jobId}) execution has been completed.{/tr}
 {elseif $status == 'Pending'}
-    {tr}Task (#{$jobId}) is pending and will be started soon...{/tr} 
+    {tr}Task (#{$jobId}) is pending and will be started soon...{/tr}
 {elseif $status == 'Failed'}
-    {tr}Task (#{$jobId}) execution has failed.{/tr} 
+    {tr}Task (#{$jobId}) execution has failed.{/tr}
 {else}
-    {tr}Unknown status for task #{$jobId}{/tr} 
+    {tr}Unknown status for task #{$jobId}{/tr}
 {/if}
 <a target="_blank" href="tiki-admin_queued_tasks.php?id={$jobId}" title='{tr}View details{/tr}'>{tr}View details{/tr}</a>


=====================================
templates/queuedtasks/tiki-admin_queued_tasks.tpl
=====================================
@@ -81,9 +81,9 @@
                             '<td>' + job.type + '</td>' +
                             '<td>' + statusBadge + '</td>' +
                             '<td>' + result + '</td>' +
-                            '<td class="date">' + job.started_at || '' + '</td>' +
-                            '<td class="date">' + job.ended_at || '' + '</td>' +
-                            '<td class="date">' + job.created_at || '' + '</td>' +
+                            '<td class="date">' + (job.started_at || '') + '</td>' +
+                            '<td class="date">' + (job.ended_at || '') + '</td>' +
+                            '<td class="date">' + (job.created_at || '') + '</td>' +
                         '</tr>';
                     });
                     $('#admin_queued_tasks tbody').html(rows);


=====================================
tiki-print.php
=====================================
@@ -221,7 +221,7 @@ if (TIKI_PRINTING_PDF) {
                             'id' => $taskId,
                             'page' => 'pdf_generation',
                             'status' => 'Pending',
-                            'mes' => tr("Your pdf generation task (#{$taskId}) has been queued successfully and will be executed shortly. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.")
+                            'mes' => tr("Your pdf generation task (#%0) has been queued successfully. You can view the status and output on the <a target='_blank' href='tiki-admin_queued_tasks.php'>Queued Tasks</a> page.", $taskId)
                         ]);
                     } else {
                         Feedback::error(tr("Failed to add pdf generation into queue"));



View it on GitLab: https://gitlab.com/tikiwiki/tiki/-/commit/9b826f4f75e94863cc3a0f5937c5ad589fae5416

-- 
View it on GitLab: https://gitlab.com/tikiwiki/tiki/-/commit/9b826f4f75e94863cc3a0f5937c5ad589fae5416
You're receiving this email because of your account on gitlab.com.

_______________________________________________
TikiWiki-cvs mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/tikiwiki-cvs
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.