From 76cae446ab459212dcd525e8e1825512d71d7996 Mon Sep 17 00:00:00 2001 From: Landwelle Server Date: Thu, 3 Dec 2026 03:15:28 +0100 Subject: [PATCH] feat(platform): Go 1.27.4, native PostgreSQL, durable production queue and Gitea dashboard Separate database, scheduling, job queue, monitoring and Gitea packages. Preserve existing routes and KeyHelp cron; add migration 0051, integration tests and operational documentation. --- .env.example | 3 + .gitea/workflows/ci.yml | 4 +- CHANGELOG.md | 10 + Dockerfile | 6 +- README.md | 16 +- cmd/portal/admin.go | 48 ++--- cmd/portal/ai_audio_modules.go | 17 +- cmd/portal/ai_cron_scheduler_test.go | 5 +- cmd/portal/ai_jobs.go | 186 +++++++------------ cmd/portal/ai_jobs_stability_test.go | 9 +- cmd/portal/main.go | 33 +++- cmd/portal/main_test.go | 2 +- cmd/portal/media_favorites_test.go | 44 ++--- cmd/portal/operations_dashboard.go | 63 +++++++ cmd/portal/operations_dashboard_test.go | 23 +++ cmd/portal/postgres.go | 73 +++----- cmd/portal/production_queue.go | 194 ++++++++++++++++++++ cmd/portal/web/admin/dashboard.html | 32 ++++ cmd/portal/wish_audio_test.go | 8 +- cmd/portal/wishes.go | 2 + docs/ARCHITECTURE.md | 2 +- docs/CHATUEBERGABE.md | 6 +- docs/CURRENT_STATE.md | 6 +- docs/PLATFORM_MODERNIZATION.md | 54 ++++++ docs/PROJECT_STRUCTURE.md | 7 +- docs/README.md | 1 + docs/ROADMAP.md | 5 +- docs/TESTING.md | 6 +- go.mod | 12 +- go.sum | 26 +++ internal/database/pool.go | 71 +++++++ internal/database/pool_integration_test.go | 49 +++++ internal/giteastatus/status.go | 158 ++++++++++++++++ internal/giteastatus/status_test.go | 34 ++++ internal/jobqueue/queue.go | 121 ++++++++++++ internal/jobqueue/queue_integration_test.go | 139 ++++++++++++++ internal/monitoring/http.go | 75 ++++++++ internal/monitoring/http_test.go | 25 +++ internal/scheduler/schedule.go | 59 ++++++ internal/scheduler/schedule_test.go | 17 ++ migrations/0051_ai_production_queue.sql | 25 +++ scripts/test-postgres-integration.sh | 82 +++++++++ 42 files changed, 1497 insertions(+), 261 deletions(-) create mode 100644 cmd/portal/operations_dashboard.go create mode 100644 cmd/portal/operations_dashboard_test.go create mode 100644 cmd/portal/production_queue.go create mode 100644 docs/PLATFORM_MODERNIZATION.md create mode 100644 go.sum create mode 100644 internal/database/pool.go create mode 100644 internal/database/pool_integration_test.go create mode 100644 internal/giteastatus/status.go create mode 100644 internal/giteastatus/status_test.go create mode 100644 internal/jobqueue/queue.go create mode 100644 internal/jobqueue/queue_integration_test.go create mode 100644 internal/monitoring/http.go create mode 100644 internal/monitoring/http_test.go create mode 100644 internal/scheduler/schedule.go create mode 100644 internal/scheduler/schedule_test.go create mode 100644 migrations/0051_ai_production_queue.sql create mode 100755 scripts/test-postgres-integration.sh diff --git a/.env.example b/.env.example index bacad29..a2ae08d 100644 --- a/.env.example +++ b/.env.example @@ -113,3 +113,6 @@ LANDWELLE_YOUTUBE_CHANNEL_ID= # Öffentliche Stellenbörse / Jobsuche der Bundesagentur für Arbeit LANDWELLE_JOBS_API_BASE=https://rest.arbeitsagentur.de/jobboerse/jobsuche-service LANDWELLE_JOBS_API_KEY=jobboerse-jobsuche + +# Native PostgreSQL connection pool (3–32 connections; default 8). +LANDWELLE_DB_MAX_CONNECTIONS=8 diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 3761197..c7d970a 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.24.4' + go-version: '1.27.4' cache: false - name: Verify modules @@ -41,7 +41,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: '1.24.4' + go-version: '1.27.4' cache: false - name: Build portal diff --git a/CHANGELOG.md b/CHANGELOG.md index 2202b9d..abefe0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +## v1.5.83 – Plattformmodernisierung (03.12.2026) + +- Go 1.27.4 in Modul, Gitea CI und optionalem Container-Build. +- Native PostgreSQL-Anbindung mit pgx v5 und begrenztem Connection-Pool; der separate SQL-Migrator bleibt kompatibel. +- Eigenständige Pakete für Datenbank, Auftragsverarbeitung, Zeitplanung, API-Monitoring und Gitea-Abfrage. +- Persistente KI-Produktionswarteschlange für Nachrichtenstudio, Audio-Rubriken, Musikwünsche und KeyHelp-Cron; atomare Claims, Status und Fortschritt über Neustarts hinweg. +- Automatische Aufträge werden nach 30 Minuten Wartezeit nicht mehr ausgestrahlt; unterbrochene laufende Aufträge nach 15 Minuten als Fehler gekennzeichnet und nicht blind wiederholt. +- Dashboard: Datenbankpool, Cron-Heartbeat, Produktionsstatus und API-Messwerte, Gitea-Branch, Commit, Quellversion, CI-Ergebnis und Vergleich mit installiertem Build. +- Neue additive Migration 0051. Keine Änderung der historischen Migrationen und keine Löschung produktiver Inhalte. + ## Repository-Pflege – Projektstruktur (03.12.2026) - 139 Go-Dateien und die eingebettete Weboberfläche in `cmd/portal/` zusammengeführt; Root-Verzeichnis enthält keine Portal-Go-Dateien mehr. diff --git a/Dockerfile b/Dockerfile index 36e036f..430c08b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,13 @@ # Build complete Go portal for Linux x64; does not depend on the builder CPU. -FROM --platform=$BUILDPLATFORM golang:1.24.4-bookworm AS build +FROM --platform=$BUILDPLATFORM golang:1.27.4-bookworm AS build WORKDIR /src -COPY go.mod ./ +COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOAMD64=v1 \ go build -trimpath -ldflags="-s -w" -o /out/landwelle-portal ./cmd/portal -# psql and ffmpeg are required at runtime by the current application. +# ffmpeg is required for audio processing; psql is retained for maintenance. FROM debian:bookworm-slim RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ diff --git a/README.md b/README.md index 13bc88c..abbb240 100644 --- a/README.md +++ b/README.md @@ -20,19 +20,20 @@ Landwelle wächst Schritt für Schritt. Hinter dem Programm und dem Portal stehe Hier liegt der **Quellcode des Landwelle-Webportals**, nicht die Musikbibliothek oder der eigentliche Sendestream. Die Anwendung wird für den Produktivbetrieb auf einem Linux-x64-Server entwickelt und über [Gitea](https://git.stadt-nexverse.de/nexverse/landwelle) versioniert. -**Aktueller Anwendungsstand:** Landwelle **v1.5.82**. Das Repository ist für Gitea und eine klare Verzeichnisstruktur eingerichtet. Repository-Pflege allein installiert keine neue Portalversion. +**Aktueller Anwendungsstand:** Landwelle **v1.5.83**. Das Repository ist für Gitea und eine klare Verzeichnisstruktur eingerichtet. Repository-Pflege allein installiert keine neue Portalversion. ### Technische Grundlage | Bereich | Umsetzung | |---|---| -| Backend | Go 1.23 mit Toolchain Go 1.24.4 | +| Backend | Go 1.27.4 | | Weboberfläche | HTML-Templates, CSS und JavaScript, in Go eingebettet | -| Datenbank | PostgreSQL mit versionierten SQL-Migrationen | +| Datenbank | PostgreSQL mit nativem pgx-Pool und versionierten SQL-Migrationen | | Livestream | Anbindung an den vorhandenen Streamingdienst | | Redaktion | Geschützter Adminbereich, Mediengalerie, Veröffentlichungen | | KI-Audioproduktion | Konfigurierbare OpenAI-/ElevenLabs-/ffmpeg-/FTP-Abläufe | -| Automatisierung | Zentraler, token-geschützter Cron-Endpunkt | +| Automatisierung | KeyHelp-Cron, persistente PostgreSQL-Jobwarteschlange | +| Monitoring | Admin-Dashboard für Datenbank, Cron, API, KI-Produktion und Gitea | | Produktivbetrieb | Linux x86_64, systemd und KeyHelp als Reverse Proxy | Die früheren Firebase-, Push- und Mobile-App-Integrationen sind aus dem aktiven Anwendungscode entfernt. Historische Datenbankmigrationen bleiben aus Gründen der Nachvollziehbarkeit erhalten. @@ -48,7 +49,7 @@ cmd/ assets/ CSS, JavaScript, Bilder, Audio migrate/ PostgreSQL-Migrationsprogramm adminpass/ Hilfsprogramm für Adminpasswörter -internal/auth/ Internes Authentifizierungspaket +internal/ Auth, Datenbank, Scheduler, Jobwarteschlange, Monitoring, Gitea config/ Beispielkonfigurationen deploy/ systemd- und KeyHelp-Vorlagen docs/ Projektübersicht, Betrieb, Fachmodule, Releasehistorie @@ -79,6 +80,9 @@ go vet ./... # Einzelnes Portal-Paket entwickeln und testen: go test ./cmd/portal +# Echte, isolierte PostgreSQL-Integration (PostgreSQL-Serverwerkzeuge nötig): +./scripts/test-postgres-integration.sh + # Auf einem Linux-x64-System: ./scripts/build-x64.sh ./scripts/build-migrator-x64.sh @@ -104,6 +108,8 @@ Die vollständigen Schritte, Prüfungen und Rollback-Hinweise stehen in [docs/DE ## Dokumentation und Mitarbeit +Die Betriebsänderungen in v1.5.83 sind unter [Plattformmodernisierung](docs/PLATFORM_MODERNIZATION.md) beschrieben. + Wer etwas am Portal weiterentwickelt, findet den Einstieg über [docs/README.md](docs/README.md). Die Regeln für Änderungen stehen in [CONTRIBUTING.md](CONTRIBUTING.md). Den Entwicklungsfahrplan findest du unter [Roadmap](docs/ROADMAP.md). Bereits veröffentlichte Änderungen sind im [CHANGELOG.md](CHANGELOG.md) nachvollziehbar. Bitte keine API-Schlüssel, privaten SSH-Schlüssel, Datenbankbackups oder hochgeladenen Medien in Git committen. Auch produktive Einstellungen gehören ausschließlich auf den Server. diff --git a/cmd/portal/admin.go b/cmd/portal/admin.go index 4a23ce6..0d1b3aa 100644 --- a/cmd/portal/admin.go +++ b/cmd/portal/admin.go @@ -12,6 +12,9 @@ import ( "fmt" "html/template" "io" + "landwelle-portal/internal/giteastatus" + "landwelle-portal/internal/jobqueue" + "landwelle-portal/internal/monitoring" "log" "mime/multipart" "net" @@ -83,6 +86,9 @@ type adminHandler struct { forum *forumStore newsStudio *newsStudioStore aiJobs *aiJobStore + productionQueue *jobqueue.Queue + apiMetrics *monitoring.Metrics + giteaStatus *giteastatus.Service navigation *navigationStore directory *directoryStore siteContent *siteContentStore @@ -129,6 +135,7 @@ type dashboardDBStats struct { } type adminDashboardData struct { + Operations operationsDashboard Username string CSRFToken string Version string @@ -720,6 +727,7 @@ func (a *adminHandler) adminRoot(w http.ResponseWriter, r *http.Request) { data.WeatherError = "Wetterdienst derzeit nicht erreichbar" } a.enrichDashboard(r.Context(), &data) + data.Operations = a.operations(r.Context()) setAdminHTMLHeaders(w) if err := a.dashboardTemplate.ExecuteTemplate(w, "dashboard.html", data); err != nil { @@ -2154,32 +2162,28 @@ func (a *adminHandler) adminWishes(w http.ResponseWriter, r *http.Request) { } wishSettings := a.settings.Get().WishAutomation if status == "approved" && a.wishAutomation != nil && wishSettings.Enabled && wishSettings.AutoProcessOnApprove { - wish, _ := a.wishes.Get(id) - ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) - defer cancel() - if _, err := a.wishAutomation.Process(ctx, wish); err != nil { - data.Error = "Freigegeben, aber Automatik fehlgeschlagen: " + err.Error() + if err := a.enqueueWishProduction(r.Context(), id, false); err != nil { + data.Error = "Freigegeben, aber Auftrag konnte nicht eingeplant werden." a.renderWishes(w, data) return } + http.Redirect(w, r, redirect+"&approved=1&queued=1", http.StatusSeeOther) + return } http.Redirect(w, r, redirect+"&approved=1", http.StatusSeeOther) return case "process": - wish, found := a.wishes.Get(id) - if !found { + if _, found := a.wishes.Get(id); !found { data.Error = "Musikwunsch nicht gefunden" a.renderWishes(w, data) return } - ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) - defer cancel() - if _, err := a.wishAutomation.ProcessManual(ctx, wish); err != nil { - data.Error = err.Error() + if err := a.enqueueWishProduction(r.Context(), id, true); err != nil { + data.Error = "Musikwunsch konnte nicht eingeplant werden." a.renderWishes(w, data) return } - http.Redirect(w, r, redirect+"&processed=1", http.StatusSeeOther) + http.Redirect(w, r, redirect+"&queued=1", http.StatusSeeOther) return default: data.Error = "Unbekannte Aktion" @@ -2204,7 +2208,10 @@ func (a *adminHandler) adminWishes(w http.ResponseWriter, r *http.Request) { data.Success = "Musikwunsch wurde gelöscht." } if r.URL.Query().Get("approved") == "1" { - data.Success = "Musikwunsch wurde freigegeben und die Automation ausgeführt." + data.Success = "Musikwunsch wurde freigegeben." + } + if r.URL.Query().Get("queued") == "1" { + data.Success = "Musikwunsch-Produktion eingeplant (oder bereits in der Warteschlange). Den aktuellen Stand findest du im Dashboard." } if r.URL.Query().Get("processed") == "1" { data.Success = "KI-Text, MP3 und FTP-Auslieferung wurden abgeschlossen." @@ -2970,21 +2977,16 @@ func (a *adminHandler) adminNewsStudio(w http.ResponseWriter, r *http.Request) { jobChannel := active jobBriefing := strings.TrimSpace(r.FormValue("briefing")) job := a.aiJobs.New(jobChannel) - go func() { - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) - defer cancel() - _, err := a.produceNewsStudioTracked(ctx, jobCfg, jobChannel, jobBriefing, job.ID) - a.aiJobs.Finish(job.ID, err) - if err != nil { - a.logger.Printf("news studio production (%s): %v", jobChannel, err) - } - }() + _, err := a.enqueueProduction(r.Context(), job, "news", productionCommand{Channel: jobChannel, News: &jobCfg, Briefing: jobBriefing}, 0, time.Time{}) + if err != nil { + a.aiJobs.Finish(job.ID, errors.New("Produktionsauftrag konnte nicht gespeichert werden.")) + } if action == "produce_stream" { a.streamAIJobHTML(w, r, job.ID) return } if strings.Contains(r.Header.Get("Accept"), "application/json") || r.Header.Get("X-Requested-With") == "XMLHttpRequest" { - writeJSONResponse(w, map[string]any{"job_id": job.ID, "status": "running"}) + writeJSONResponse(w, map[string]any{"job_id": job.ID, "status": "queued"}) return } http.Redirect(w, r, "/admin/ai/news?tab="+active+"&job="+job.ID, http.StatusSeeOther) diff --git a/cmd/portal/ai_audio_modules.go b/cmd/portal/ai_audio_modules.go index 6117360..da4ebd9 100644 --- a/cmd/portal/ai_audio_modules.go +++ b/cmd/portal/ai_audio_modules.go @@ -409,15 +409,10 @@ func (a *adminHandler) adminAIAudioModule(w http.ResponseWriter, r *http.Request } job := a.aiJobs.NewWithSteps(module.Key, []string{"Sprechtext prüfen", "MP3 erzeugen", "Hintergrundmusik", "FTP-Upload", "Lokale Datei bereinigen", "Abschluss"}) - go func(module AIAudioModuleDefinition, cfg AIAudioModuleSettings, runtime RuntimeSettings, jobID string) { - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) - defer cancel() - err := a.produceAIAudioModuleTracked(ctx, module, cfg, runtime, jobID) - a.aiJobs.Finish(jobID, err) - if err != nil && a.logger != nil { - a.logger.Printf("ai audio module production (%s): %v", module.Key, err) - } - }(module, cfg, runtime, job.ID) + _, err := a.enqueueProduction(r.Context(), job, "audio", productionCommand{Channel: module.Key, Audio: &cfg}, 0, time.Time{}) + if err != nil { + a.aiJobs.Finish(job.ID, errors.New("Produktionsauftrag konnte nicht gespeichert werden.")) + } a.streamAIJobHTML(w, r, job.ID) } @@ -507,7 +502,7 @@ func (a *adminHandler) produceAIAudioModuleTracked(ctx context.Context, module A // Automatic rubrics use their saved, human-written prompt and configured // production settings. Generated copy is not written into the manual editor: // simultaneous editorial work must not be overwritten by the cron worker. -func (a *adminHandler) produceScheduledAIAudioModule(ctx context.Context, module AIAudioModuleDefinition) error { +func (a *adminHandler) produceScheduledAIAudioModule(ctx context.Context, module AIAudioModuleDefinition, jobID string) error { runtime := a.settings.Get() cfg, ok := runtime.AIAudioModules[module.Key] if !ok { @@ -526,7 +521,7 @@ func (a *adminHandler) produceScheduledAIAudioModule(ctx context.Context, module if cfg.Text == "" { return fmt.Errorf("%s: OpenAI hat keinen Sprechtext zurückgegeben", module.Title) } - if err := a.produceAIAudioModuleTracked(ctx, module, cfg, runtime, ""); err != nil { + if err := a.produceAIAudioModuleTracked(ctx, module, cfg, runtime, jobID); err != nil { return fmt.Errorf("%s: Audio-Produktion: %w", module.Title, err) } return nil diff --git a/cmd/portal/ai_cron_scheduler_test.go b/cmd/portal/ai_cron_scheduler_test.go index cd9212c..d359eaa 100644 --- a/cmd/portal/ai_cron_scheduler_test.go +++ b/cmd/portal/ai_cron_scheduler_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "encoding/json" + "landwelle-portal/internal/jobqueue" "os" "strings" "testing" @@ -37,8 +38,8 @@ func TestAutoTaskPostgresJSONDecodesAllSchedulingFields(t *testing.T) { } func TestAutoTaskClaimQueryIsSingleSelectResult(t *testing.T) { - sql := autoTaskClaimSQL(42) - for _, v := range []string{"WITH claimed AS (", "UPDATE landwelle.ai_auto_tasks", "RETURNING id", ") SELECT id FROM claimed;"} { + sql := jobqueue.ScheduledSQL + for _, v := range []string{"WITH claimed AS (", "UPDATE landwelle.ai_auto_tasks", "RETURNING id,last_run_at", "FROM claimed"} { if !strings.Contains(sql, v) { t.Fatalf("missing %q: %s", v, sql) } diff --git a/cmd/portal/ai_jobs.go b/cmd/portal/ai_jobs.go index 6e30c81..45b41d0 100644 --- a/cmd/portal/ai_jobs.go +++ b/cmd/portal/ai_jobs.go @@ -2,10 +2,13 @@ package main import ( "context" + "crypto/rand" "crypto/subtle" "encoding/json" "errors" "fmt" + "landwelle-portal/internal/jobqueue" + "landwelle-portal/internal/scheduler" "net/http" "os" "strconv" @@ -31,8 +34,10 @@ type AIJob struct { Steps []AIJobStep `json:"steps"` } type aiJobStore struct { - mu sync.RWMutex - jobs map[string]AIJob + mu sync.RWMutex + jobs map[string]AIJob + queue *jobqueue.Queue + redact func(string) string } func newAIJobStore() *aiJobStore { return &aiJobStore{jobs: map[string]AIJob{}} } @@ -72,7 +77,7 @@ func (s *aiJobStore) New(channel string) AIJob { } func (s *aiJobStore) NewWithSteps(channel string, labels []string) AIJob { now := time.Now() - id := fmt.Sprintf("%d", now.UnixNano()) + id := rand.Text() steps := make([]AIJobStep, len(labels)) for i, l := range labels { steps[i] = AIJobStep{Key: fmt.Sprintf("step-%d", i+1), Label: l, Status: "pending", UpdatedAt: now} @@ -86,18 +91,29 @@ func (s *aiJobStore) NewWithSteps(channel string, labels []string) AIJob { } func (s *aiJobStore) Update(id string, idx int, status, msg string) { s.mu.Lock() - defer s.mu.Unlock() + j, ok := s.jobs[id] if !ok { + s.mu.Unlock() return } if idx >= 0 && idx < len(j.Steps) { j.Steps[idx].Status = status + if s.redact != nil { + msg = s.redact(msg) + } j.Steps[idx].Message = msg j.Steps[idx].UpdatedAt = time.Now() } j.UpdatedAt = time.Now() s.jobs[id] = j + raw, _ := json.Marshal(j) + s.mu.Unlock() + if s.queue != nil { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _ = s.queue.Progress(ctx, id, raw) + cancel() + } } func (s *aiJobStore) Finish(id string, err error) { s.mu.Lock() @@ -110,12 +126,27 @@ func (s *aiJobStore) Finish(id string, err error) { if err != nil { j.Status = "error" j.Error = err.Error() + if s.redact != nil { + j.Error = s.redact(j.Error) + } } else { j.Status = "done" } s.jobs[id] = j } func (s *aiJobStore) Get(id string) (AIJob, bool) { + if s.queue != nil { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + r, err := s.queue.Get(ctx, id) + cancel() + if err == nil { + var j AIJob + if json.Unmarshal(r.Snapshot, &j) == nil { + j.Status, j.Error, j.UpdatedAt = r.Status, r.Error, r.UpdatedAt + return j, true + } + } + } s.mu.RLock() defer s.mu.RUnlock() j, ok := s.jobs[id] @@ -132,13 +163,13 @@ func (a *adminHandler) streamAIJobHTML(w http.ResponseWriter, r *http.Request, j w.Header().Set("X-Robots-Tag", "noindex, nofollow, noarchive") controller := http.NewResponseController(w) - _ = controller.SetWriteDeadline(time.Now().Add(13 * time.Minute)) + _ = controller.SetWriteDeadline(time.Now().Add(60 * time.Minute)) flusher, canFlush := w.(http.Flusher) _, _ = fmt.Fprint(w, `Landwelle Produktion

