Forum: idempotente Antworten gegen Doppelpost/Cooldown-Fehler bei Funkloch (v1306)

Praxisfall: Antwort wird serverseitig erstellt, aber die HTTP-Antwort geht
unterwegs verloren (schlechtes Netz). UI zeigt Fehler statt Erfolg, Text bleibt
stehen -> Nutzer tippt erneut -> 2. Versuch laeuft in den 30s-Cooldown (429),
der bereits gepostete Beitrag bleibt unsichtbar.

- forum_posts.client_uuid (Migration). Reply mit stabiler client_uuid:
  Retry liefert den BEREITS erstellten Post zurueck (kein Cooldown/Doppelpost).
- Frontend: UUID bleibt ueber Retries stabil, Reset erst nach Erfolg; Foto-
  Doppel-Upload bei Retry verhindert.
- Anti-Spam-Cooldown bleibt fuer echte neue Posts aktiv.
- Tests: tests/test_forum_idempotency.py (Retry=selber Post, Cooldown greift,
  ohne UUID rueckwaertskompatibel).
This commit is contained in:
rene 2026-06-19 10:29:42 +02:00
parent 140140f690
commit 6ea3f50b05
9 changed files with 136 additions and 25 deletions

View file

@ -530,6 +530,8 @@ def _migrate(conn_factory):
("forum_posts", "foto_urls", "TEXT"),
("forum_posts", "is_deleted", "INTEGER NOT NULL DEFAULT 0"),
("forum_posts", "likes", "INTEGER NOT NULL DEFAULT 0"),
# Idempotenz: Client-UUID gegen Doppelposts bei verlorener Antwort (Funkloch)
("forum_posts", "client_uuid", "TEXT"),
# Users: Moderator-Flag + Forum-Standort
("users", "is_moderator", "INTEGER NOT NULL DEFAULT 0"),
("users", "forum_lat", "REAL"),

View file

