mivita/app/Support/OperationalAlert.php
Kevin c9cd17a41a Alarm-Mail bei fehlgeschlagenen geplanten Aufgaben und Queue-Jobs
- OperationalAlert: Log (Kanal monitoring) immer, Mail an
  MONITORING_ALERT_EMAIL (Standard EXCEPTION_MAIL), optional ntfy;
  gleiche Meldung hoechstens einmal pro Stunde
- Kernel: onFailure fuer alle geplanten Aufgaben (auch kuenftige)
- AppServiceProvider: Queue::failing
- withoutOverlapping mit kurzen Sperrdauern (10-60 Min.) statt 24 h

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:49:18 +00:00

107 lines
3.8 KiB
PHP

<?php
namespace App\Support;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Throwable;
/**
* Zentrale Betriebs-Alerts: meldet fehlgeschlagene geplante Aufgaben
* (Console\Kernel) und Queue-Jobs (AppServiceProvider). Der Log-Eintrag
* (`critical`, Kanal monitoring) läuft immer; Mail und ntfy-Push sind
* Best-Effort, unabhängig voneinander, und dürfen den auslösenden Prozess nie
* stören. Gleiche Meldungen gehen höchstens einmal je Drosselzeit raus, damit
* ein Task im 5-Minuten-Takt kein Postfach flutet.
*/
class OperationalAlert
{
/**
* @param array<string, mixed> $context
*/
public static function send(string $summary, array $context = []): void
{
Log::channel('monitoring')->critical('[monitoring] '.$summary, $context);
if (! config('monitoring.alerts.enabled') || ! self::firstWithinThrottle($summary)) {
return;
}
self::mail($summary, $context);
self::push($summary, $context);
}
private static function firstWithinThrottle(string $summary): bool
{
try {
return Cache::add('monitoring:alert:'.sha1($summary), true, now()->addMinutes((int) config('monitoring.alerts.throttle_minutes')));
} catch (Throwable) {
return true;
}
}
/**
* @param array<string, mixed> $context
*/
private static function mail(string $summary, array $context): void
{
$recipient = config('monitoring.alerts.mail_to');
if (empty($recipient)) {
return;
}
try {
Mail::raw(
$summary."\n\n".json_encode($context, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
fn ($message) => $message->to($recipient)->subject('['.config('app.name').'] Betriebs-Alert: '.Str::limit($summary, 80)),
);
} catch (Throwable $e) {
Log::channel('monitoring')->error('[monitoring] Alert-Mail konnte nicht versendet werden.', [
'summary' => $summary,
'error' => $e->getMessage(),
]);
}
}
/**
* JSON-Publish an die ntfy-Basis-URL (UTF-8-sicher, anders als Header).
*
* @param array<string, mixed> $context
*/
private static function push(string $summary, array $context): void
{
$url = (string) config('monitoring.alerts.ntfy.url');
$topic = (string) config('monitoring.alerts.ntfy.topic');
if ($url === '' || $topic === '') {
return;
}
$details = collect($context)
->map(fn (mixed $value, string $key): string => $key.': '.(is_scalar($value) || $value === null ? (string) $value : json_encode($value)))
->implode("\n");
try {
Http::timeout(5)
->connectTimeout(3)
->when(filled(config('monitoring.alerts.ntfy.token')), fn ($request) => $request->withToken((string) config('monitoring.alerts.ntfy.token')))
->post(rtrim($url, '/'), [
'topic' => $topic,
'title' => config('app.name').' ('.app()->environment().'): Betriebs-Alert',
'message' => Str::limit(trim($summary."\n\n".$details), 3500),
'priority' => (int) config('monitoring.alerts.ntfy.priority'),
'tags' => ['rotating_light'],
])
->throw();
} catch (Throwable $e) {
Log::channel('monitoring')->error('[monitoring] ntfy-Push konnte nicht versendet werden.', [
'summary' => $summary,
'error' => $e->getMessage(),
]);
}
}
}