Der Produktionsauftrag wird vorbereitet …

`) // Ein ausreichend großer erster Block verhindert, dass Reverse-Proxys die // Fortschrittsanzeige bis zum Ende der Produktion puffern. @@ -150,7 +181,7 @@ function renderJob(job){const status=document.getElementById('status'),steps=doc lastUpdated := time.Time{} ticker := time.NewTicker(750 * time.Millisecond) defer ticker.Stop() - timeout := time.NewTimer(13 * time.Minute) + timeout := time.NewTimer(60 * time.Minute) defer timeout.Stop() send := func(job AIJob) { @@ -187,7 +218,7 @@ function renderJob(job){const status=document.getElementById('status'),steps=doc return case <-timeout.C: job.Status = "error" - job.Error = "Die Live-Anzeige wurde nach 13 Minuten beendet. Bitte die Produktionshistorie prüfen." + job.Error = "Die Live-Anzeige wurde nach 60 Minuten beendet. Bitte die Produktionshistorie prüfen." send(job) _, _ = fmt.Fprint(w, "") return @@ -215,23 +246,8 @@ type AIAutoTask struct { UpdatedAt time.Time `json:"updated_at"` } -func parseDays(v string) []int { - var out []int - for _, p := range strings.Split(v, ",") { - n, e := strconv.Atoi(strings.TrimSpace(p)) - if e == nil && n >= 1 && n <= 7 { - out = append(out, n) - } - } - return out -} -func daysCSV(days []int) string { - var p []string - for _, d := range days { - p = append(p, strconv.Itoa(d)) - } - return strings.Join(p, ",") -} +func parseDays(v string) []int { return scheduler.ParseDays(v) } +func daysCSV(days []int) string { return scheduler.DaysCSV(days) } // autoTaskDBRow decodes the PostgreSQL json_build_object column names. // Fields containing underscores MUST have explicit JSON tags. Otherwise @@ -309,13 +325,7 @@ type AICronAdminStatus struct { LastDurationMS int64 } -func berlinLocation() *time.Location { - location, err := time.LoadLocation("Europe/Berlin") - if err != nil { - return time.FixedZone("Europe/Berlin", 3600) - } - return location -} +func berlinLocation() *time.Location { return scheduler.Berlin() } func normalizeAutoTaskKey(key string) string { return strings.ToLower(strings.TrimSpace(key)) @@ -340,43 +350,9 @@ func supportedAutoTaskKey(key string) bool { } func autoTaskIsDue(task AIAutoTask, now time.Time) bool { - if !task.Active || !supportedAutoTaskKey(task.TaskKey) { - return false - } - local := now.In(berlinLocation()) - weekday := int(local.Weekday()) - if weekday == 0 { - weekday = 7 - } - return strings.TrimSpace(task.RunTime) == local.Format("15:04") && containsInt(task.Days, weekday) -} - -func sameAutoTaskMinute(last *time.Time, now time.Time) bool { - if last == nil { - return false - } - location := berlinLocation() - return last.In(location).Format("2006-01-02 15:04") == now.In(location).Format("2006-01-02 15:04") -} - -// Claim an automatic task atomically in PostgreSQL. A read followed by an -// unconditional UPDATE can start the same task twice when cron requests overlap. -// Comparing Berlin wall-clock minutes also preserves one run during the autumn -// daylight-saving-time clock change. -func autoTaskClaimSQL(id int64) string { - // A SELECT around the UPDATE avoids the "UPDATE 1" command tag in psql's - // command output. The caller must receive only the claimed task's ID. - return `WITH claimed AS ( -UPDATE landwelle.ai_auto_tasks -SET last_run_at=now(), last_status='queued', last_error='', updated_at=now() -WHERE id=` + strconv.FormatInt(id, 10) + ` - AND active - AND (last_run_at IS NULL OR - date_trunc('minute', last_run_at AT TIME ZONE 'Europe/Berlin') - IS DISTINCT FROM date_trunc('minute', now() AT TIME ZONE 'Europe/Berlin')) -RETURNING id -) SELECT id FROM claimed;` + return supportedAutoTaskKey(task.TaskKey) && scheduler.Due(task.Active, task.RunTime, task.Days, now) } +func sameAutoTaskMinute(last *time.Time, now time.Time) bool { return scheduler.SameMinute(last, now) } func cronRequestAuthorized(r *http.Request) bool { token := strings.TrimSpace(os.Getenv("LANDWELLE_CRON_TOKEN")) @@ -413,23 +389,27 @@ func (a *adminHandler) runDueAutoTasks(ctx context.Context) (int, int, error) { continue } due++ - if a.database != nil && a.database.Enabled() { - claimed, err := a.database.exec(ctx, autoTaskClaimSQL(task.ID)) - if err != nil { - if a.logger != nil { - a.logger.Printf("auto task %d could not be claimed: %v", task.ID, err) - } - claimErrors = append(claimErrors, fmt.Errorf("Aufgabe %d: PostgreSQL-Start fehlgeschlagen: %w", task.ID, err)) - continue - } - // An overlapping request might already have claimed this minute. - // Parse the ID from a single SQL result instead of matching raw psql output. - if strings.TrimSpace(string(claimed)) != strconv.FormatInt(task.ID, 10) { - continue - } + key := normalizeAutoTaskKey(task.TaskKey) + var j AIJob + if strings.HasPrefix(key, "audio:") { + j = a.aiJobs.NewWithSteps(key, audioJobLabels) + } else { + j = a.aiJobs.New(strings.TrimPrefix(key, "news:")) + j.Channel = key + } + claimed, err := a.enqueueProduction(ctx, j, "scheduled", productionCommand{Channel: key}, task.ID, now) + if err != nil || !claimed { + a.aiJobs.mu.Lock() + delete(a.aiJobs.jobs, j.ID) + a.aiJobs.mu.Unlock() + } + if err != nil { + claimErrors = append(claimErrors, fmt.Errorf("Aufgabe %d: Warteschlange nicht verfügbar", task.ID)) + continue + } + if claimed { + started++ } - started++ - go a.executeAutoTask(task) } return due, started, errors.Join(claimErrors...) } @@ -521,44 +501,6 @@ func (a *adminHandler) cronAdminStatus(ctx context.Context) AICronAdminStatus { return status } -func containsInt(v []int, n int) bool { - for _, x := range v { - if x == n { - return true - } - } - return false -} -func (a *adminHandler) executeAutoTask(t AIAutoTask) { - if !supportedAutoTaskKey(t.TaskKey) { - return - } - _, _ = a.database.exec(context.Background(), `UPDATE landwelle.ai_auto_tasks SET last_run_at=now(),last_status='running',last_error='',updated_at=now() WHERE id=`+strconv.FormatInt(t.ID, 10)) - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute) - defer cancel() - var err error - key := normalizeAutoTaskKey(t.TaskKey) - if strings.HasPrefix(key, "audio:") { - moduleKey := strings.TrimPrefix(key, "audio:") - module, exists := aiAudioModuleByKey(moduleKey) - if !exists { - err = fmt.Errorf("unbekannte Audio-Rubrik %q", moduleKey) - } else { - err = a.produceScheduledAIAudioModule(ctx, module) - } - } else { - cfg, _ := a.newsStudio.Get() - ch := strings.TrimPrefix(key, "news:") - _, err = a.produceNewsStudio(ctx, cfg, ch, "") - } - status := "done" - msg := "" - if err != nil { - status = "error" - msg = err.Error() - } - _, _ = a.database.exec(context.Background(), `UPDATE landwelle.ai_auto_tasks SET last_status=`+sqlText(status)+`,last_error=`+sqlText(msg)+`,updated_at=now() WHERE id=`+strconv.FormatInt(t.ID, 10)) -} func writeJSONResponse(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") diff --git a/cmd/portal/ai_jobs_stability_test.go b/cmd/portal/ai_jobs_stability_test.go index 851ceb1..65ca009 100644 --- a/cmd/portal/ai_jobs_stability_test.go +++ b/cmd/portal/ai_jobs_stability_test.go @@ -1,6 +1,7 @@ package main import ( + "landwelle-portal/internal/jobqueue" "strings" "testing" "time" @@ -54,16 +55,16 @@ func TestAIJobStorePrunesExpiredJobs(t *testing.T) { } func TestAutoTaskClaimSQLPreventsDuplicateStarts(t *testing.T) { - query := autoTaskClaimSQL(123) + query := jobqueue.ScheduledSQL for _, clause := range []string{ - "WHERE id=123", + "WHERE id=$1", "AND active", "last_run_at IS NULL", "IS DISTINCT FROM", "AT TIME ZONE 'Europe/Berlin'", "WITH claimed AS (", - "RETURNING id", - ") SELECT id FROM claimed;", + "RETURNING id,last_run_at", + "FROM claimed", } { if !strings.Contains(query, clause) { t.Errorf("claim query missing %q: %s", clause, query) diff --git a/cmd/portal/main.go b/cmd/portal/main.go index dc451a7..282afc2 100644 --- a/cmd/portal/main.go +++ b/cmd/portal/main.go @@ -11,6 +11,9 @@ import ( "fmt" "html/template" "io/fs" + "landwelle-portal/internal/giteastatus" + "landwelle-portal/internal/jobqueue" + "landwelle-portal/internal/monitoring" "log" "math/rand" "net" @@ -37,7 +40,7 @@ const ( apiVersion = "v1" apiContractVersion = "1.0.0" applicationName = "Landwelle Radio" - applicationVersion = "1.5.82" + applicationVersion = "1.5.83" ) var publicTemplateFiles = []string{ @@ -235,6 +238,7 @@ func main() { if err != nil { logger.Fatal(err) } + defer database.Close() siteSeasonCurrent = &siteSeasonStore{db: database} weather := NewWeatherService() traffic := newTrafficService(logger) @@ -298,6 +302,26 @@ func main() { logger.Fatal(err) } + workerCtx, stopWorker := context.WithCancel(context.Background()) + defer stopWorker() + workerDone := make(chan struct{}) + admin.apiMetrics = &monitoring.Metrics{} + admin.giteaStatus = &giteastatus.Service{} + go admin.giteaStatus.Run(workerCtx) + if database.pool != nil { + admin.productionQueue = &jobqueue.Queue{Pool: database.pool} + check, cancel := context.WithTimeout(context.Background(), 5*time.Second) + err := admin.productionQueue.Check(check) + cancel() + if err != nil { + logger.Fatal("Produktionswarteschlange nicht verfügbar; Migration 0051 prüfen") + } + + admin.aiJobs.queue = admin.productionQueue + admin.aiJobs.redact = admin.redactProductionMessage + } + go func() { defer close(workerDone); admin.startProductionWorker(workerCtx) }() + mux := http.NewServeMux() mux.Handle("/assets/", cacheControl(http.StripPrefix("/assets/", http.FileServer(http.FS(assets))))) mux.HandleFunc("/media/", func(w http.ResponseWriter, r *http.Request) { @@ -658,7 +682,7 @@ func main() { server := &http.Server{ Addr: envOr("ADDR", ":2200"), - Handler: requestLog(logger, securityHeaders(rateLimitMiddleware(mux))), + Handler: requestLog(logger, securityHeaders(admin.apiMetrics.Middleware(rateLimitMiddleware(mux)))), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 4 * time.Minute, @@ -688,11 +712,16 @@ func main() { } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() + stopWorker() rss.Stop(ctx) nowPlayingService.Stop(ctx) if err := server.Shutdown(ctx); err != nil { logger.Printf("Graceful Shutdown: %v", err) } + select { + case <-workerDone: + case <-ctx.Done(): + } logger.Printf("Portal sauber beendet") } diff --git a/cmd/portal/main_test.go b/cmd/portal/main_test.go index 69267fa..872fda7 100644 --- a/cmd/portal/main_test.go +++ b/cmd/portal/main_test.go @@ -147,7 +147,7 @@ func TestWeatherHelpers(t *testing.T) { } func TestApplicationVersion(t *testing.T) { - if applicationVersion != "1.5.82" { + if applicationVersion != "1.5.83" { t.Fatalf("unexpected application version %q", applicationVersion) } } diff --git a/cmd/portal/media_favorites_test.go b/cmd/portal/media_favorites_test.go index f9c4206..32ebf03 100644 --- a/cmd/portal/media_favorites_test.go +++ b/cmd/portal/media_favorites_test.go @@ -9,31 +9,33 @@ import ( "testing" ) -// The fake psql process records the actual SQL sent by postgresStore, allowing -// this test to cover both the ordered gallery query and the write statement -// without needing a production PostgreSQL instance. +// Record the actual SQL at the database boundary, without external processes. func fakeMediaFavoritesDatabase(t *testing.T) (*mediaStore, string) { t.Helper() dir := t.TempDir() - command := filepath.Join(dir, "psql") logFile := filepath.Join(dir, "queries.log") - fake := `#!/bin/sh -for arg do statement="$arg"; done -printf '%s\n' "$statement" >> "$MEDIA_TEST_QUERY_LOG" -case "$statement" in - *"json_build_array"*) printf '[{"count":2}]\n' ;; - *"WITH changed"*) - case "$statement" in - *"WHERE id=999 RETURNING"*) printf '[]\n' ;; - *) printf '[{"id":7}]\n' ;; - esac ;; - *) printf '[{"id":7,"original_name":"Favorit.jpg","storage_key":"one.jpg","is_favorite":true},{"id":8,"original_name":"Normal.jpg","storage_key":"two.jpg","is_favorite":false}]\n' ;; -esac -` - if err := os.WriteFile(command, []byte(fake), 0700); err != nil { - t.Fatal(err) - } - db := &postgresStore{configured: true, psqlPath: command, env: append(os.Environ(), "MEDIA_TEST_QUERY_LOG="+logFile)} + db := &postgresStore{execFn: func(ctx context.Context, statement string) ([]byte, error) { + f, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return nil, err + } + _, err = f.WriteString(statement + "\n") + f.Close() + if err != nil { + return nil, err + } + switch { + case strings.Contains(statement, "json_build_array"): + return []byte(`[{"count":2}]`), nil + case strings.Contains(statement, "WITH changed"): + if strings.Contains(statement, "WHERE id=999 RETURNING") { + return []byte("[]"), nil + } + return []byte(`[{"id":7}]`), nil + default: + return []byte(`[{"id":7,"original_name":"Favorit.jpg","storage_key":"one.jpg","is_favorite":true},{"id":8,"original_name":"Normal.jpg","storage_key":"two.jpg","is_favorite":false}]`), nil + } + }} return &mediaStore{db: db, dir: dir}, logFile } diff --git a/cmd/portal/operations_dashboard.go b/cmd/portal/operations_dashboard.go new file mode 100644 index 0000000..e8ef9ae --- /dev/null +++ b/cmd/portal/operations_dashboard.go @@ -0,0 +1,63 @@ +package main + +import ( + "context" + "landwelle-portal/internal/giteastatus" + "landwelle-portal/internal/jobqueue" + "landwelle-portal/internal/monitoring" + "time" +) + +type operationsDashboard struct { + DBStatus string + DBLatencyMS int64 + DBTotal, DBIdle, DBBusy, DBMax int32 + CronStatus string + CronLast string + QueueAvailable bool + Queue jobqueue.Summary + API monitoring.Snapshot + Gitea giteastatus.Snapshot + BuildCommit, BuildTime, Deployment string +} + +func (a *adminHandler) operations(ctx context.Context) operationsDashboard { + d := operationsDashboard{DBStatus: "Nicht konfiguriert", CronStatus: "Nicht geprüft", BuildCommit: buildCommit, BuildTime: buildTime} + if a.apiMetrics != nil { + d.API = a.apiMetrics.Snapshot() + } + if a.giteaStatus != nil { + d.Gitea = a.giteaStatus.Get() + } + d.Deployment = d.Gitea.Deployment(buildCommit) + if a.database != nil && a.database.pool != nil { + check, cancel := context.WithTimeout(ctx, 2*time.Second) + start := time.Now() + if err := a.database.Ping(check); err == nil { + d.DBStatus = "Verbunden" + } else { + d.DBStatus = "Nicht erreichbar" + } + d.DBLatencyMS = time.Since(start).Milliseconds() + cancel() + stat := a.database.pool.Stat() + d.DBTotal, d.DBIdle, d.DBBusy, d.DBMax = stat.TotalConns(), stat.IdleConns(), stat.AcquiredConns(), stat.MaxConns() + check, cancel = context.WithTimeout(ctx, 2*time.Second) + cron := a.cronAdminStatus(check) + cancel() + d.CronStatus = cron.HealthLabel + if cron.LastPingAt != nil { + d.CronLast = cron.LastPingAt.In(berlinLocation()).Format("02.01.2006 15:04:05") + } + } + if a.productionQueue != nil { + check, cancel := context.WithTimeout(ctx, 2*time.Second) + q, err := a.productionQueue.Summary(check) + cancel() + if err == nil { + d.QueueAvailable = true + d.Queue = q + } + } + return d +} diff --git a/cmd/portal/operations_dashboard_test.go b/cmd/portal/operations_dashboard_test.go new file mode 100644 index 0000000..b419a0e --- /dev/null +++ b/cmd/portal/operations_dashboard_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "bytes" + "strings" + "testing" +) + +func TestOperationsDashboardRenders(t *testing.T) { + tmpl, err := parseAdminTemplate("web/admin/dashboard.html") + if err != nil { + t.Fatal(err) + } + var out bytes.Buffer + if err = tmpl.ExecuteTemplate(&out, "dashboard.html", adminDashboardData{Username: "Test", Version: displayVersion()}); err != nil { + t.Fatal(err) + } + for _, s := range []string{"Datenbank & Cron", "KI-Warteschlange", "API-Monitoring", "Gitea · Landwelle", "Repository öffnen"} { + if !strings.Contains(out.String(), s) { + t.Fatalf("dashboard missing %s", s) + } + } +} diff --git a/cmd/portal/postgres.go b/cmd/portal/postgres.go index 33af0c9..caee54d 100644 --- a/cmd/portal/postgres.go +++ b/cmd/portal/postgres.go @@ -5,17 +5,18 @@ import ( "encoding/json" "errors" "fmt" - "net/url" "os" - "os/exec" "strings" "time" + + "github.com/jackc/pgx/v5/pgxpool" + "landwelle-portal/internal/database" ) type postgresStore struct { - configured bool - psqlPath string - env []string + pool *pgxpool.Pool + // A test seam for repository-level SQL assertions, never used in production. + execFn func(context.Context, string) ([]byte, error) } func newPostgresStore() (*postgresStore, error) { @@ -23,71 +24,41 @@ func newPostgresStore() (*postgresStore, error) { if raw == "" { return &postgresStore{}, nil } - path, err := exec.LookPath("psql") - if err != nil { - return nil, errors.New("DATABASE_URL ist gesetzt, aber psql fehlt; installiere postgresql-client") - } - env, err := postgresEnv(raw) - if err != nil { - return nil, err - } - store := &postgresStore{configured: true, psqlPath: path, env: append(os.Environ(), env...)} ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - if _, err := store.exec(ctx, "SELECT 1;"); err != nil { - return nil, fmt.Errorf("PostgreSQL nicht erreichbar: %w", err) - } - return store, nil -} - -func postgresEnv(raw string) ([]string, error) { - u, err := url.Parse(raw) + pool, err := database.Open(ctx, raw, int32(envIntRange("LANDWELLE_DB_MAX_CONNECTIONS", 8, 3, 32))) if err != nil { return nil, err } - if u.Scheme != "postgres" && u.Scheme != "postgresql" { - return nil, errors.New("DATABASE_URL muss postgres:// oder postgresql:// verwenden") - } - if u.User == nil || u.User.Username() == "" { - return nil, errors.New("DATABASE_URL enthält keinen Benutzer") - } - db := strings.TrimPrefix(u.Path, "/") - if db == "" { - return nil, errors.New("DATABASE_URL enthält keine Datenbank") - } - env := []string{"PGUSER=" + u.User.Username(), "PGDATABASE=" + db, "PGOPTIONS=-c search_path=landwelle,public", "PGAPPNAME=landwelle-portal"} - if p, ok := u.User.Password(); ok { - env = append(env, "PGPASSWORD="+p) - } - if h := u.Hostname(); h != "" { - env = append(env, "PGHOST="+h) - } - if p := u.Port(); p != "" { - env = append(env, "PGPORT="+p) - } - if v := u.Query().Get("sslmode"); v != "" { - env = append(env, "PGSSLMODE="+v) - } - return env, nil + return &postgresStore{pool: pool}, nil } -func (p *postgresStore) Enabled() bool { return p != nil && p.configured } +func (p *postgresStore) Enabled() bool { return p != nil && (p.pool != nil || p.execFn != nil) } func (p *postgresStore) Ping(ctx context.Context) error { if !p.Enabled() { return errors.New("PostgreSQL ist nicht konfiguriert") } + if p.pool != nil { + return p.pool.Ping(ctx) + } _, err := p.exec(ctx, "SELECT 1;") return err } +func (p *postgresStore) Close() { + if p != nil && p.pool != nil { + p.pool.Close() + } +} func (p *postgresStore) exec(ctx context.Context, sql string) ([]byte, error) { if !p.Enabled() { return nil, errors.New("PostgreSQL ist nicht konfiguriert") } - cmd := exec.CommandContext(ctx, p.psqlPath, "--no-psqlrc", "--set", "ON_ERROR_STOP=1", "--tuples-only", "--no-align", "--command", sql) - cmd.Env = p.env - out, err := cmd.CombinedOutput() + if p.execFn != nil { + return p.execFn(ctx, sql) + } + out, err := database.Text(ctx, p.pool, sql) if err != nil { - return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) + return nil, fmt.Errorf("PostgreSQL: %w", err) } return out, nil } diff --git a/cmd/portal/production_queue.go b/cmd/portal/production_queue.go new file mode 100644 index 0000000..8642041 --- /dev/null +++ b/cmd/portal/production_queue.go @@ -0,0 +1,194 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "landwelle-portal/internal/jobqueue" +) + +type productionCommand struct { + Channel string + News *NewsStudioSettings + Audio *AIAudioModuleSettings + Briefing string + WishID string + ManualWish bool +} + +var audioJobLabels = []string{"Sprechtext prüfen", "MP3 erzeugen", "Hintergrundmusik", "FTP-Upload", "Lokale Datei bereinigen", "Abschluss"} + +func (a *adminHandler) enqueueProduction(ctx context.Context, j AIJob, kind string, cmd productionCommand, taskID int64, when time.Time) (bool, error) { + if a.productionQueue == nil { + return false, errors.New("PostgreSQL-Produktionswarteschlange nicht verfügbar") + } + j.Status = "queued" + payload, err := json.Marshal(cmd) + if err != nil { + return false, err + } + snapshot, err := json.Marshal(j) + if err != nil { + return false, err + } + record := jobqueue.Job{ID: j.ID, Channel: j.Channel, Kind: kind, Payload: payload, Snapshot: snapshot} + if taskID != 0 { + return a.productionQueue.EnqueueScheduled(ctx, taskID, when, record) + } + if kind == "wish" { + return a.productionQueue.EnqueueWish(ctx, record, cmd.WishID) + } + return true, a.productionQueue.Enqueue(ctx, record) +} +func (a *adminHandler) startProductionWorker(ctx context.Context) { + if a.productionQueue == nil { + return + } + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + default: + } + claimCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + record, ok, err := a.productionQueue.Claim(claimCtx) + cancel() + if err != nil { + if ctx.Err() == nil { + a.logger.Printf("Produktionswarteschlange: Auftrag konnte nicht übernommen werden") + } + } else if ok { + a.runProductionRecord(ctx, record) + continue + } + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} +func (a *adminHandler) runProductionRecord(parent context.Context, record jobqueue.Job) { + var j AIJob + if err := json.Unmarshal(record.Snapshot, &j); err != nil { + j = AIJob{ID: record.ID, Channel: record.Channel} + } + j.Status = "running" + j.UpdatedAt = time.Now() + a.aiJobs.mu.Lock() + a.aiJobs.jobs[j.ID] = j + a.aiJobs.mu.Unlock() + ctx, cancel := context.WithTimeout(parent, 12*time.Minute) + defer cancel() + var err error + defer func() { + if recover() != nil { + err = errors.New("Interner Fehler in der Audioproduktion") + } + if err == nil && ctx.Err() != nil { + err = ctx.Err() + } + a.aiJobs.Finish(j.ID, err) + a.aiJobs.mu.RLock() + finished := cloneAIJob(a.aiJobs.jobs[j.ID]) + a.aiJobs.mu.RUnlock() + raw, _ := json.Marshal(finished) + finishCtx, stop := context.WithTimeout(context.Background(), 8*time.Second) + defer stop() + if e := a.productionQueue.Finish(finishCtx, j.ID, finished.Status, finished.Error, raw); e != nil { + a.logger.Printf("Produktionswarteschlange: Abschluss von %s nicht gespeichert", j.ID) + } + a.aiJobs.mu.Lock() + delete(a.aiJobs.jobs, j.ID) + a.aiJobs.mu.Unlock() + }() + var cmd productionCommand + if err = json.Unmarshal(record.Payload, &cmd); err != nil { + return + } + switch record.Kind { + case "news": + if cmd.News == nil { + err = errors.New("Nachrichten-Konfiguration fehlt") + return + } + _, err = a.produceNewsStudioTracked(ctx, *cmd.News, cmd.Channel, cmd.Briefing, j.ID) + case "audio": + module, ok := aiAudioModuleByKey(cmd.Channel) + if !ok || cmd.Audio == nil { + err = errors.New("Audio-Konfiguration fehlt") + return + } + err = a.produceAIAudioModuleTracked(ctx, module, *cmd.Audio, a.settings.Get(), j.ID) + case "wish": + wish, ok := a.wishes.Get(cmd.WishID) + if !ok { + err = errors.New("Musikwunsch nicht mehr vorhanden") + return + } + if !cmd.ManualWish && wish.Status != "approved" { + err = errors.New("Musikwunsch nicht mehr freigegeben") + return + } + a.aiJobs.Update(j.ID, 0, "running", "Musikwunsch wird produziert") + if cmd.ManualWish { + _, err = a.wishAutomation.ProcessManual(ctx, wish) + } else { + _, err = a.wishAutomation.Process(ctx, wish) + } + if err != nil { + a.aiJobs.Update(j.ID, 0, "error", err.Error()) + _ = a.wishes.SetProcessing(wish.ID, "error", a.redactProductionMessage(err.Error())) + // The existing workflow stores error details when possible; avoid + // clearing any already generated audio on failure. + } else { + a.aiJobs.Update(j.ID, 0, "done", "Musikwunsch produziert") + } + case "scheduled": + key := normalizeAutoTaskKey(cmd.Channel) + if !supportedAutoTaskKey(key) { + err = errors.New("Unbekannte automatische Aufgabe") + return + } + if len(key) > 6 && key[:6] == "audio:" { + module, ok := aiAudioModuleByKey(key[6:]) + if !ok { + err = errors.New("Unbekannte Audio-Rubrik") + return + } + err = a.produceScheduledAIAudioModule(ctx, module, j.ID) + } else { + cfg, _ := a.newsStudio.Get() + _, err = a.produceNewsStudioTracked(ctx, cfg, key[5:], "", j.ID) + } + default: + err = fmt.Errorf("Unbekannter Produktionsauftrag") + } +} + +func (a *adminHandler) redactProductionMessage(message string) string { + cfg := a.settings.Get() + for _, secret := range []string{cfg.OpenAI.APIKey, cfg.ElevenLabs.APIKey, cfg.FTP.Password, cfg.SMTP.Password, cfg.Social.FacebookPageToken} { + if secret != "" { + message = strings.ReplaceAll(message, secret, "[geschützt]") + } + } + return message +} + +func (a *adminHandler) enqueueWishProduction(ctx context.Context, id string, manual bool) error { + job := a.aiJobs.NewWithSteps("Musikwunsch", []string{"KI-Text, Audio und Auslieferung"}) + _, err := a.enqueueProduction(ctx, job, "wish", productionCommand{WishID: id, ManualWish: manual}, 0, time.Time{}) + // The durable record is the source of truth; the ephemeral job is not needed + // until the worker claims it. Do not remove a record already taken by worker. + if err != nil { + a.aiJobs.Finish(job.ID, errors.New("Musikwunsch konnte nicht eingeplant werden")) + } + return err +} diff --git a/cmd/portal/web/admin/dashboard.html b/cmd/portal/web/admin/dashboard.html index 1cae296..c456ea6 100644 --- a/cmd/portal/web/admin/dashboard.html +++ b/cmd/portal/web/admin/dashboard.html @@ -101,6 +101,38 @@
Go{{.GoVersion}}
System{{.GoOS}} / {{.GoArch}}
Goroutinen{{.GoRoutines}}
Speicher{{.MemoryMB}} MB
+
+
▦
Betrieb

