feat: Aufräum-Job für Storys älter als 7 Tage
- /api/cron/cleanup-stories (CRON_SECRET): löscht Storys älter als 7 Tage samt Aufrufen, Pfoten, Kommentaren, Supabase-Bild und Mux-Asset; max. 200 pro Lauf, Fehler einzelner Storys brechen den Lauf nicht ab - gemeinsame Funktion deleteStoryWithMedia (src/lib/story-cleanup.ts), auch von stories.delete genutzt - Datenschutzerklärung Abschnitt 6: Storys spätestens nach 7 Tagen gelöscht - Datenexport: Story-Block heißt "stories" statt "activeStories" - CLAUDE.md: Cron-Jobs laufen über die NAS-Crontab + docker/run-cron.sh (der alte Hinweis "nichts ruft trim-feeds auf" war veraltet) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ac664d488d
commit
a01c58e5f0
8 files changed
+170
-21
No files matched your search
@@ -104,7 +104,7 @@ Despite `next.config.ts`'s `output: "standalone"` and the original stack researc
|
||||
|
||||
**Runs as 3 load-balanced replicas, not a single container (since 2026-08-16, Gitea #26).** `docker/docker-compose.yml` defines `pawfeed-1`/`pawfeed-2`/`pawfeed-3` (via the `x-pawfeed-common` YAML anchor) instead of one `pawfeed` service — Next.js standalone output is single-process (`node server.js`), so one container only ever used one CPU core regardless of how many the NAS has. A load test on 2026-08-15 hit a hard ceiling at ~60–65 req/sec with one core pegged at 133% while 3 cores sat idle; splitting into 3 replicas fixed it (confirmed via a follow-up load test showing ~100% CPU spread evenly across all three). Nginx Proxy Manager (container `nginx-app-1` on this NAS, admin UI at `192.168.1.222:81`) load-balances across them via a `least_conn` upstream block — that block lives in `/Docker-Data/nginxproxymanager/data/nginx/custom/http_top.conf` on the NAS host (an nginx `upstream {}` is only valid in the `http{}` context, which NPM's per-host "Custom Nginx Configuration" field can't reach — that field only writes into the `server{}`/`location{}` context, and holds the `proxy_pass http://pawfeed_upstream;` override for the `pawfeed.org` Proxy Host instead). Full runbook, decisions, and risk notes: `docker/SCALING-ROADMAP.md`. **Deploying a config or code change means rebuilding all 3 replicas** — there is no separate single-container path anymore, and NPM's proxy target is `pawfeed_upstream`, not a bare `pawfeed:3000` hostname. Use `./docker/rolling-deploy.sh` for deploys against the live site — it rebuilds the shared `pawfeed:latest` image once, then restarts `pawfeed-1`/`2`/`3` one at a time, gated on each becoming `healthy` per the Docker `healthcheck` (`GET /api/health`, a dependency-free liveness check — see `src/app/api/health/route.ts`) before moving to the next, so at least 2 replicas always serve traffic. Verified zero-downtime on 2026-08-16 (continuous curl monitoring showed unbroken HTTP 200 through a full rolling deploy). `docker compose up -d --build` (`start.sh`) still works but restarts all 3 at once — only use it for first-time setup or when a brief outage is acceptable. `src/lib/prisma.ts`'s Prisma pg pool size is capped per-replica via `DB_POOL_MAX` (compose sets `10`) so 3 replicas stay well under the Supabase pooler's client-connection limit.
|
||||
|
||||
`src/app/api/cron/trim-feeds/route.ts` trims each pet's Redis feed sorted set to the 90-day retention window and expects a `CRON_SECRET` bearer token. `vercel.json`'s `crons` array that points at it is **inert** on this self-hosted deployment — nothing calls this route yet. It needs an external trigger (e.g. a NAS-side cron job hitting the route with the secret header) before it actually runs.
|
||||
**Cron jobs run from the NAS crontab** (user `daniel`, `crontab -l`), not from `vercel.json` (whose `crons` array is inert here). Each entry calls `docker/run-cron.sh /api/cron/<name>`, which reads `CRON_SECRET` from `docker/.env`, hits the route with the bearer token via the DDNS host (`--resolve` to localhost — plain `pawfeed.org` fails TLS from the NAS) and logs every run with status + body to `docker/cron.log`. Current schedule: `trim-feeds` 04:00 (Redis feeds → 90 days), `cleanup-stories` 04:30 (deletes stories older than 7 days incl. views, paws, comments, Supabase image and Mux asset — `src/lib/story-cleanup.ts`, max 200 per run), `anniversaries` 08:00, `pet-suggestions` Mondays 09:00, plus `docker/backup-db.sh` 03:00. A new cron route needs a new crontab line on the NAS — it does not run otherwise.
|
||||
|
||||
### Directories that are not app code
|
||||
|
||||
|
||||
+1
-1
@@ -159,7 +159,7 @@ Neu 7:
|
||||
- [x] Nutzerfeedback - Story löschbar ? wie kann man die story löschen, falls man mal was falsches in die story geladen hat ?
|
||||
→ Gab es bisher nirgends. Neu: Server `stories.delete` (nur Owner; löscht Aufrufe — `StoryView` hat bewusst kein Cascade —, dann die Story, Pfoten/Kommentare per Cascade; danach Bild in Supabase Storage bzw. Mux-Asset best-effort). Web: Papierkorb neben der Zuschauerzahl in der eigenen Story + Rückfrage (`AlertDialog`), Bild-Timer pausiert während der Rückfrage, gelöscht wird die beim Antippen gemerkte Story-ID. App: gleicher Papierkorb + native Rückfrage, Timer pausiert. Nach dem Löschen springt der Viewer zur nächsten Story bzw. schließt, wenn keine mehr da ist. 5 neue Tests in `src/__tests__/stories.test.ts`. Nicht auf einem Gerät getestet. Commit `81d9c6d`, live (Web + OTA Runtime 1.0.6: Android `49757586-c443-4952-a679-c66a4225ef82`, iOS `48d22b11-abc9-4c75-be52-a122b0130c5e`).
|
||||
- [ ] Storys nur für Ersteller länger einsehbar wegen den Kommentaren (7Tage)
|
||||
→ Noch offen. Befund: abgelaufene Storys werden nie gelöscht (Einträge, Bilder, Mux-Videos bleiben liegen) — Vorschlag: grauer Ring "Deine Story" 7 Tage für den Ersteller, danach Aufräum-Cron (braucht einen Auslöser auf dem NAS, die bestehenden Cron-Routen haben keinen) + Satz unter "Speicherdauer" in der Datenschutzerklärung.
|
||||
→ Noch offen. Befund: abgelaufene Storys werden nie gelöscht (Einträge, Bilder, Mux-Videos bleiben liegen) — Vorschlag: grauer Ring "Deine Story" 7 Tage für den Ersteller, danach Aufräum-Cron (braucht einen Auslöser auf dem NAS, die bestehenden Cron-Routen haben keinen) + Satz unter "Speicherdauer" in der Datenschutzerklärung. **Teil erledigt (02.10.):** Aufräum-Job gebaut — `/api/cron/cleanup-stories` löscht Storys älter als 7 Tage komplett (Aufrufe, Pfoten, Kommentare, Bild, Mux-Video; gemeinsame Funktion `src/lib/story-cleanup.ts`, auch von „Story löschen“ genutzt), täglich 04:30 über die bestehende NAS-Crontab (`docker/run-cron.sh`, Log in `docker/cron.log`); Datenschutzerklärung Abschnitt 6 ergänzt. Offen bleibt nur die 7-Tage-Ansicht für den Ersteller.
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* /api/cron/cleanup-stories — löscht Storys, die älter als 7 Tage sind.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
const mockDeleteFiles = vi.fn().mockResolvedValue(undefined);
|
||||
vi.mock("@/lib/supabase-storage", () => ({ deleteFiles: (...a: unknown[]) => mockDeleteFiles(...a) }));
|
||||
const mockMuxDelete = vi.fn().mockResolvedValue(undefined);
|
||||
vi.mock("@/lib/mux", () => ({ mux: { video: { assets: { delete: (...a: unknown[]) => mockMuxDelete(...a) } } } }));
|
||||
|
||||
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
|
||||
|
||||
const mockPrisma = createMockPrisma();
|
||||
// Getter: vi.mock wird nach oben gehoben, mockPrisma existiert erst beim Zugriff.
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
get prisma() {
|
||||
return mockPrisma;
|
||||
},
|
||||
}));
|
||||
|
||||
import { GET } from "@/app/api/cron/cleanup-stories/route";
|
||||
|
||||
const request = (auth?: string) =>
|
||||
new Request("https://pawfeed.org/api/cron/cleanup-stories", { headers: auth ? { authorization: auth } : {} });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.CRON_SECRET = "test-secret";
|
||||
mockPrisma.$transaction.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe("GET /api/cron/cleanup-stories", () => {
|
||||
it("rejects requests without the cron secret", async () => {
|
||||
expect((await GET(request())).status).toBe(401);
|
||||
expect((await GET(request("Bearer wrong"))).status).toBe(401);
|
||||
expect(mockPrisma.story.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes stories older than 7 days with their media", async () => {
|
||||
mockPrisma.story.findMany.mockResolvedValue([
|
||||
{ id: "old-photo", storageKey: "stories/a.jpg", muxAssetId: null },
|
||||
{ id: "old-video", storageKey: null, muxAssetId: "asset-1" },
|
||||
]);
|
||||
|
||||
const res = await GET(request("Bearer test-secret"));
|
||||
|
||||
expect(await res.json()).toEqual({ ok: true, deleted: 2, failed: 0, more: false });
|
||||
const where = mockPrisma.story.findMany.mock.calls[0][0].where;
|
||||
const cutoffAgeDays = (Date.now() - where.createdAt.lt.getTime()) / (24 * 60 * 60 * 1000);
|
||||
expect(Math.round(cutoffAgeDays)).toBe(7);
|
||||
expect(mockPrisma.storyView.deleteMany).toHaveBeenCalledWith({ where: { storyId: "old-photo" } });
|
||||
expect(mockDeleteFiles).toHaveBeenCalledWith(["stories/a.jpg"]);
|
||||
expect(mockMuxDelete).toHaveBeenCalledWith("asset-1");
|
||||
});
|
||||
|
||||
it("keeps going when one story fails and reports it", async () => {
|
||||
mockPrisma.story.findMany.mockResolvedValue([
|
||||
{ id: "s1", storageKey: null, muxAssetId: null },
|
||||
{ id: "s2", storageKey: null, muxAssetId: null },
|
||||
]);
|
||||
mockPrisma.$transaction.mockRejectedValueOnce(new Error("db hiccup")).mockResolvedValueOnce([]);
|
||||
|
||||
const body = await (await GET(request("Bearer test-secret"))).json();
|
||||
|
||||
expect(body).toEqual({ ok: false, deleted: 1, failed: 1, more: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { timingSafeStringEqual } from "@/lib/timing-safe-compare";
|
||||
import { STORY_RETENTION_DAYS, deleteStoryWithMedia } from "@/lib/story-cleanup";
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
// Pro Lauf begrenzt: run-cron.sh bricht nach 60 s ab, und jede Story kostet
|
||||
// bis zu zwei externe Löschaufrufe (Supabase, Mux). Ein Rückstand wird über
|
||||
// die folgenden Tage abgebaut.
|
||||
const BATCH_SIZE = 200;
|
||||
|
||||
function authorized(req: Request): boolean {
|
||||
const secret = process.env.CRON_SECRET;
|
||||
if (!secret) return false;
|
||||
return timingSafeStringEqual(req.headers.get("authorization") ?? "", `Bearer ${secret}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht Storys, die älter als STORY_RETENTION_DAYS sind, endgültig — vorher
|
||||
* blieben abgelaufene Storys samt Bildern und Mux-Videos für immer liegen
|
||||
* („lazy delete“ hat sie nur ausgeblendet). Ausgelöst täglich vom NAS-Crontab
|
||||
* über docker/run-cron.sh.
|
||||
*/
|
||||
export async function GET(req: Request) {
|
||||
if (!authorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const cutoff = new Date(Date.now() - STORY_RETENTION_DAYS * DAY_MS);
|
||||
const stories = await prisma.story.findMany({
|
||||
where: { createdAt: { lt: cutoff } },
|
||||
select: { id: true, storageKey: true, muxAssetId: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: BATCH_SIZE,
|
||||
});
|
||||
|
||||
let deleted = 0;
|
||||
let failed = 0;
|
||||
for (const story of stories) {
|
||||
try {
|
||||
await deleteStoryWithMedia(prisma, story);
|
||||
deleted++;
|
||||
} catch (err) {
|
||||
failed++;
|
||||
console.error("[cron/cleanup-stories] delete failed", story.id, err);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: failed === 0, deleted, failed, more: stories.length === BATCH_SIZE });
|
||||
}
|
||||
@@ -217,6 +217,11 @@ export default function DatenschutzPage() {
|
||||
keine gesetzlichen Aufbewahrungspflichten entgegenstehen. Kontodaten werden nach
|
||||
Löschung des Kontos innerhalb von 30 Tagen gelöscht.
|
||||
</p>
|
||||
<p className="mt-3">
|
||||
Storys sind 24 Stunden für andere sichtbar. Spätestens 7 Tage nach dem Veröffentlichen
|
||||
löschen wir sie automatisch endgültig, zusammen mit Bild bzw. Video, Aufrufen, Pfoten und
|
||||
Kommentaren. Sie können eine eigene Story jederzeit vorher selbst löschen.
|
||||
</p>
|
||||
<p className="mt-3">
|
||||
Technische Fehlerberichte (Absturz-/Fehlerdaten inkl. IP-Adresse, siehe Abschnitt 2)
|
||||
werden automatisiert nach 30 Tagen gelöscht. Dieser Zeitraum ist nach unserer Erfahrung
|
||||
|
||||
@@ -38,7 +38,7 @@ export async function buildDataExport(prisma: PrismaClient, ownerId: string) {
|
||||
include: { images: true, milestone: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
stories: { orderBy: { createdAt: "asc" } }, // only currently-active ones remain (lazy-delete)
|
||||
stories: { orderBy: { createdAt: "asc" } }, // max. 7 Tage alt — ältere löscht /api/cron/cleanup-stories
|
||||
comments: { orderBy: { createdAt: "asc" } },
|
||||
reactions: true,
|
||||
reposts: true,
|
||||
@@ -173,7 +173,7 @@ export async function buildDataExport(prisma: PrismaClient, ownerId: string) {
|
||||
images: post.images.map((img) => getMediaUrl(img.storageKey)),
|
||||
milestone: post.milestone,
|
||||
})),
|
||||
activeStories: pet.stories.map((s) => ({
|
||||
stories: pet.stories.map((s) => ({
|
||||
mediaUrl: getMediaUrl(s.storageKey),
|
||||
createdAt: s.createdAt,
|
||||
expiresAt: s.expiresAt,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import "server-only";
|
||||
import type { PrismaClient } from "@prisma/client";
|
||||
import { deleteFiles } from "@/lib/supabase-storage";
|
||||
import { mux } from "@/lib/mux";
|
||||
|
||||
/**
|
||||
* Wie lange eine Story insgesamt gespeichert bleibt: 24 h für alle sichtbar,
|
||||
* danach nur noch für den Ersteller (geplant, siehe mobile/found.md), nach
|
||||
* 7 Tagen löscht /api/cron/cleanup-stories sie endgültig. Steht so auch in
|
||||
* der Datenschutzerklärung (Abschnitt 6 „Speicherdauer“).
|
||||
*/
|
||||
export const STORY_RETENTION_DAYS = 7;
|
||||
|
||||
export type DeletableStory = {
|
||||
id: string;
|
||||
storageKey: string | null;
|
||||
muxAssetId: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Löscht eine Story vollständig: Aufrufe (StoryView hat bewusst kein
|
||||
* onDelete: Cascade, D-08), dann die Story — Pfoten und Kommentare hängen per
|
||||
* Cascade dran. Bild in Supabase Storage und Mux-Asset danach best-effort:
|
||||
* ein Fehler dort wird geloggt, lässt das Löschen aber nicht scheitern.
|
||||
*/
|
||||
export async function deleteStoryWithMedia(prisma: PrismaClient, story: DeletableStory): Promise<void> {
|
||||
await prisma.$transaction([
|
||||
prisma.storyView.deleteMany({ where: { storyId: story.id } }),
|
||||
prisma.story.delete({ where: { id: story.id } }),
|
||||
]);
|
||||
|
||||
if (story.storageKey) {
|
||||
await deleteFiles([story.storageKey]).catch((err) => console.error("[stories] storage delete failed", err));
|
||||
}
|
||||
if (story.muxAssetId) {
|
||||
await mux.video.assets.delete(story.muxAssetId).catch((err) => console.error("[stories] mux delete failed", err));
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
createSignedUploadUrl,
|
||||
ALLOWED_CONTENT_TYPES,
|
||||
MAX_FILE_SIZE,
|
||||
deleteFiles,
|
||||
} from "@/lib/supabase-storage";
|
||||
import { deleteStoryWithMedia } from "@/lib/story-cleanup";
|
||||
import { randomUUID } from "crypto";
|
||||
import { petIdentitySelect } from "@/repositories/pet-repository";
|
||||
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
|
||||
@@ -444,11 +444,8 @@ export const storiesRouter = router({
|
||||
}),
|
||||
|
||||
/**
|
||||
* Owner löscht eine eigene Story (auch eine abgelaufene). Entfernt Aufrufe
|
||||
* (StoryView hat bewusst kein onDelete: Cascade, D-08), dann die Story —
|
||||
* Pfoten und Kommentare hängen per Cascade dran. Bild in Supabase Storage
|
||||
* und Mux-Asset werden danach best-effort gelöscht: ein Fehler dort darf
|
||||
* das Löschen für den Nutzer nicht scheitern lassen (nur geloggt).
|
||||
* Owner löscht eine eigene Story (auch eine abgelaufene) — samt Aufrufen,
|
||||
* Pfoten, Kommentaren, Bild und Mux-Asset, siehe deleteStoryWithMedia().
|
||||
*/
|
||||
delete: protectedProcedure
|
||||
.use(rateLimited("stories.delete", 20, 60))
|
||||
@@ -461,17 +458,7 @@ export const storiesRouter = router({
|
||||
if (!story) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
await assertPetOwnership(ctx.prisma, story.petId, ctx.userId);
|
||||
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.storyView.deleteMany({ where: { storyId: story.id } }),
|
||||
ctx.prisma.story.delete({ where: { id: story.id } }),
|
||||
]);
|
||||
|
||||
if (story.storageKey) {
|
||||
await deleteFiles([story.storageKey]).catch((err) => console.error("[stories] storage delete failed", err));
|
||||
}
|
||||
if (story.muxAssetId) {
|
||||
await mux.video.assets.delete(story.muxAssetId).catch((err) => console.error("[stories] mux delete failed", err));
|
||||
}
|
||||
await deleteStoryWithMedia(ctx.prisma, story);
|
||||
return { deleted: true };
|
||||
}),
|
||||
|
||||
|
||||
Reference in new issue
Block a user