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

@ -1 +1 @@
1305
1306

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

View file

@ -0,0 +1,76 @@
"""Forum-Antworten: Idempotenz gegen Doppelposts bei verlorener Antwort (Funkloch).
Szenario aus der Praxis: Eine Antwort wird serverseitig erstellt, aber die HTTP-
Antwort erreicht das Handy nicht (schlechtes Netz). Der Nutzer tippt erneut auf
Antworten". Mit stabiler client_uuid liefert der Retry denselben Post zurück —
statt 30-Sekunden-Cooldown-Fehler (429) oder Doppelpost.
Cooldown/Duplikat-Checks sind NICHT gestubbt client_time steuert die Zeitbasis.
"""
from __future__ import annotations
import secrets
def _mk_thread(client, headers, client_time):
r = client.post(
"/api/forum/threads",
headers=headers,
json={
"kategorie": "allgemein",
"titel": "Idempotenz-Thread",
"text": f"Genug langer Thread-Text {secrets.token_hex(6)}.",
"client_time": client_time,
},
)
assert r.status_code == 201, f"thread create: {r.status_code} {r.text}"
return r.json()
def _reply(client, headers, thread_id, text, client_time, client_uuid=None):
body = {"text": text, "client_time": client_time}
if client_uuid is not None:
body["client_uuid"] = client_uuid
return client.post(f"/api/forum/threads/{thread_id}/posts", headers=headers, json=body)
def test_retry_same_uuid_returns_same_post_no_cooldown(client, user):
h = user["headers"]
t = _mk_thread(client, h, "2026-06-19T10:00:00")
# 1. Antwort (60s nach Thread → kein Cooldown)
r1 = _reply(client, h, t["id"], "Oh ja das stimmt", "2026-06-19T10:01:00", client_uuid="uuid-A")
assert r1.status_code == 201, r1.text
pid = r1.json()["id"]
# Retry mit SELBER UUID, nur 5s später (läge im 30s-Cooldown) → idempotent,
# liefert denselben Post zurück, KEIN 429.
r2 = _reply(client, h, t["id"], "Oh ja das stimmt", "2026-06-19T10:01:05", client_uuid="uuid-A")
assert r2.status_code == 201, r2.text
assert r2.json()["id"] == pid, "Retry muss den bereits erstellten Post zurückliefern"
# Es darf nur EINE Antwort existieren (kein Doppelpost).
detail = client.get(f"/api/forum/threads/{t['id']}", headers=h).json()
assert detail["antworten"] == 1
assert len([p for p in detail["posts"] if not p.get("is_deleted")]) == 1
def test_cooldown_still_blocks_genuinely_new_reply(client, user):
h = user["headers"]
t = _mk_thread(client, h, "2026-06-19T10:00:00")
r1 = _reply(client, h, t["id"], "Erste Antwort", "2026-06-19T10:01:00", client_uuid="uuid-1")
assert r1.status_code == 201, r1.text
# Andere UUID + anderer Text, nur 10s später → echter Doppel-Post-Versuch → 429
r2 = _reply(client, h, t["id"], "Zweite Antwort", "2026-06-19T10:01:10", client_uuid="uuid-2")
assert r2.status_code == 429, f"Cooldown muss greifen: {r2.status_code} {r2.text}"
def test_reply_without_uuid_still_works(client, user):
"""Rückwärtskompatibel: Antwort ohne client_uuid bleibt 201."""
h = user["headers"]
t = _mk_thread(client, h, "2026-06-19T10:00:00")
r = _reply(client, h, t["id"], "Antwort ohne UUID", "2026-06-19T10:01:00")
assert r.status_code == 201, r.text