@ -38,6 +38,7 @@ class ThreadCreate(BaseModel):
class PostCreate(BaseModel):
text: str = Field(..., min_length=1, max_length=10000)
client_time: Optional[str] = Field(None, max_length=64)
client_uuid: Optional[str] = Field(None, max_length=64) # Idempotenz-Schlüssel gegen Doppelposts
class ThreadPatch(BaseModel):
is_pinned: Optional[int] = None
@ -402,12 +403,30 @@ async def create_post(thread_id: int, data: PostCreate, user=Depends(get_current
if thread['is_deleted']:
raise HTTPException(404, "Thread nicht gefunden.")
# Idempotenz: Ein Retry mit derselben client_uuid (z.B. wenn die Antwort
# des 1. Versuchs im Funkloch verloren ging) liefert den BEREITS erstellten
# Post zurück — statt Cooldown-/Duplikat-Fehler oder Doppelpost. Der Client
# behält die UUID über Retries hinweg und setzt sie erst nach Erfolg zurück.
if data.client_uuid:
existing = conn.execute(
"""SELECT p.*, u.name AS autor_name, u.founder_number AS autor_founder_number
FROM forum_posts p
LEFT JOIN users u ON u.id = p.user_id
WHERE p.user_id=? AND p.client_uuid=? AND p.thread_id=?""",
(user["id"], data.client_uuid, thread_id)
).fetchone()
if existing:
ed = dict(existing)
ed['foto_urls'] = _parse_foto_urls(ed.get('foto_urls'))
ed['user_liked'] = _user_liked(conn, user["id"], 'post', ed['id'])
return ed
ct = safe_client_time(data.client_time)
_check_post_limits(user["id"], conn, data.text.strip(), user.get("created_at"), is_thread=False, now_client=ct)
cur = conn.execute(
"INSERT INTO forum_posts (thread_id, user_id, text, created_at) VALUES (?, ?, ?, ?)",
(thread_id, user['id'], data.text.strip(), ct)
"INSERT INTO forum_posts (thread_id, user_id, text, created_at, client_uuid) VALUES (?, ?, ?, ?, ?)",
(thread_id, user['id'], data.text.strip(), ct, data.client_uuid)
)
conn.execute(
"UPDATE forum_threads SET antworten = antworten + 1 WHERE id = ?",

View file

@ -86,14 +86,14 @@
<title>Ban Yaro</title>
<!-- Theme + theme-color Statusleiste vor CSS setzen -->
<script src="/js/boot-early.js?v=1305"></script>
<script src="/js/boot-early.js?v=1306"></script>
<!-- CSS: Reihenfolge ist wichtig — ?v= zwingt Browser zur Neuladung -->
<link rel="stylesheet" href="/css/design-system.css?v=1305">
<link rel="stylesheet" href="/css/layout.css?v=1305">
<link rel="stylesheet" href="/css/components.css?v=1305">
<link rel="stylesheet" href="/css/utilities.css?v=1305">
<link rel="stylesheet" href="/css/lists.css?v=1305">
<link rel="stylesheet" href="/css/design-system.css?v=1306">
<link rel="stylesheet" href="/css/layout.css?v=1306">
<link rel="stylesheet" href="/css/components.css?v=1306">
<link rel="stylesheet" href="/css/utilities.css?v=1306">
<link rel="stylesheet" href="/css/lists.css?v=1306">
</head>
<body>
@ -624,12 +624,12 @@
<div id="modal-container"></div>
<!-- JS: Reihenfolge ist wichtig — erst Basis, dann Features -->
<script src="/js/api.js?v=1305"></script>
<script src="/js/ui.js?v=1305"></script>
<script src="/js/app.js?v=1305"></script>
<script src="/js/worlds.js?v=1305"></script>
<script src="/js/offline-indicator.js?v=1305"></script>
<script src="/js/contact-form.js?v=1305"></script>
<script src="/js/api.js?v=1306"></script>
<script src="/js/ui.js?v=1306"></script>
<script src="/js/app.js?v=1306"></script>
<script src="/js/worlds.js?v=1306"></script>
<script src="/js/offline-indicator.js?v=1306"></script>
<script src="/js/contact-form.js?v=1306"></script>
<!-- Feature-Seiten werden lazy geladen -->
@ -639,7 +639,7 @@
<!-- Boot: Offline-Banner + SW-Registration (extrahiert für CSP) -->
<script src="/js/boot.js?v=1305"></script>
<script src="/js/boot.js?v=1306"></script>
</body>

View file

@ -3,7 +3,7 @@
Router, State-Management, Navigation, Initialisierung.
============================================================ */
const APP_VER = '1305'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
const APP_VER = '1306'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
const APP_VERSION = '1.6.0'; // ← semantische Version, wird bei make release gesetzt
window.APP_VER = APP_VER; // global verfügbar für andere Module (z.B. offline-indicator)
window.APP_VERSION = APP_VERSION;

View file

@ -751,20 +751,33 @@ function _fmtDate(iso) {
if (postsListEl) _bindPostActions(postsListEl, thread.id, uid, isMod);
// Reply abschicken
// Idempotenz-Schlüssel: bleibt über Retries STABIL und wird erst nach
// erfolgreichem Senden zurückgesetzt. So liefert ein Retry (z.B. wenn die
// Antwort des 1. Versuchs im Funkloch verloren ging) denselben Post zurück
// statt eines Cooldown-Fehlers/Doppelposts.
let _replyUuid = null;
document.getElementById('ft-reply')?.addEventListener('click', async () => {
const btn = document.getElementById('ft-reply');
const text = document.getElementById('forum-reply-text')?.value?.trim();
if (!text) { UI.toast.warning('Bitte Text eingeben.'); return; }
if (!_replyUuid) {
_replyUuid = (window.crypto && crypto.randomUUID)
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
await UI.asyncButton(btn, async () => {
const post = await API.forum.addPost(thread.id, { text, client_time: API.clientNow() });
const post = await API.forum.addPost(thread.id, { text, client_time: API.clientNow(), client_uuid: _replyUuid });
// Foto hochladen falls vorhanden
// Foto hochladen falls vorhanden — bei idempotentem Retry hat der Post
// seine Fotos bereits, dann NICHT erneut hochladen (kein Doppel-Upload).
const files = Array.from(document.getElementById('forum-reply-file')?.files || []);
for (const file of files.slice(0, 5)) {
try {
await API.forum.uploadPostFoto(post.id, file);
} catch (e) { /* Foto-Upload-Fehler ignorieren */ }
if (!post.foto_urls || post.foto_urls.length === 0) {
for (const file of files.slice(0, 5)) {
try {
await API.forum.uploadPostFoto(post.id, file);
} catch (e) { /* Foto-Upload-Fehler ignorieren */ }
}
}
thread.antworten = (thread.antworten || 0) + 1;
@ -782,6 +795,7 @@ function _fmtDate(iso) {
document.getElementById('forum-reply-text').value = '';
const previews = document.getElementById('forum-reply-previews');
if (previews) previews.innerHTML = '';
_replyUuid = null; // Erfolg → nächste Antwort bekommt eine frische UUID
UI.toast.success('Antwort gesendet.');
});
});

View file

@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<script src="/js/landing-init.js?v=1305"></script>
<script src="/js/landing-init.js?v=1306"></script>
<title>Ban Yaro — Die Hunde-App für Deutschland, Österreich & Schweiz</title>
<meta name="description" content="Ban Yaro: Die kostenlose All-in-One Hunde-App für DACH. Tagebuch, Giftköder-Alarm, Training mit KI, Forum, Wurfbörse, Stammbaum, Inzucht-Check — DSGVO-konform, offline-fähig, direkt im Browser oder als native iPhone-App (Ban Yaro Go).">
<meta name="keywords" content="Hunde App, Hunde Community, Wurfbörse, Züchter, Welpen kaufen, Stammbaum Hund, Inzuchtkoeffizient, Hundezucht, Impfpass Hund, Giftköder Alarm, Gassi Community, Hundetraining App, Hunde Forum, Hunde KI, Hundefilm Datenbank, Welpen Marktplatz">

View file

@ -4,7 +4,7 @@
============================================================ */
// ← EINZIGE Stelle für die Version — STATIC_ASSETS und CACHE_VERSION leiten sich ab
const VER = '1305';
const VER = '1306';
const CACHE_VERSION = `by-v${VER}`;
const CACHE_STATIC = `${CACHE_VERSION}-static`;
const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten