Rundmail-Versand blockweise aus dem Browser statt in einem Request
Bei ~150 Empfängern lief der synchrone SMTP-Versand in die Zeitlimits des Shared Hosts; bei Abbruch gingen bereits verschickte Mails ins Leere und der Protokolleintrag fehlte. Jetzt verschickt jeder Aufruf 10 Mails, der Fortschritt liegt in der Session und wird pro Empfänger gesichert. Die Fortschrittsseite stößt die Blöcke per fetch an, ein offener Rest lässt sich auf der Übersicht fortsetzen. Ein Cron-Job ist dafür nicht nötig.
This commit is contained in:
parent
8ff2287419
commit
744a68fcdb
5 changed files with 181 additions and 22 deletions
|
|
@ -258,6 +258,14 @@ Rundmails und Erinnerungen werden per SMTP verschickt. Konfiguriert wird das üb
|
|||
|
||||
Lokal fängt [Mailpit](http://localhost:8025) alle Mails ab, es wird nichts an echte Adressen verschickt.
|
||||
|
||||
**Blockweiser Versand:** Rundmails gehen nicht mehr in einem einzigen Request raus (das
|
||||
lief bei ~150 Empfängern in die Zeitlimits des Shared Hosts). Der Versand wird in Blöcken
|
||||
von 10 Mails aus dem Browser angestoßen (`action=batch`, Fortschritt in der Session), der
|
||||
Admin sieht eine Fortschrittsanzeige. Bricht der Request ab, bleibt der Rest in der
|
||||
Session erhalten und ist auf der Rundmail-Übersicht über „Versand fortsetzen“ wieder
|
||||
aufrufbar – ein Cron-Job ist dafür nicht nötig. Der Protokolleintrag entsteht erst nach
|
||||
dem letzten Block, deshalb nach einem Abbruch immer erst fortsetzen statt neu senden.
|
||||
|
||||
## Erinnerungsmails (Cron-Job)
|
||||
|
||||
Spieler mit fehlenden Tipps oder fehlendem Joker bekommen automatisch eine Erinnerung. Ausgelöst wird das über eine von außen erreichbare Web-Route, die ein Cron-Job auf einem beliebigen Rechner aufruft:
|
||||
|
|
|
|||
|
|
@ -10,13 +10,13 @@ Diese Datei ersetzt die Erkundung. Erst hier nachschlagen, dann gezielt mit
|
|||
Abschnitt zu lesen. `docs/legacy/` ist absichtlich ausgeblendet (siehe
|
||||
`.ignore`); dort liegt der alte Laravel-Stand.
|
||||
|
||||
Umfang: 11436 Zeilen in 66 Dateien.
|
||||
Umfang: 11504 Zeilen in 66 Dateien.
|
||||
|
||||
## Einstiegspunkte
|
||||
|
||||
| Datei | Zeilen | Zweck |
|
||||
|---|---|---|
|
||||
| `tippspiel/public/index.php` | 1206 | Front-Controller; Routing ist eine if/elseif-Kette auf `?page=` |
|
||||
| `tippspiel/public/index.php` | 1289 | Front-Controller; Routing ist eine if/elseif-Kette auf `?page=` |
|
||||
| `tippspiel/src/autoload.php` | 26 | PSR-4-artiger Autoloader für `App\` |
|
||||
| `tools/schema.sql` | 204 | Schema der neuen DB (Tabellen, Indizes) |
|
||||
| `tippspiel/public/sw.js` | 114 | Service Worker für Web-Push |
|
||||
|
|
@ -49,11 +49,11 @@ Umfang: 11436 Zeilen in 66 Dateien.
|
|||
| `admin_seasons` | Admin | `admin/seasons` | 586 |
|
||||
| `admin_rounds` | Admin | `admin/rounds` | 696 |
|
||||
| `admin_roundmails` | Admin | `admin/roundmails` | 804 |
|
||||
| `admin_users` | Admin | `admin/users` | 871 |
|
||||
| `round` | Login | `round` | 975 |
|
||||
| `ranking` | Login | `ranking` | 1034 |
|
||||
| `questions` | Login | `questions` | 1099 |
|
||||
| `home` | Login | `home` | 1162 |
|
||||
| `admin_users` | Admin | `admin/users` | 954 |
|
||||
| `round` | Login | `round` | 1058 |
|
||||
| `ranking` | Login | `ranking` | 1117 |
|
||||
| `questions` | Login | `questions` | 1182 |
|
||||
| `home` | Login | `home` | 1245 |
|
||||
|
||||
Alle übrigen Pfade laufen auf `home` bzw. 404. Reihenfolge und Bedingungen
|
||||
stehen in `tippspiel/public/index.php`. `(Fallback)` markiert Seiten eines
|
||||
|
|
@ -70,7 +70,7 @@ ohne View.
|
|||
| `tippspiel/src/Core/ErrorHandler.php` | 75 | Globale Fehlerbehandlung: Log + lesbare Fehlerseite statt leerem 500 | `register()`, `handleException($e)`, `handleFatal()`, `render()` |
|
||||
| `tippspiel/src/Core/ErrorLog.php` | 52 | PHP-Fehlerdatei außerhalb des Web-Roots, Rotation bei 5 MB | `path()`, `rotateIfNeeded($maxBytes)` |
|
||||
| `tippspiel/src/Core/Iban.php` | 51 | IBAN normalisieren und prüfen | `normalize($value)`, `isValid($value)` |
|
||||
| `tippspiel/src/Core/Mailer.php` | 159 | Minimaler SMTP-Client ohne externe Abhängigkeiten | `send($recipients, $subject, $html, $replyTo)` |
|
||||
| `tippspiel/src/Core/Mailer.php` | 167 | Minimaler SMTP-Client ohne externe Abhängigkeiten | `send($recipients, $subject, $html, $replyTo, …)` |
|
||||
| `tippspiel/src/Core/ResultFetcher.php` | 535 | Ergebnisse von openligadb und API-Football holen und eintragen | `openligadb($apply, $check)`, `apifootball($apply, $check)` |
|
||||
| `tippspiel/src/Core/WebPush.php` | 446 | Web-Push (VAPID, RFC 8291) ohne externe Abhängigkeiten | `isConfigured()`, `publicKey()`, `subject()`, `isValidEndpoint($endpoint)`, `isValidKeyMaterial($p256dh, $auth)`, `send($subscription, $payload)`, `encrypt($payload, $p256dh, $auth, $salt, …)` |
|
||||
|
||||
|
|
@ -100,7 +100,7 @@ ohne View.
|
|||
| `tippspiel/src/Views/admin/accounts.php` | 108 | Konto- und Ausschüttungsübersicht |
|
||||
| `tippspiel/src/Views/admin/fetcher_activity.php` | 64 | Protokoll des Ergebnis-Fetchers |
|
||||
| `tippspiel/src/Views/admin/message.php` | 34 | Mitteilung an alle Spieler setzen |
|
||||
| `tippspiel/src/Views/admin/roundmails.php` | 212 | Rundmails verfassen und versenden |
|
||||
| `tippspiel/src/Views/admin/roundmails.php` | 272 | Rundmails verfassen und versenden |
|
||||
| `tippspiel/src/Views/admin/rounds.php` | 206 | Spiele und Ergebnisse eintragen |
|
||||
| `tippspiel/src/Views/admin/seasons.php` | 217 | Saisons verwalten |
|
||||
| `tippspiel/src/Views/admin/users.php` | 190 | Benutzer verwalten (inkl. Tipp-/Joker-Lücken) |
|
||||
|
|
|
|||
|
|
@ -805,6 +805,81 @@ if ($page === 'reminder') {
|
|||
Auth::requireLogin();
|
||||
Auth::requireAdmin();
|
||||
|
||||
// Versand erfolgt blockweise aus dem Browser: Ein Request verschickt nur
|
||||
// BATCH_SIZE Mails. So bleibt jeder Aufruf deutlich unter den Zeitlimits
|
||||
// des Shared Hosts, und ein Abbruch verliert höchstens einen Block.
|
||||
$jobKey = 'roundmail_job';
|
||||
$batchSize = 10;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'batch') {
|
||||
@set_time_limit(120);
|
||||
ignore_user_abort(true);
|
||||
$wantsJson = ($_POST['format'] ?? '') === 'json';
|
||||
$job = $_SESSION[$jobKey] ?? null;
|
||||
|
||||
if (!$job) {
|
||||
if ($wantsJson) {
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['done' => true, 'redirect' => '/index.php?page=admin_roundmails']);
|
||||
exit;
|
||||
}
|
||||
header('Location: /index.php?page=admin_roundmails');
|
||||
exit;
|
||||
}
|
||||
|
||||
$batch = array_splice($job['queue'], 0, $batchSize);
|
||||
$error = null;
|
||||
try {
|
||||
Mailer::send($batch, $job['topic'], $job['html'], $job['reply_to'],
|
||||
function ($email, $ok) use (&$job, $jobKey) {
|
||||
$job[$ok ? 'sent' : 'failed'][] = $email;
|
||||
$_SESSION[$jobKey] = $job;
|
||||
// Fortschritt sofort sichern: bricht der Request ab, ist er erhalten
|
||||
session_write_close();
|
||||
session_start();
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
// Der Block gilt als nicht versendet und wird beim nächsten Aufruf wiederholt
|
||||
$job['queue'] = array_merge($batch, $job['queue']);
|
||||
$error = $e->getMessage();
|
||||
}
|
||||
|
||||
$total = count($job['queue']) + count($job['sent']) + count($job['failed']);
|
||||
$done = empty($job['queue']);
|
||||
$redirect = '/index.php?page=admin_roundmails';
|
||||
|
||||
if ($done) {
|
||||
if (!empty($job['sent'])) {
|
||||
Roundmail::create((int)$job['user_id'], $job['sent'], $job['topic'], $job['html'], (int)$job['season_id']);
|
||||
}
|
||||
$_SESSION['admin_message'] = 'Mail an ' . count($job['sent']) . ' Empfänger versendet.';
|
||||
if (!empty($job['failed'])) {
|
||||
$_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $job['failed']);
|
||||
}
|
||||
unset($_SESSION[$jobKey]);
|
||||
} else {
|
||||
$_SESSION[$jobKey] = $job;
|
||||
$redirect = '/index.php?page=admin_roundmails&send=1';
|
||||
}
|
||||
|
||||
if ($wantsJson) {
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode([
|
||||
'done' => $done,
|
||||
'sent' => count($job['sent']),
|
||||
'failed' => count($job['failed']),
|
||||
'total' => $total,
|
||||
'remaining' => count($job['queue']),
|
||||
'error' => $error,
|
||||
'redirect' => $redirect,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
header('Location: ' . $redirect);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$redirect = '/index.php?page=admin_roundmails';
|
||||
try {
|
||||
|
|
@ -823,17 +898,18 @@ if ($page === 'reminder') {
|
|||
|
||||
$sender = Auth::user();
|
||||
$currentSeason = Season::getViewSeason();
|
||||
$html = Roundmail::textToHtml($text);
|
||||
$failed = Mailer::send($recipients['valid'], $topic, $html, $sender['email'] ?? null);
|
||||
$sent = array_values(array_diff($recipients['valid'], $failed));
|
||||
if (!empty($sent)) {
|
||||
Roundmail::create((int)$sender['id'], $sent, $topic, $html, $currentSeason ? (int)$currentSeason['id'] : 0);
|
||||
}
|
||||
|
||||
$_SESSION['admin_message'] = 'Mail an ' . count($sent) . ' Empfänger versendet.';
|
||||
if (!empty($failed)) {
|
||||
$_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $failed);
|
||||
}
|
||||
$_SESSION[$jobKey] = [
|
||||
'user_id' => (int)$sender['id'],
|
||||
'reply_to' => $sender['email'] ?? null,
|
||||
'topic' => $topic,
|
||||
'html' => Roundmail::textToHtml($text),
|
||||
'season_id' => $currentSeason ? (int)$currentSeason['id'] : 0,
|
||||
'queue' => array_values($recipients['valid']),
|
||||
'sent' => [],
|
||||
'failed' => [],
|
||||
];
|
||||
$_SESSION['admin_message'] = 'Versand läuft: ' . count($recipients['valid']) . ' Empfänger.';
|
||||
$redirect = '/index.php?page=admin_roundmails&send=1';
|
||||
} catch (\Throwable $e) {
|
||||
$_SESSION['admin_error'] = 'Fehler: ' . $e->getMessage();
|
||||
$_SESSION['admin_form'] = $_POST;
|
||||
|
|
@ -852,6 +928,13 @@ if ($page === 'reminder') {
|
|||
$compose = isset($_GET['new']);
|
||||
$excludeReminders = ($_GET['hide_reminders'] ?? '') === '1';
|
||||
|
||||
// Offener Versand aus einer früheren Sitzung (Abbruch, Timeout, Browser zu)
|
||||
$sendJob = $_SESSION[$jobKey] ?? null;
|
||||
$sending = isset($_GET['send']) && $sendJob;
|
||||
if ($sending) {
|
||||
$sendTotal = count($sendJob['queue']) + count($sendJob['sent']) + count($sendJob['failed']);
|
||||
}
|
||||
|
||||
if ($compose) {
|
||||
$currentSeason = Season::getViewSeason();
|
||||
$tippableRound = $currentSeason ? Round::getFirstTippable($currentSeason['id']) : null;
|
||||
|
|
@ -859,7 +942,7 @@ if ($page === 'reminder') {
|
|||
$baseUrl = rtrim(getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')), '/');
|
||||
$tippLink = $baseUrl . '/';
|
||||
$mailConfigured = (bool)getenv('SMTP_HOST');
|
||||
} elseif (!$viewMail) {
|
||||
} elseif (!$viewMail && !$sending) {
|
||||
$perPage = 20;
|
||||
$totalMails = Roundmail::count($excludeReminders);
|
||||
$totalPages = max(1, (int)ceil($totalMails / $perPage));
|
||||
|
|
|
|||
|
|
@ -20,10 +20,12 @@ class Mailer {
|
|||
* @param string $subject
|
||||
* @param string $html
|
||||
* @param string|null $replyTo
|
||||
* @param callable|null $onEach Wird nach jedem Empfänger mit ($email, $ok) aufgerufen,
|
||||
* damit der Aufrufer den Fortschritt sofort sichern kann
|
||||
* @return string[] Empfänger, an die nicht versendet werden konnte
|
||||
* @throws \Exception bei Verbindungs- oder Anmeldefehlern
|
||||
*/
|
||||
public static function send(array $recipients, $subject, $html, $replyTo = null) {
|
||||
public static function send(array $recipients, $subject, $html, $replyTo = null, ?callable $onEach = null) {
|
||||
$mailer = new self();
|
||||
$mailer->connect();
|
||||
|
||||
|
|
@ -32,8 +34,14 @@ class Mailer {
|
|||
foreach ($recipients as $to) {
|
||||
try {
|
||||
$mailer->sendOne($to, $subject, $html, $replyTo);
|
||||
if ($onEach) {
|
||||
$onEach($to, true);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$failed[] = $to;
|
||||
if ($onEach) {
|
||||
$onEach($to, false);
|
||||
}
|
||||
$mailer->command('RSET', [250]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -83,6 +83,58 @@ $reminderParam = ($excludeReminders ?? false) ? '&hide_reminders=1' : '';
|
|||
});
|
||||
</script>
|
||||
|
||||
<?php elseif ($sending): ?>
|
||||
|
||||
<h2>Mail wird versendet</h2>
|
||||
<p id="rm-progress-text"><?php echo count($sendJob['sent']); ?> von <?php echo (int)$sendTotal; ?> Empfängern versendet …</p>
|
||||
<progress id="rm-progress" max="<?php echo (int)$sendTotal; ?>" value="<?php echo count($sendJob['sent']); ?>" style="width: 100%; max-width: 520px;"></progress>
|
||||
<p id="rm-error" style="color: #b00;"></p>
|
||||
<p class="hint">Der Versand läuft blockweise (10 Mails pro Anfrage), damit der Server nicht in ein Zeitlimit läuft.
|
||||
Fenster bitte offen lassen. Ein Abbruch ist unschädlich: Der offene Rest lässt sich auf der Übersicht fortsetzen.</p>
|
||||
|
||||
<noscript>
|
||||
<form method="post" action="/index.php?page=admin_roundmails">
|
||||
<input type="hidden" name="action" value="batch">
|
||||
<button type="submit">Nächsten Block senden</button>
|
||||
</form>
|
||||
<p>Ohne JavaScript muss dieser Knopf für jeden Block erneut gedrückt werden.</p>
|
||||
</noscript>
|
||||
|
||||
<p><a href="/index.php?page=admin_roundmails">Zur Übersicht (Versand pausieren)</a></p>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var text = document.getElementById('rm-progress-text');
|
||||
var bar = document.getElementById('rm-progress');
|
||||
var errorBox = document.getElementById('rm-error');
|
||||
var attempts = 0;
|
||||
|
||||
function step() {
|
||||
var body = new FormData();
|
||||
body.append('action', 'batch');
|
||||
body.append('format', 'json');
|
||||
fetch('/index.php?page=admin_roundmails', {method: 'POST', body: body, credentials: 'same-origin'})
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (data) {
|
||||
attempts = 0;
|
||||
bar.max = data.total;
|
||||
bar.value = data.sent;
|
||||
text.textContent = data.sent + ' von ' + data.total + ' Empfängern versendet …';
|
||||
if (data.error) { errorBox.textContent = 'Hinweis: ' + data.error; }
|
||||
if (data.done) { window.location.href = data.redirect; return; }
|
||||
step();
|
||||
})
|
||||
.catch(function () {
|
||||
attempts++;
|
||||
if (attempts < 5) { setTimeout(step, 2000 * attempts); return; }
|
||||
text.textContent = 'Versand angehalten. Bitte die Seite neu laden, um fortzusetzen.';
|
||||
});
|
||||
}
|
||||
|
||||
step();
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php elseif ($viewMail): ?>
|
||||
|
||||
<h2><?php echo htmlspecialchars($viewMail['topic']); ?></h2>
|
||||
|
|
@ -100,6 +152,14 @@ $reminderParam = ($excludeReminders ?? false) ? '&hide_reminders=1' : '';
|
|||
|
||||
<p><a href="/index.php?page=admin_roundmails&new=1">Neue Mail schreiben</a></p>
|
||||
|
||||
<?php if (!empty($sendJob)): ?>
|
||||
<p style="color: #b00;">
|
||||
Ein Versand ist noch offen: <?php echo count($sendJob['sent']); ?> versendet,
|
||||
<?php echo count($sendJob['queue']); ?> offen.
|
||||
<a href="/index.php?page=admin_roundmails&send=1">Versand fortsetzen</a>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<label class="reminder-toggle">
|
||||
<input type="checkbox" id="toggle-reminders" <?php echo $excludeReminders ? 'checked' : ''; ?>>
|
||||
Erinnerungen ein/ausblenden
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue