[Fix] Internal cron scheduler blocking view responses

Internal cron is now triggered by an axios request from the frontend so it can truly run in a separate request. Fixes #167
This commit is contained in:
2025-12-07 12:55:33 +01:00
parent 25034ee2f3
commit 6b688f72e0
8 changed files with 108 additions and 119 deletions
@@ -18,6 +18,7 @@ public function handle(CaldavService $service)
// only run every 5 minutes although the task is called every minute
$cacheKey = 'caldav_sync_last_run';
if (\Illuminate\Support\Facades\Cache::has($cacheKey)) {
Log::info('CalDAV sync Throttled');
return 0;
}
Cache::put($cacheKey, true, 300);
@@ -33,6 +34,7 @@ public function handle(CaldavService $service)
$count++;
}
Log::info("Synced " . count($todos) . " todos.");
$this->info("Synced " . count($todos) . " todos.");
return 0;
}
@@ -2,7 +2,7 @@
namespace App\Http\Middleware;
use Illuminate\Foundation\Inspiring;
use App\Models\Setting;
use Illuminate\Http\Request;
use Inertia\Middleware;
@@ -39,10 +39,9 @@ public function share(Request $request): array
return [
...parent::share($request),
'name' => config('app.name'),
'auth' => [
'user' => $request->user(),
],
'auth' => ['user' => $request->user(),],
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
'cron' => Setting::get('app.cron_method') === 'request'
];
}
}
-48
View File
@@ -1,48 +0,0 @@
<?php
namespace App\Listeners;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Setting;
class ScheduleListener
{
/**
* Handle the event.
*
* This listener is attached to RouteMatched when app.schedule_method == 'internal'.
* It will trigger the scheduler at most once per minute (throttle via cache).
*/
public function handle($event)
{
// TODO: this check is also done, when registering the listener EventServiceProvider.php
// it can probably be removed here safely which would spare a database call on each request
// only run when internal scheduling is enabled (defensive)
$method = Setting::where('key', 'app.schedule_method')->value('value') ?? 'internal';
if ($method !== 'internal') {
return;
}
// throttle key: run at most once every 55 seconds
$cacheKey = 'caramel_scheduler_last_run';
$ttlSeconds = 55;
if (Cache::has($cacheKey)) {
return;
}
// mark as run
Cache::put($cacheKey, true, $ttlSeconds);
try {
Log::info('Triggering scheduler via ScheduleListener');
Artisan::call('schedule:run');
} catch (\Throwable $e) {
Log::error('Error running scheduler: ' . $e->getMessage());
}
}
}
+3 -15
View File
@@ -4,11 +4,6 @@
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Schedule;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Illuminate\Routing\Events\RouteMatched;
use App\Models\Setting;
use App\Listeners\ScheduleListener;
use App\Jobs\CheckInvoiceDueDatesJob;
class EventServiceProvider extends ServiceProvider
@@ -22,16 +17,9 @@ public function boot(): void
{
parent::boot();
if (Schema::hasTable('settings')) {
$method = Setting::where('key', 'app.schedule_method')->value('value') ?? 'internal';
if ($method === 'internal') {
Event::listen(RouteMatched::class, [ScheduleListener::class, 'handle']);
}
}
// TODO: read where to put these or ask in the forums
// it seems to work here, but where is the apropriate place?
// Kernel::schedule did not work
// // TODO: read where to put these or ask in the forums
// // it seems to work here, but where is the apropriate place?
// // Kernel::schedule did not work
Schedule::command('caldav:sync')
->everyMinute()
->withoutOverlapping();
+1 -1
View File
@@ -11,6 +11,6 @@ public function run(): void
{
Setting::updateOrCreate(['key' => 'invoices.number_format'], ['value' => 'RE-{number}']);
Setting::updateOrCreate(['key' => 'invoices.number_start'], ['value' => '1']);
Setting::updateOrCreate(['key' => 'app.schedule_method'], ['value' => '1']);
Setting::updateOrCreate(['key' => 'app.cron_method'], ['value' => 'request']);
}
}
+20 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Head } from '@inertiajs/vue3'
import { Head, usePage } from '@inertiajs/vue3'
import AppSidebar from '@/components/AppSidebar.vue';
import { onMounted } from 'vue';
import 'vue-sonner/style.css'
@@ -7,22 +7,38 @@ import { Toaster } from 'vue-sonner'
import { Info, CircleAlert, CircleCheck, LoaderCircle, Ban } from "lucide-vue-next"
import { Button } from '@/components/ui/crm-button'
import { SidebarProvider } from '@/components/ui/sidebar';
import { usePage } from '@inertiajs/vue3';
import { AlertDialog, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/components/ui/alert-dialog'
import { alertStore } from '@/stores/alertStore';
import axios from 'axios';
const isOpen = usePage().props.sidebarOpen;
const alert = alertStore()
const props = defineProps<{
title: string;
title: string
}>();
const isOpen = usePage().props.sidebarOpen;
const cron = usePage().props.cron
onMounted(() => {
if (navigator.platform.toUpperCase().indexOf('MAC') >= 0) {
document.body.classList.add('is-mac')
}
if (cron) {
triggerWebcron()
setInterval(triggerWebcron, 30000)
}
})
const triggerWebcron = async function () {
await axios.get('/webcron')
.catch(function (response) {
if (response.status >= 400) {
console.error(response.message)
}
})
}
</script>
<template>
+24
View File
@@ -2,11 +2,35 @@
// import AuthLayout from '@/layouts/auth/AuthSimpleLayout.vue';
// import AuthLayout from '@/layouts/auth/AuthCardLayout.vue';
import AuthLayout from '@/layouts/auth/AuthSplitLayout.vue';
import { onMounted } from 'vue';
import { usePage } from '@inertiajs/vue3'
import axios from 'axios';
defineProps<{
title?: string;
description?: string;
}>();
const cron = usePage().props.cron
onMounted(() => {
if (navigator.platform.toUpperCase().indexOf('MAC') >= 0) {
document.body.classList.add('is-mac')
}
if (cron) {
triggerWebcron()
}
})
const triggerWebcron = async function () {
await axios.get('/webcron')
.catch(function (response) {
if (response.status >= 400) {
console.error(response)
}
})
}
</script>
<template>
+55 -47
View File
@@ -9,6 +9,7 @@
use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\ProductController;
use App\Models\Setting;
Route::middleware('auth')->group(function () {
@@ -54,8 +55,6 @@
// Products
Route::get('products', [ProductController::class, 'show'])->name('products');
Route::get('timesheets', function () {
return Inertia::render('Timesheets');
})->name('timesheets');
@@ -64,53 +63,62 @@
Route::get('proceduralDocumentation', function () {
return Inertia::render('ProceduralDocumentation');
})->name('proceduralDocumentation');
/*
|--------------------------------------------------------------------------
| Web cron route
|--------------------------------------------------------------------------
|
| Example: GET /webcron?token=SECRET or set header X-WEBCron-Token: SECRET
| Configure secret in .env as WEBCRON_SECRET (optional). If no secret is set,
| the route is open (not recommended in production).
|
*/
Route::get('/webcron', function (Request $request) {
// only allow if scheduling method is webcron
$method = \App\Models\Setting::where('key', 'app.schedule_method')->value('value') ?? 'internal';
if ($method !== 'webcron') {
return response('Not Found', 404);
}
$secret = env('WEBCRON_SECRET', null);
// basic token protection
if ($secret) {
$token = $request->query('token') ?? $request->header('X-WEBCron-Token');
if (!$token || !hash_equals((string)$secret, (string)$token)) {
return response('Forbidden', 403);
}
}
// quick throttle to avoid abuse (server-side)
$cacheKey = 'caramel_webcron_last_run';
if (\Illuminate\Support\Facades\Cache::has($cacheKey)) {
return response('Throttled', 429);
}
Cache::put($cacheKey, true, 55);
try {
Log::info('Triggering scheduler via /webcron route');
Artisan::call('schedule:run');
return response('OK', 200);
} catch (\Throwable $e) {
Log::error('Error running scheduler: ' . $e->getMessage());
return response('Error', 500);
}
});
});
/*
|--------------------------------------------------------------------------
| Web cron route
|--------------------------------------------------------------------------
|
| Example: GET /webcron?token=SECRET or set header X-WEBCron-Token: SECRET
| Configure secret in .env as WEBCRON_SECRET (optional). If no secret is set,
| the route is open (not recommended in production).
|
*/
Route::get('/webcron', function (Request $request) {
// Return early of cron method is set to anything other then 'webcron' or 'request'
$method = \App\Models\Setting::where('key', 'app.cron_method')->value('value') ?? 'request';
if (!in_array($method, ['webcron', 'request'])) {
return response('Not Found', 404);
}
// TODO: Only allow requests from the same host or with the secret token
// $clientHost = ;
// $serverHost = ;
$sameHost = true;
$secret = env('WEBCRON_SECRET', null);
$token = null;
if ($secret) {
$token = $request->query('token') ?? $request->header('X-WEBCron-Token');
}
if (
!hash_equals((string)$secret, (string)$token) &&
!$sameHost
) {
return response('Forbidden', 403);
}
// Throttle to avoid abuse (server-side)
$cacheKey = 'caramel_webcron_last_run';
if (\Illuminate\Support\Facades\Cache::has($cacheKey)) {
return response('Throttled', 304);
}
Cache::put($cacheKey, true, 55);
// Run scheduler
try {
Log::info('Triggering scheduler via /webcron route');
$output = '';
Artisan::call('schedule:run');
return response('OK', 200);
} catch (\Throwable $e) {
Log::error('Error running scheduler: ' . $e->getMessage());
return response('Error', 500);
}
});
require __DIR__ . '/settings.php';
require __DIR__ . '/auth.php';