Datenbank & Cron

+
{{.Operations.DBStatus}}PostgreSQL · {{.Operations.DBLatencyMS}} ms (Ping)
+
Pool belegt / max.{{.Operations.DBBusy}} / {{.Operations.DBMax}}
Freie Verbindungen{{.Operations.DBIdle}}
+
{{.Operations.CronStatus}}Letzter Cron-Aufruf: {{if .Operations.CronLast}}{{.Operations.CronLast}}{{else}}–{{end}}
+ Cron-Aufgaben ansehen +
+
+
◷
Produktion

KI-Warteschlange

+ {{if .Operations.QueueAvailable}} +
Wartend / aktiv{{.Operations.Queue.Queued}} / {{.Operations.Queue.Running}}
Erfolg / Fehler{{.Operations.Queue.Done}} / {{.Operations.Queue.Failed}}
+ {{range .Operations.Queue.Recent}}
{{.Channel}}{{.Status}}
{{.CreatedAt.Format "02.01. 15:04 MST"}}
Details
{{else}}

Noch keine gespeicherten Aufträge.

{{end}} + {{else}}

Warteschlange nicht verfügbar.

{{end}} +
+
+
{ }
Schnittstellen

API-Monitoring

+
Aufrufe seit Start{{.Operations.API.Requests}}
HTTP 5xx{{.Operations.API.Errors}}
+
{{.Operations.API.AverageMS}} msMittlere Antwortzeit seit Start
+ {{if not .Operations.API.LastError.IsZero}}Letzter Serverfehler: {{.Operations.API.LastError.Format "02.01.2006 15:04 MST"}}{{end}} +
+
+
⇄
Entwicklung

Gitea · Landwelle

+ {{if .Operations.Gitea.Available}} +
{{.Operations.Gitea.Branch}} · {{.Operations.Gitea.ShortCommit}}{{.Operations.Gitea.Message}}
+
Repository-Version{{if .Operations.Gitea.SourceVersion}}v{{.Operations.Gitea.SourceVersion}}{{else}}Unbekannt{{end}}
Produktivversion{{.Version}}
+
{{.Operations.Gitea.CIStatus}}CI für aktuellen Commit
+ {{if .Operations.Gitea.CIRunURL}}CI-Lauf ansehen{{end}} + {{else}}

Repository-Status wird geladen oder ist nicht erreichbar.

{{end}} +
{{.Operations.Deployment}}Installierter Build: {{.Operations.BuildCommit}}
+ {{if not .Operations.Gitea.CheckedAt.IsZero}}Stand: {{.Operations.Gitea.CheckedAt.Format "02.01.2006 15:04 MST"}}{{end}} +

Repository öffnen

+
diff --git a/cmd/portal/wish_audio_test.go b/cmd/portal/wish_audio_test.go index 20f3774..c55cb08 100644 --- a/cmd/portal/wish_audio_test.go +++ b/cmd/portal/wish_audio_test.go @@ -59,8 +59,12 @@ func TestManualWishProductionUsesManualWorkflow(t *testing.T) { t.Fatal(err) } text := string(body) - if !strings.Contains(text, `a.wishAutomation.ProcessManual(ctx, wish)`) { - t.Fatal("manual wish production is not routed through ProcessManual") + if !strings.Contains(text, `a.enqueueWishProduction(r.Context(), id, true)`) { + t.Fatal("manual wish production is not routed through persistent queue") + } + worker, err := os.ReadFile("production_queue.go") + if err != nil || !strings.Contains(string(worker), `a.wishAutomation.ProcessManual(ctx, wish)`) { + t.Fatal("worker does not preserve manual production") } if !strings.Contains(text, `wishSettings.Enabled && wishSettings.AutoProcessOnApprove`) { t.Fatal("automatic approval must require both automation switches") diff --git a/cmd/portal/wishes.go b/cmd/portal/wishes.go index f4a2fa9..30246de 100644 --- a/cmd/portal/wishes.go +++ b/cmd/portal/wishes.go @@ -100,6 +100,8 @@ func newWishStore(databases ...*postgresStore) (*wishStore, error) { } func (s *wishStore) load() error { + s.mu.Lock() + defer s.mu.Unlock() if s.db != nil && s.db.Enabled() { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2a3af8e..559dcd8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -14,7 +14,7 @@ Browser (Website + Player) / Redaktion (Admin) Dateiablage /var/lib/landwelle ``` -Go-Version 1.24.4, Backend ohne externe Go-Pakete, `go:embed web`, systemd: `landwelle-radio`, Konfigurationsdatei `/etc/landwelle/landwelle.env`. +Go-Version 1.27.4, Backend mit nativem pgx-PostgreSQL-Treiber, `go:embed web`, systemd: `landwelle-radio`, Konfigurationsdatei `/etc/landwelle/landwelle.env`. **Öffentliche Wege:** `/` (Startseite), `/player` (Popup-Webplayer), `/programm`, `/highlights`, `/highlights/`, `/veranstaltungen`, `/mediathek`, `/admin/highlights`, `/admin/seasons`, `/admin/todos`, `/api/v1/` (Website-API). Keine Mobile-/Desktop-App-Dienste und kein Firebase. diff --git a/docs/CHATUEBERGABE.md b/docs/CHATUEBERGABE.md index 19f1a83..3514b28 100644 --- a/docs/CHATUEBERGABE.md +++ b/docs/CHATUEBERGABE.md @@ -1,13 +1,13 @@ # Landwelle – Projektübergabe -**Aktueller Quellstand: v1.5.82 (3. Dezember 2026)** +**Aktueller Quellstand: v1.5.83 (3. Dezember 2026)** Dieses Repository ist die verbindliche Gitea-Quelle für das Landwelle-Webportal. Die frühere Übergabe zu einer eigenständigen ZIP-Ausgabe ist überholt. ## Architektur und Betrieb - Go-Monolith mit eingebetteten Web-Templates und statischen Assets -- PostgreSQL und unveränderliche SQL-Migrationen bis 0050 +- PostgreSQL und unveränderliche SQL-Migrationen bis 0051 - Linux x64; Dienst `landwelle-radio`; Port `127.0.0.1:2200` - Binary: `/opt/landwelle/landwelle-portal` - Secrets: `/etc/landwelle/landwelle.env` @@ -22,6 +22,8 @@ Firebase, mobile App-APIs, IT-App-Push und ehemalige clientseitige App-Repositor ## Entwicklung +Go 1.27.4, nativer pgx-Pool, persistente Produktionswarteschlange, Scheduler- und Monitoring-Pakete sowie Gitea-Dashboard: [PLATFORM_MODERNIZATION.md](PLATFORM_MODERNIZATION.md). + Portal-Quellcode und paketinterne Tests liegen unter `cmd/portal/`, eingebettete HTML-/CSS-/JS-/Mediendateien unter `cmd/portal/web/`. Die Projektstruktur ist in [PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md) erklärt. Auf dem Gitea-Hauptbranch `main` arbeiten, größere Änderungen über Featurebranch und Pull Request. Die Gitea-Workflows befinden sich unter `.gitea/workflows/`, erfordern einen Actions-Runner und deployen **nicht** automatisch. diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index b134de7..241a8b3 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -1,7 +1,7 @@ # Aktueller technischer Projektstand **Stand:** 3. Dezember 2026 -**Anwendung:** Landwelle v1.5.82 +**Anwendung:** Landwelle v1.5.83 **Versionsverwaltung:** Gitea, `nexverse/landwelle`, Hauptbranch `main` **Betrieb:** Linux x64, systemd `landwelle-radio`, KeyHelp-Reverse-Proxy @@ -15,11 +15,11 @@ Der Startseiten-Player spielt vor dem Livestream die bereitgestellte KI-Transpar Redaktion, Mediengalerie (mit Favoritenfunktion), Programm, Team, Veranstaltungen, Highlights, Navigation, Saisonsteuerung, Statistik, Downloads und weitere Seiten werden über den geschützten Adminbereich verwaltet. -Das KI-Nachrichtenstudio und die KI-Audiomodule nutzen konfigurierte OpenAI-/ElevenLabs-/ffmpeg-/FTP-Verarbeitung. Der zentrale, token-geschützte Cron-Endpunkt startet geplante Aufgaben. Die seit v1.5.80 behobenen Zuordnungsfehler sind im Quellcode berücksichtigt. +Das KI-Nachrichtenstudio und die KI-Audiomodule nutzen konfigurierte OpenAI-/ElevenLabs-/ffmpeg-/FTP-Verarbeitung. Der zentrale, token-geschützte Cron-Endpunkt legt geplante Aufgaben atomar in der persistenten PostgreSQL-Warteschlange ab. Nachrichtenstudio, Audio-Rubriken und Musikwünsche nutzen dieselbe Warteschlange. Das Admin-Dashboard zeigt Job-, Cron-, Datenbank-, API- und Gitea-Status. PostgreSQL-Abfragen der Webanwendung nutzen einen nativen pgx-Verbindungspool. Die seit v1.5.80 behobenen Zuordnungsfehler sind im Quellcode berücksichtigt. ## Datenbank und Sicherheit -PostgreSQL ist die verbindliche Datenbank. Die produktive Migrationshistorie reicht bis `0050_media_favorites.sql`; `9000_landwelle_zuhause_navigation.sql` gehört zur älteren gesonderten Navigationsmigration. Historische App-Tabellen und Migrationen bleiben aus Gründen der Bestandssicherheit erhalten, obwohl Firebase, mobile Apps und Push-Funktionen aus der laufenden Anwendung entfernt wurden. +PostgreSQL ist die verbindliche Datenbank. Die produktive Migrationshistorie reicht bis `0051_ai_production_queue.sql`; `9000_landwelle_zuhause_navigation.sql` gehört zur älteren gesonderten Navigationsmigration. Historische App-Tabellen und Migrationen bleiben aus Gründen der Bestandssicherheit erhalten, obwohl Firebase, mobile Apps und Push-Funktionen aus der laufenden Anwendung entfernt wurden. Zugangsdaten liegen außerhalb des Repositories unter `/etc/landwelle/landwelle.env`. Persistente Dateien liegen unter `/var/lib/landwelle`. diff --git a/docs/PLATFORM_MODERNIZATION.md b/docs/PLATFORM_MODERNIZATION.md new file mode 100644 index 0000000..8a0b2eb --- /dev/null +++ b/docs/PLATFORM_MODERNIZATION.md @@ -0,0 +1,54 @@ +# Landwelle v1.5.83 – Plattformmodernisierung + +## Toolchain und Module + +Die Webanwendung nutzt Go 1.27.4. Die Versionsvorgabe steht in `go.mod`; Gitea Actions nutzt dieselbe Toolchain. Die neue Anwendung bleibt ein Linux-x64-Binary ohne zusätzliche Go-Runtime im Produktivbetrieb. Der serverweite Go-Installationspfad anderer Projekte muss nicht geändert werden. + +Die unabhängigen Infrastrukturbausteine liegen in `internal/database`, `internal/jobqueue`, `internal/scheduler`, `internal/monitoring` und `internal/giteastatus`. Die bestehenden Radio-, Redaktions- und Adminhandler bilden weiterhin einen zusammenhängenden modularen Monolithen. Weitere Fachpakete werden getrennt nach ihrem Abhängigkeitsmodell ausgelagert, nicht durch bloßes Verschieben. + +## PostgreSQL + +Die Webanwendung verwendet pgx v5 und einen gemeinsamen Connection-Pool (Standard 8, konfigurierbar über `LANDWELLE_DB_MAX_CONNECTIONS` von 3 bis 32). Die bestehende `DATABASE_URL` bleibt gültig. Die Pool-Verbindungen nutzen `landwelle,public`, UTC und standardkonforme SQL-Strings. + +Die zentrale Kompatibilitätsschicht liefert den bisherigen zeilenorientierten SQL-Text an ältere Stores; neue Auftragsqueries sind parametrisiert. Die vollständige Parametrisierung der älteren Fachqueries ist ein eigenständiges, schrittweises Refactoring. Der separate Migrator sowie PostgreSQL-Backup- und Restorewerkzeuge verwenden weiterhin PostgreSQL-CLI-Programme. Die Webanwendung startet für ihre SQL-Abfragen keine `psql`-Prozesse mehr. + +## Dauerhafte Produktionswarteschlange + +Migration `0051_ai_production_queue.sql` ergänzt ausschließlich eine Tabelle und Indizes. Bei konfigurierter Datenbank startet das neue Portal nicht ohne diese Migration. + +- Manuelle Nachrichten- und Audioproduktion speichert einen Auftrag mit den fachlichen Eingaben. Provider-/FTP-Zugangsdaten werden erst beim Ausführen aus den vorhandenen Einstellungen gelesen. +- Automatische KeyHelp-Cron-Aufträge werden innerhalb desselben SQL-Statements beansprucht und eingereiht. Berlin-Minuten werden auch bei der doppelten Herbststunde dedupliziert. +- Musikwünsche speichern nur ihre Referenz und die Produktionsart. Es gibt höchstens einen gleichzeitig wartenden oder laufenden Auftrag je Wunsch. „Nur posten – ohne MP3“ bleibt unabhängig. +- Ein Worker verarbeitet die Warteschlange seriell; PostgreSQL verhindert konkurrierende Claims. Wartende Aufträge bleiben bei Neustarts erhalten. Geplante Sendebeiträge, die seit mehr als 30 Minuten warten, werden aus Gründen der Aktualität mit Fehler beendet. Manuelle wartende Aufträge bleiben verfügbar. +- Laufende Produktionen haben ein Zeitbudget von 12 Minuten. Nach einem ungeplanten Abbruch wird ein nach 15 Minuten nicht abgeschlossener Auftrag als Fehler markiert. Er wird **nicht automatisch wiederholt**: Eine MP3 könnte bereits erzeugt oder auf das FTP-Ziel übertragen worden sein. Redaktionell prüfen und bei Bedarf bewusst neu produzieren. +- Fortschritt, Ergebnis und Auftragsstatus werden gespeichert. Die bisherigen Produktionsdialoge und Status-Endpunkte bleiben erhalten. Die manuelle Sprechtextvorschau ohne vollständige Audioproduktion bleibt synchron. +- Historie wird nicht automatisch gelöscht. Eine spätere Aufbewahrungsregel ist separat zu definieren. Inhalte und Fehlerdetails bleiben im geschützten System; bekannte Providergeheimnisse werden aus gespeicherten Jobmeldungen entfernt. + +## Dashboard + +Unter `/admin` werden zusätzlich angezeigt: + +- tatsächlicher PostgreSQL-Ping und Pool-Auslastung; +- Cron-Heartbeat und letzter Aufruf; +- wartende, laufende, erfolgreiche und fehlgeschlagene Aufträge sowie die letzten acht Produktionen; +- aggregierte API-Aufrufe, HTTP-5xx und mittlere Antwortzeit seit Prozessstart (keine IP-Adressen oder Request-Bodies); +- Gitea-Repository, Branch `main`, Commit, Commit-Betreff, Anwendungsstand des Quellcodes, CI-Ergebnis für genau diesen Commit und Vergleich mit dem installierten Build. + +Gitea wird lesend mit HTTPS und begrenzten Timeouts etwa einmal pro Minute abgefragt. Für diese öffentliche Repository-Ansicht wird kein Token benötigt. CI-Run-IDs werden aus der öffentlichen Gitea-Actions-Liste ermittelt und anschließend über die einzelne Run-API gegen den Commit geprüft. Ist die Ansicht nicht erreichbar oder ändert sich ihr Format, wird der Status als unbekannt angezeigt, nicht fälschlich als erfolgreich. + +## Release und Prüfung + +Vor dem Update die produktive PostgreSQL-Datenbank, Medien und Konfiguration sichern. Zunächst Migration 0051 anwenden, dann die getestete Linux-x64-Binary einspielen. Der bestehende KeyHelp-Cron-Aufruf, Port 2200, systemd-Dienst und externe Stream bleiben unverändert. + +```bash +go mod verify +go test ./... +go vet ./... +./scripts/test-postgres-integration.sh +./scripts/build-x64.sh +./scripts/build-migrator-x64.sh +``` + +Der Integrationstest verwendet einen ausschließlich über einen privaten Unix-Socket erreichbaren, temporären PostgreSQL-Cluster. Er prüft sämtliche Migrationen, native SQL-Abfragen, Fehler in Transaktionen, parallele Cron-Claims, persistente Aufträge, Musikwunsch-Deduplizierung und die Behandlung unterbrochener Aufträge. Er verwendet weder die produktive Datenbank noch echte KI-/FTP-Zugangsdaten. + +Ein späterer Rollback auf v1.5.82 kann die zusätzliche Tabelle gefahrlos belassen. Wartende neue Aufträge werden von der alten Version nicht verarbeitet. Vor einem Rollback deshalb den Produktionsstatus prüfen; niemals eine DB-Sicherung ohne Abstimmung über produktive Daten zurückspielen. diff --git a/docs/PROJECT_STRUCTURE.md b/docs/PROJECT_STRUCTURE.md index 7d0a353..a75d548 100644 --- a/docs/PROJECT_STRUCTURE.md +++ b/docs/PROJECT_STRUCTURE.md @@ -13,6 +13,11 @@ Diese Übersicht hilft dabei, Änderungen im Landwelle-Portal schnell dem richti | `cmd/migrate/` | PostgreSQL-Migrator | | `cmd/adminpass/` | Passwort-Hash-Hilfsprogramm | | `internal/auth/` | Interne Authentifizierungslogik | +| `internal/database/` | Native PostgreSQL-Verbindungspools und SQL-Kompatibilität | +| `internal/jobqueue/` | Persistente Produktionsaufträge und atomare Claims | +| `internal/scheduler/` | Zeitzonen- und Zeitplanregeln | +| `internal/monitoring/` | Aggregierte HTTP-API-Messwerte | +| `internal/giteastatus/` | Commitgenauer, gecachter Gitea-Status | | `migrations/` | Versionsgebundene SQL-Migrationen (nicht umnummerieren oder rückwirkend ändern) | | `scripts/` | Ausführbare Build-, Update-, Backup- und Prüfscripte | | `deploy/` | systemd- und KeyHelp-Konfigurationsbeispiele | @@ -51,7 +56,7 @@ Die folgenden Dateien befinden sich in `cmd/portal/`. Dateien mit fachlich passe Das Portal ist derzeit ein Go-Monolith mit gemeinsam genutzten Datentypen, Stores, Handlern und Templates. Eine rein optische Verteilung auf viele Unterordner würde neue Go-Pakete und damit andere Sichtbarkeiten sowie Importabhängigkeiten erzeugen. Das wäre eine eigenständige Architekturänderung und ist nicht Teil dieser Repository-Bereinigung. -Darum bleiben zusammengehörige Quell- und Testdateien vorerst im Portalpaket. Neue, fachlich unabhängige Komponenten können schrittweise in eigene Pakete unter `internal/` ausgelagert werden. Jede solche Änderung benötigt eigene Tests. +Seit v1.5.83 sind Datenbank, Warteschlange, Scheduler, Monitoring und Gitea-Zugriff eigenständige Pakete unter `internal/`. Die übrigen eng gekoppelten HTTP-Handler und redaktionellen Fachmodule verbleiben vorerst gemeinsam im Portalpaket. Weitere fachlich unabhängige Komponenten können schrittweise ausgelagert werden. Jede solche Änderung benötigt eigene Tests. ## Test- und Build-Regeln diff --git a/docs/README.md b/docs/README.md index 0470ba0..ecb6986 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ Willkommen bei den technischen Unterlagen des Landwelle-Webportals. Der erste Ü - [Aktueller Projektstand](CURRENT_STATE.md) - [Projektstruktur und Modulübersicht](PROJECT_STRUCTURE.md) +- [Plattformmodernisierung und Betriebsmonitoring](PLATFORM_MODERNIZATION.md) - [Roadmap](ROADMAP.md) - [Projektübergabe](CHATUEBERGABE.md) - [Architektur](ARCHITECTURE.md) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 9e836a3..db25ac3 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,6 +1,6 @@ # Landwelle – Entwicklungsfahrplan -**Stand: Dezember 2026 · Webportal v1.5.82** +**Stand: Dezember 2026 · Webportal v1.5.83** Landwelle wird als Webradio und Regionalportal für Niedersachsen weiterentwickelt. Dieser Fahrplan beschreibt mögliche nächste Schritte – keine Zusage für feste Veröffentlichungstermine. @@ -13,10 +13,11 @@ Landwelle wird als Webradio und Regionalportal für Niedersachsen weiterentwicke - Startseiten-Highlights mit Detailseiten und Saison-Designs - Favoriten in der Mediengalerie und in der Beitragsbildauswahl - Entfernen der aktiven Firebase-, Push- und App-Integrationen +- Go 1.27.4, nativer PostgreSQL-Pool, persistente Produktionswarteschlange und Admin-Monitoring inklusive Gitea ## Nächste technische Schwerpunkte -1. **Zuverlässigkeit:** Cron- und Produktionshistorie, sichere Wiederholung fehlgeschlagener OpenAI-/ElevenLabs-/FTP-Aufgaben, Monitoring und Restore-Tests. +1. **Zuverlässigkeit:** Ausbau der Produktionshistorie, sichere redaktionelle Wiederholung fehlgeschlagener OpenAI-/ElevenLabs-/FTP-Aufträge und regelmäßige Restore-Tests. 2. **Redaktion:** klarer Freigabeworkflow, Beitragsplanung, Versionen, wiederverwendbare Vorlagen und bessere Medienauswahl. 3. **Regionales Angebot:** Ausflugstipps, Sagen, Traditionen, Orte, norddeutsche Küche und regionale Beitragsreihen. 4. **Mediathek:** Suche, Audiolängen, Sendungsreihen, Dateikontrolle und sauberer Export. diff --git a/docs/TESTING.md b/docs/TESTING.md index f857d9e..0a7a4a5 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,6 +1,6 @@ # Teststrategie -**Stand: Landwelle v1.5.82 – neue Repository-Struktur** +**Stand: Landwelle v1.5.83 – native PostgreSQL-Anbindung** ## Verbindliche Basisprüfung @@ -18,6 +18,10 @@ Bei Änderungen an Nebenläufigkeit, Caches oder Hintergrundjobs zusätzlich: go test -race ./... ``` +## Echte PostgreSQL-Integration + +`./scripts/test-postgres-integration.sh` baut eine isolierte, nur über einen privaten Unix-Socket erreichbare PostgreSQL-Testinstanz auf, führt sämtliche Migrationen aus und testet den Verbindungspool sowie die dauerhafte Auftragsverarbeitung. Die produktive Datenbank wird dabei nicht verwendet. Normale `go test ./...`-Läufe überspringen Tests, die die explizite Test-Datenbankadresse benötigen. + ## Syntax- und Strukturprüfungen - alle JavaScript-Dateien mit `node --check` prüfen diff --git a/go.mod b/go.mod index 859ca39..ad12e6f 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,13 @@ module landwelle-portal -go 1.23 +go 1.27.4 -toolchain go1.24.4 +require github.com/jackc/pgx/v5 v5.13.0 + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/text v0.41.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8c34db7 --- /dev/null +++ b/go.sum @@ -0,0 +1,26 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/database/pool.go b/internal/database/pool.go new file mode 100644 index 0000000..12fa624 --- /dev/null +++ b/internal/database/pool.go @@ -0,0 +1,71 @@ +// Package database manages native PostgreSQL connections and the legacy text +// query contract used by portal repositories. +package database + +import ( + "bytes" + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func Open(ctx context.Context, dsn string, max int32) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil { + return nil, fmt.Errorf("ungültige PostgreSQL-Konfiguration") + } + cfg.MaxConns = max + cfg.MinConns = 0 + cfg.MaxConnIdleTime = 5 * time.Minute + cfg.MaxConnLifetime = 30 * time.Minute + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + cfg.ConnConfig.RuntimeParams["search_path"] = "landwelle,public" + cfg.ConnConfig.RuntimeParams["application_name"] = "landwelle-portal" + cfg.ConnConfig.RuntimeParams["standard_conforming_strings"] = "on" + cfg.ConnConfig.RuntimeParams["timezone"] = "UTC" + p, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, err + } + if err = p.Ping(ctx); err != nil { + p.Close() + return nil, fmt.Errorf("PostgreSQL nicht erreichbar: %w", err) + } + return p, nil +} + +// Text executes existing trusted, escaped SQL in the simple query protocol. +// It preserves psql's tuples-only row output, including multi-statement +// transactions, without spawning an operating-system process. New code should +// use pgx's parameterized queries instead. +func Text(ctx context.Context, p *pgxpool.Pool, sql string) ([]byte, error) { + c, err := p.Acquire(ctx) + if err != nil { + return nil, err + } + defer c.Release() + results, err := c.Conn().PgConn().Exec(ctx, sql).ReadAll() + if err != nil { + // pgxpool discards a non-idle connection on release. No failed transaction + // or session state may leak into the next request. + return nil, err + } + var b bytes.Buffer + for _, res := range results { + if res.Err != nil { + return nil, res.Err + } + for _, row := range res.Rows { + for i, col := range row { + if i > 0 { + b.WriteByte('|') + } + b.Write(col) + } + b.WriteByte('\n') + } + } + return b.Bytes(), nil +} diff --git a/internal/database/pool_integration_test.go b/internal/database/pool_integration_test.go new file mode 100644 index 0000000..3840ac3 --- /dev/null +++ b/internal/database/pool_integration_test.go @@ -0,0 +1,49 @@ +package database + +import ( + "context" + "os" + "strings" + "testing" + "time" +) + +func TestNativePoolWithIsolatedPostgres(t *testing.T) { + dsn := os.Getenv("LANDWELLE_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires disposable PostgreSQL test database") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + p, err := Open(ctx, dsn, 3) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if p.Config().ConnConfig.Database != "landwelle_test" { + t.Fatal("refusing non-test database") + } + for _, tc := range []struct{ sql, want string }{ + {"SELECT 42;", "42"}, + {"SELECT json_build_array(json_build_object('id',7))::text;", "[{\"id\" : 7}]"}, + {"SHOW search_path;", "landwelle,public"}, + {"SELECT 'a''b';", "a'b"}, + } { + got, err := Text(ctx, p, tc.sql) + if err != nil { + t.Fatal(err) + } + if strings.ReplaceAll(strings.TrimSpace(string(got)), " ", "") != strings.ReplaceAll(tc.want, " ", "") { + t.Fatalf("%s: got %q want %q", tc.sql, got, tc.want) + } + } + if _, err := Text(ctx, p, "BEGIN; SELECT 1/0; COMMIT;"); err == nil { + t.Fatal("failed transaction did not return error") + } + if got, err := Text(ctx, p, "SELECT 123;"); err != nil || strings.TrimSpace(string(got)) != "123" { + t.Fatalf("pool unusable after failed transaction: %s %v", got, err) + } + if p.Stat().MaxConns() != 3 { + t.Fatal("pool limit ignored") + } +} diff --git a/internal/giteastatus/status.go b/internal/giteastatus/status.go new file mode 100644 index 0000000..5065cf6 --- /dev/null +++ b/internal/giteastatus/status.go @@ -0,0 +1,158 @@ +// Package giteastatus reads the public Landwelle repository, without secrets. +// The Actions list API requires auth on this Gitea instance; the public run +// listing provides run IDs, which are validated with the individual run API. +package giteastatus + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "sync" + "time" +) + +const Repository = "https://git.stadt-nexverse.de/nexverse/landwelle" +const API = "https://git.stadt-nexverse.de/api/v1/repos/nexverse/landwelle" + +type Snapshot struct { + Available bool + Branch, Commit, Message, SourceVersion, CIStatus, CIRunURL string + CommitAt, CheckedAt time.Time +} + +func (s Snapshot) ShortCommit() string { + if len(s.Commit) > 12 { + return s.Commit[:12] + } + return s.Commit +} +func (s Snapshot) Deployment(build string) string { + if build == "" || build == "unknown" || !s.Available { + return "Nicht verifizierbar" + } + if len(build) >= 7 && strings.HasPrefix(s.Commit, build) { + return "Commit identisch" + } + return "Abweichender Build" +} + +type Service struct { + mu sync.RWMutex + value Snapshot +} + +func (s *Service) Get() Snapshot { s.mu.RLock(); defer s.mu.RUnlock(); return s.value } +func (s *Service) Run(ctx context.Context) { + ticker := time.NewTicker(60 * time.Second) + defer ticker.Stop() + client := &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) > 3 || req.URL.Host != "git.stadt-nexverse.de" { + return fmt.Errorf("unerwartete Weiterleitung") + } + return nil + }} + for { + if ctx.Err() != nil { + return + } + result := fetch(ctx, client, Repository, API) + s.mu.Lock() + s.value = result + s.mu.Unlock() + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} +func read(ctx context.Context, c *http.Client, u string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json, text/plain, text/html") + resp, err := c.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return nil, fmt.Errorf("HTTP %d", resp.StatusCode) + } + return io.ReadAll(io.LimitReader(resp.Body, 1<<20)) +} + +var hashRE = regexp.MustCompile("^[0-9a-f]{40,64}$") +var runRE = regexp.MustCompile("id=\"action-run-item-([0-9]+)\"") +var versionRE = regexp.MustCompile("(?m)^\\s*applicationVersion\\s*=\\s*\"([0-9]+\\.[0-9]+\\.[0-9]+)\"") + +func fetch(ctx context.Context, c *http.Client, repo, api string) Snapshot { + s := Snapshot{Branch: "main", CIStatus: "Unbekannt", CheckedAt: time.Now()} + b, err := read(ctx, c, api+"/branches/main") + if err != nil { + return s + } + var branch struct { + Commit struct { + ID, Message string + Timestamp time.Time + } + } + if json.Unmarshal(b, &branch) != nil || !hashRE.MatchString(branch.Commit.ID) { + return s + } + s.Available = true + s.Commit = branch.Commit.ID + s.CommitAt = branch.Commit.Timestamp + s.Message = strings.SplitN(branch.Commit.Message, "\n", 2)[0] + if len(s.Message) > 240 { + s.Message = s.Message[:240] + } + // Pin source version to the exact commit, not a moving branch. + if raw, e := read(ctx, c, repo+"/raw/commit/"+s.Commit+"/cmd/portal/main.go"); e == nil { + if m := versionRE.FindSubmatch(raw); len(m) == 2 { + s.SourceVersion = string(m[1]) + } + } + html, e := read(ctx, c, repo+"/actions?workflow=ci.yml&branch=main") + if e != nil { + return s + } + s.CIStatus = "Noch kein Ergebnis für diesen Commit" + for _, m := range runRE.FindAllSubmatch(html, 5) { + id := string(m[1]) + data, e := read(ctx, c, api+"/actions/runs/"+id) + if e != nil { + continue + } + var run struct { + HeadSHA string `json:"head_sha"` + Status, Conclusion, Path string + } + if json.Unmarshal(data, &run) != nil || run.HeadSHA != s.Commit || !strings.HasPrefix(run.Path, "ci.yml@") { + continue + } + s.CIRunURL = repo + "/actions/runs/" + id + switch run.Conclusion { + case "success": + s.CIStatus = "Bestanden" + case "failure": + s.CIStatus = "Fehlgeschlagen" + case "cancelled", "canceled": + s.CIStatus = "Abgebrochen" + default: + if run.Status == "completed" { + s.CIStatus = "Abgeschlossen (Ergebnis unbekannt)" + } else { + s.CIStatus = "Läuft / wartet" + } + } + break + } + return s +} diff --git a/internal/giteastatus/status_test.go b/internal/giteastatus/status_test.go new file mode 100644 index 0000000..7c49d38 --- /dev/null +++ b/internal/giteastatus/status_test.go @@ -0,0 +1,34 @@ +package giteastatus + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCommitSpecificStatus(t *testing.T) { + sha := strings.Repeat("a", 40) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/branches/main"): + w.Write([]byte("{\"commit\":{\"id\":\"" + sha + "\",\"message\":\"Update\\nDetails\"}}")) + case strings.Contains(r.URL.Path, "/raw/commit/"): + w.Write([]byte("applicationVersion = \"1.5.83\"")) + case strings.HasSuffix(r.URL.Path, "/actions"): + w.Write([]byte("
")) + case strings.HasSuffix(r.URL.Path, "/runs/2"): + w.Write([]byte("{\"head_sha\":\"" + strings.Repeat("b", 40) + "\",\"path\":\"ci.yml@refs/heads/main\",\"status\":\"completed\",\"conclusion\":\"success\"}")) + case strings.HasSuffix(r.URL.Path, "/runs/1"): + w.Write([]byte("{\"head_sha\":\"" + sha + "\",\"path\":\"ci.yml@refs/heads/main\",\"status\":\"completed\",\"conclusion\":\"failure\"}")) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + s := fetch(context.Background(), server.Client(), server.URL, server.URL+"/api") + if !s.Available || s.SourceVersion != "1.5.83" || s.CIStatus != "Fehlgeschlagen" || !strings.HasSuffix(s.CIRunURL, "/1") || s.Deployment(sha[:12]) != "Commit identisch" { + t.Fatalf("unexpected snapshot: %+v", s) + } +} diff --git a/internal/jobqueue/queue.go b/internal/jobqueue/queue.go new file mode 100644 index 0000000..60915d1 --- /dev/null +++ b/internal/jobqueue/queue.go @@ -0,0 +1,121 @@ +// Package jobqueue owns durable production scheduling, claims and state. +// PostgreSQL is the source of truth. No credentials are part of the command. +package jobqueue + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type Queue struct{ Pool *pgxpool.Pool } +type Job struct { + ID, Channel, Kind, Status, Error string + Payload, Snapshot json.RawMessage + CreatedAt, UpdatedAt time.Time + TaskID *int64 + ScheduledAt *time.Time +} +type Summary struct { + Queued, Running, Done, Failed int64 + Recent []Job +} + +const columns = "id,channel,kind,status,error,payload,snapshot,created_at,updated_at,task_id,scheduled_at" + +func scan(r pgx.Row) (j Job, err error) { + err = r.Scan(&j.ID, &j.Channel, &j.Kind, &j.Status, &j.Error, &j.Payload, &j.Snapshot, &j.CreatedAt, &j.UpdatedAt, &j.TaskID, &j.ScheduledAt) + return +} +func (q Queue) Enqueue(ctx context.Context, j Job) error { + _, err := q.Pool.Exec(ctx, "INSERT INTO landwelle.ai_production_queue(id,channel,kind,payload,snapshot) VALUES($1,$2,$3,$4,$5)", j.ID, j.Channel, j.Kind, j.Payload, j.Snapshot) + return err +} +func (q Queue) EnqueueWish(ctx context.Context, j Job, wishID string) (bool, error) { + tag, err := q.Pool.Exec(ctx, "INSERT INTO landwelle.ai_production_queue(id,channel,kind,payload,snapshot,dedupe_key) VALUES($1,$2,'wish',$3,$4,$5) ON CONFLICT(dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('queued','running') DO NOTHING", j.ID, j.Channel, j.Payload, j.Snapshot, "wish:"+wishID) + return tag.RowsAffected() == 1, err +} + +// Claiming the scheduled minute and inserting the durable command are atomic. +// Preserve Berlin wall-clock deduplication including the DST repeated hour. +const ScheduledSQL = "WITH claimed AS (UPDATE landwelle.ai_auto_tasks SET last_run_at=$2,last_status='queued',last_error='',updated_at=now() WHERE id=$1 AND active AND task_key=$3 AND (last_run_at IS NULL OR date_trunc('minute',last_run_at AT TIME ZONE 'Europe/Berlin') IS DISTINCT FROM date_trunc('minute',$2::timestamptz AT TIME ZONE 'Europe/Berlin')) RETURNING id,last_run_at) INSERT INTO landwelle.ai_production_queue(id,channel,kind,payload,snapshot,task_id,scheduled_at) SELECT $4,$3,'scheduled',$5,$6,id,last_run_at FROM claimed" + +func (q Queue) EnqueueScheduled(ctx context.Context, task int64, when time.Time, j Job) (bool, error) { + tag, err := q.Pool.Exec(ctx, ScheduledSQL, task, when, j.Channel, j.ID, j.Payload, j.Snapshot) + return tag.RowsAffected() == 1, err +} + +// One producer at a time across processes prevents concurrent writes to the +// same broadcast FTP target. Expire interrupted work after its 12-min deadline +// plus a safety margin; never replay ambiguous external side effects. +func (q Queue) Claim(ctx context.Context) (Job, bool, error) { + tx, err := q.Pool.Begin(ctx) + if err != nil { + return Job{}, false, err + } + defer tx.Rollback(context.Background()) + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(72411983)"); err != nil { + return Job{}, false, err + } + _, err = tx.Exec(ctx, "WITH expired AS (UPDATE landwelle.ai_production_queue SET status='error',error=CASE WHEN status='running' THEN 'Produktion unterbrochen; FTP-Ziel vor erneutem Start prüfen.' ELSE 'Geplanter Auftrag zu alt; redaktionell neu starten.' END,finished_at=now(),updated_at=now() WHERE (status='running' AND started_at 0 { + s.AverageMS = m.elapsed.Load() / n + } + if n := m.lastError.Load(); n > 0 { + s.LastError = time.Unix(int64(n), 0) + } + return s +} + +type writer struct { + http.ResponseWriter + status int +} + +func (w *writer) WriteHeader(s int) { + if w.status != 0 { + return + } + if s >= 200 { + w.status = s + } + w.ResponseWriter.WriteHeader(s) +} +func (w *writer) Write(b []byte) (int, error) { + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } + return w.ResponseWriter.Write(b) +} +func (w *writer) Unwrap() http.ResponseWriter { return w.ResponseWriter } +func (w *writer) Flush() { + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } + _ = http.NewResponseController(w.ResponseWriter).Flush() +} +func (m *Metrics) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api" && !strings.HasPrefix(r.URL.Path, "/api/") { + next.ServeHTTP(w, r) + return + } + start := time.Now() + rw := &writer{ResponseWriter: w} + defer func() { + m.elapsed.Add(uint64(time.Since(start).Milliseconds())) + m.requests.Add(1) + if rw.status >= 500 { + m.errors.Add(1) + m.lastError.Store(uint64(time.Now().Unix())) + } + }() + next.ServeHTTP(rw, r) + }) +} diff --git a/internal/monitoring/http_test.go b/internal/monitoring/http_test.go new file mode 100644 index 0000000..ba29c61 --- /dev/null +++ b/internal/monitoring/http_test.go @@ -0,0 +1,25 @@ +package monitoring + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestAPIAggregate(t *testing.T) { + m := &Metrics{} + h := m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/error" { + http.Error(w, "error", 503) + return + } + w.Write([]byte("ok")) + })) + for _, p := range []string{"/", "/api", "/api/error", "/api/v1/info"} { + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", p, nil)) + } + s := m.Snapshot() + if s.Requests != 3 || s.Errors != 1 || s.LastError.IsZero() { + t.Fatalf("bad aggregate: %+v", s) + } +} diff --git a/internal/scheduler/schedule.go b/internal/scheduler/schedule.go new file mode 100644 index 0000000..3cce8c3 --- /dev/null +++ b/internal/scheduler/schedule.go @@ -0,0 +1,59 @@ +// Package scheduler owns the calendar and wall-clock scheduling policy for +// Landwelle's external KeyHelp cron trigger. It has no database or HTTP dependencies. +package scheduler + +import ( + "strconv" + "strings" + "time" + _ "time/tzdata" +) + +var berlin = func() *time.Location { + l, err := time.LoadLocation("Europe/Berlin") + if err != nil { + panic(err) + } + return l +}() + +func Berlin() *time.Location { return berlin } +func ParseDays(v string) []int { + var out []int + for _, p := range strings.Split(v, ",") { + n, err := strconv.Atoi(strings.TrimSpace(p)) + if err == nil && n >= 1 && n <= 7 { + out = append(out, n) + } + } + return out +} +func DaysCSV(days []int) string { + var out []string + for _, d := range days { + out = append(out, strconv.Itoa(d)) + } + return strings.Join(out, ",") +} +func Due(active bool, clock string, days []int, now time.Time) bool { + if !active { + return false + } + local := now.In(berlin) + if strings.TrimSpace(clock) != local.Format("15:04") { + return false + } + weekday := int(local.Weekday()) + if weekday == 0 { + weekday = 7 + } + for _, d := range days { + if d == weekday { + return true + } + } + return false +} +func SameMinute(last *time.Time, now time.Time) bool { + return last != nil && last.In(berlin).Format("2006-01-02 15:04") == now.In(berlin).Format("2006-01-02 15:04") +} diff --git a/internal/scheduler/schedule_test.go b/internal/scheduler/schedule_test.go new file mode 100644 index 0000000..009f502 --- /dev/null +++ b/internal/scheduler/schedule_test.go @@ -0,0 +1,17 @@ +package scheduler + +import ( + "testing" + "time" +) + +func TestBerlinRepeatedHour(t *testing.T) { + first := time.Date(2026, 10, 25, 0, 30, 0, 0, time.UTC) + second := first.Add(time.Hour) + if !Due(true, "02:30", []int{7}, first) || !Due(true, "02:30", []int{7}, second) || !SameMinute(&first, second) { + t.Fatal("repeated Berlin minute must be deduplicated") + } + if SameMinute(nil, second) || SameMinute(&first, second.Add(time.Minute)) { + t.Fatal("different minute treated as equal") + } +} diff --git a/migrations/0051_ai_production_queue.sql b/migrations/0051_ai_production_queue.sql new file mode 100644 index 0000000..a40158a --- /dev/null +++ b/migrations/0051_ai_production_queue.sql @@ -0,0 +1,25 @@ +-- Durable production commands; never store provider credentials in payloads. +CREATE TABLE IF NOT EXISTS landwelle.ai_production_queue ( + id text PRIMARY KEY, + channel text NOT NULL, + kind text NOT NULL CHECK (kind IN ('news','audio','scheduled','wish')), + payload jsonb NOT NULL, + dedupe_key text, + snapshot jsonb NOT NULL, + status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','running','done','error')), + error text NOT NULL DEFAULT '', + task_id bigint, + scheduled_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + started_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now(), + finished_at timestamptz +); +CREATE INDEX IF NOT EXISTS ai_production_queue_pending_idx +ON landwelle.ai_production_queue (created_at,id) WHERE status='queued'; +CREATE INDEX IF NOT EXISTS ai_production_queue_history_idx +ON landwelle.ai_production_queue (created_at DESC); +CREATE UNIQUE INDEX IF NOT EXISTS ai_production_queue_active_dedupe_idx +ON landwelle.ai_production_queue (dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('queued','running'); +CREATE INDEX IF NOT EXISTS ai_production_queue_running_idx +ON landwelle.ai_production_queue (started_at) WHERE status='running'; diff --git a/scripts/test-postgres-integration.sh b/scripts/test-postgres-integration.sh new file mode 100755 index 0000000..206af8d --- /dev/null +++ b/scripts/test-postgres-integration.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Start a disposable local PostgreSQL cluster on a private Unix socket only. +# No production environment file, database or credentials are used. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" +PGBIN="$(pg_config --bindir)" +for cmd in initdb pg_ctl createdb psql; do + test -x "$PGBIN/$cmd" || { echo "PostgreSQL-Testwerkzeug fehlt: $cmd" >&2; exit 1; } +done +TMP="$(mktemp -d /var/tmp/landwelle-postgres-test.XXXXXX)" +AS=() +if [[ $EUID -eq 0 ]]; then + id postgres >/dev/null + chown postgres:postgres "$TMP" + AS=(runuser -u postgres --) +fi +cleanup(){ + "${AS[@]}" "$PGBIN/pg_ctl" -D "$TMP/db" -m fast -w stop >/dev/null 2>&1 || true + rm -rf -- "$TMP" +} +trap cleanup EXIT +"${AS[@]}" mkdir -m 700 "$TMP/socket" +"${AS[@]}" "$PGBIN/initdb" -D "$TMP/db" -U postgres --auth=trust --no-locale -E UTF8 >/dev/null +"${AS[@]}" "$PGBIN/pg_ctl" -D "$TMP/db" -l "$TMP/postgres.log" -o "-h '' -k $TMP/socket -p 5432" -w start >/dev/null +unset PGPASSWORD PGSERVICE PGSERVICEFILE PGOPTIONS PGSSLROOTCERT PGSSLCERT PGSSLKEY PGHOSTADDR +export PGHOST="$TMP/socket" PGPORT=5432 PGUSER=postgres PGDATABASE=landwelle_test PGSSLMODE=disable +"$PGBIN/createdb" -h "$PGHOST" -p "$PGPORT" -U postgres landwelle_test +export DATABASE_URL="postgresql://postgres@/landwelle_test?host=$PGHOST&sslmode=disable" +export LANDWELLE_TEST_DATABASE_URL="$DATABASE_URL" +touch "$TMP/test.env" +# Apply all historical and current migrations without moving repository files. +go run ./cmd/migrate --env-file "$TMP/test.env" --dir migrations --keep-files --lock-file "$TMP/migration.lock" +go test -count=1 -p 1 ./internal/database ./internal/jobqueue +# Optional authenticated HTTP smoke test against the same disposable database. +if [[ "${LANDWELLE_HTTP_SMOKE:-0}" == 1 ]]; then + "$PGBIN/psql" -X -v ON_ERROR_STOP=1 -c 'UPDATE landwelle.feed_sources SET enabled=false' >/dev/null + go build -o "$TMP/portal" ./cmd/portal + "${AS[@]}" env -i PATH=/usr/local/bin:/usr/bin:/bin HOME="$TMP" DATABASE_URL="$DATABASE_URL" python3 - "$TMP" <<'PY' +import os,sys,subprocess,socket,time,urllib.request,urllib.parse,http.cookiejar,secrets,pathlib,json +root=pathlib.Path(sys.argv[1]) +with socket.socket() as sock: + sock.bind(('127.0.0.1',0)) + port=sock.getsockname()[1] +password=secrets.token_urlsafe(24) +env=dict(os.environ,ADDR=f'127.0.0.1:{port}',LANDWELLE_STATE_DIR=str(root/'state'),LANDWELLE_ADMIN_USER='integration-test-admin',LANDWELLE_ADMIN_PASSWORD=password,LANDWELLE_ADMIN_COOKIE_SECURE='false',LANDWELLE_AZURACAST_ENABLED='false',LANDWELLE_OPENAI_ENABLED='false',LANDWELLE_ELEVENLABS_ENABLED='false',LANDWELLE_FTP_ENABLED='false',LANDWELLE_SMTP_ENABLED='false') +with (root/'portal.log').open('w+') as log: + p=subprocess.Popen([str(root/'portal')],cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT) + try: + base=f'http://127.0.0.1:{port}' + for i in range(100): + if p.poll() is not None:raise RuntimeError('Testportal vor dem Start beendet') + try: + with urllib.request.urlopen(base+'/ready',timeout=.5) as r: + if json.load(r)['status']=='ready':break + except Exception:time.sleep(.15) + else:raise RuntimeError('Testportal nicht bereit') + for path in ['/ready','/version','/','/player','/highlights','/assets/landwelle-ki-transparenz-preroll-v2.mp3','/api/info']: + with urllib.request.urlopen(base+path,timeout=30) as r: + assert r.status==200 and r.read() + print('HTTP',r.status,path,flush=True) + client=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + data=urllib.parse.urlencode(dict(username='integration-test-admin',password=password)).encode() + with client.open(base+'/admin/login',data=data,timeout=45) as r: + html=r.read().decode() + assert r.url.endswith('/admin') + for phrase in ['Gitea · Landwelle','KI-Warteschlange','API-Monitoring','Datenbank & Cron','Verbunden','Repository öffnen']: + assert phrase in html,phrase + assert password not in html + print('HTTP 200 authenticated admin dashboard with operational widgets',flush=True) + with client.open(base+'/admin/media',timeout=30) as r: + assert r.status==200 and r.read() + print('HTTP 200 authenticated media gallery',flush=True) + finally: + p.terminate() + try:p.wait(timeout=20) + except subprocess.TimeoutExpired:p.kill();p.wait() + if p.returncode not in (0,-15): + log.seek(0) + print(log.read()[-2000:]) +PY +fi