package api import ( "encoding/json" "fmt" "net/http" "os" "path/filepath" "strconv" "strings" "time" "streamd/apps/streamd/internal/auth" "streamd/apps/streamd/internal/db" "streamd/apps/streamd/internal/logfile" ) // logSources maps a caller-supplied source name to the log file suffix the // supervisor writes. It is a fixed allowlist, and the file name is built from // the stream's own name, so no part of the path comes from request input. var logSources = map[string]string{ "nre": "-nre.log", "ffmpeg.out": "-ffmpeg.out.log", "ffmpeg.err": "-ffmpeg.err.log", } // postEvent records an agent-authored event. This is how a failing phone // capture reaches the dashboard instead of only the agent's console. func (h *Handler) postEvent(w http.ResponseWriter, r *http.Request, id int64) { p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } st, err := h.Store.GetStream(id) if err != nil { writeErr(w, http.StatusNotFound, "not found") return } var in struct { Kind string `json:"kind"` Severity string `json:"severity"` Message string `json:"message"` Detail map[string]any `json:"detail"` } if err := readJSON(r, &in); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } kind := strings.TrimSpace(in.Kind) if kind == "" { writeErr(w, http.StatusBadRequest, "kind required") return } // Agents may only author their own capture events; everything else on the // timeline is written by streamd itself and must stay trustworthy. if !agentEventKinds[kind] { writeErr(w, http.StatusBadRequest, "kind "+kind+" is not one an agent may report (allowed: capture_started, capture_ok, capture_failed)") return } sev := strings.TrimSpace(in.Severity) if sev == "" { sev = db.SevInfo if kind == db.EventCaptureFailed { sev = db.SevError } } var detail json.RawMessage if len(in.Detail) > 0 { if b, err := json.Marshal(in.Detail); err == nil && len(b) < 8192 { detail = b } } h.Store.AddEvent(db.StreamEvent{ StreamID: id, Kind: kind, Severity: sev, Actor: p.Actor(), Message: in.Message, Detail: detail, }) h.logger().Info("agent event", "stream", st.Name, "kind", kind, "actor", p.Actor(), "msg", in.Message) if h.Notifier != nil { h.Notifier.NotifyStreamChanged(st.Name, kind) } writeJSON(w, http.StatusCreated, map[string]any{"ok": true}) } var agentEventKinds = map[string]bool{ db.EventCaptureStarted: true, db.EventCaptureOK: true, db.EventCaptureFailed: true, } func (h *Handler) listEvents(w http.ResponseWriter, r *http.Request, id int64) { if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { return } // Flush first so a caller sees the effect of what they just did. _ = h.Store.FlushHistory() q := r.URL.Query() limit, _ := strconv.Atoi(q.Get("limit")) list, err := h.Store.ListEvents(id, limit, q.Get("kind"), q.Get("since")) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"events": list}) } func (h *Handler) listMetrics(w http.ResponseWriter, r *http.Request, id int64) { if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { return } _ = h.Store.FlushHistory() window := parseWindow(r.URL.Query().Get("window")) points, err := h.Store.ListMetrics(id, window) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } uptime, _ := h.Store.UptimeRatio(id, window) out := map[string]any{"metrics": points, "window_s": int(window.Seconds())} if uptime >= 0 { out["uptime_ratio"] = uptime } writeJSON(w, http.StatusOK, out) } func parseWindow(s string) time.Duration { switch strings.ToLower(strings.TrimSpace(s)) { case "", "1h": return time.Hour case "15m": return 15 * time.Minute case "6h": return 6 * time.Hour case "24h", "1d": return 24 * time.Hour case "7d": return 7 * 24 * time.Hour } if d, err := time.ParseDuration(s); err == nil && d > 0 && d <= 7*24*time.Hour { return d } return time.Hour } // logPath resolves a stream + source + optional variant to a log file path. // Returns "" when the source is not on the allowlist. func (h *Handler) logPath(st db.Stream, source, variant string) string { suffix, ok := logSources[strings.ToLower(strings.TrimSpace(source))] if !ok || strings.TrimSpace(h.LogRoot) == "" { return "" } base := st.Name // A variant's packager writes to "--ffmpeg.*.log". The // variant id is validated against the stream's own ladder rather than // trusted, so it cannot contribute path characters. if v := strings.TrimSpace(variant); v != "" && v != db.SourceVariantID { known := false for _, spec := range db.ParseVariantsJSON(st.VariantsJSON) { if spec.ID == v { known = true break } } if !known { return "" } base = st.Name + "-" + v } return filepath.Join(h.LogRoot, base+suffix) } func (h *Handler) streamLogs(w http.ResponseWriter, r *http.Request, id int64) { if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok { return } st, err := h.Store.GetStream(id) if err != nil { writeErr(w, http.StatusNotFound, "not found") return } q := r.URL.Query() source := q.Get("source") if source == "" { source = "nre" } path := h.logPath(st, source, q.Get("variant")) if path == "" { writeErr(w, http.StatusBadRequest, "unknown log source — use one of nre, ffmpeg.out, ffmpeg.err") return } tail, _ := strconv.Atoi(q.Get("tail")) if tail <= 0 { tail = 500 } if tail > 5000 { tail = 5000 } body, err := logfile.Tail(path, tail) if err != nil { if os.IsNotExist(err) { writeJSON(w, http.StatusOK, map[string]any{ "source": source, "lines": "", "exists": false, "note": "no log yet — this stream has not run since streamd started", }) return } writeErr(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{ "source": source, "exists": true, "lines": string(body), }) } // streamLogsSSE follows a log file and pushes new bytes as they appear, so the // dashboard can show a live tail. func (h *Handler) streamLogsSSE(w http.ResponseWriter, r *http.Request, id int64) { if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok { return } st, err := h.Store.GetStream(id) if err != nil { writeErr(w, http.StatusNotFound, "not found") return } q := r.URL.Query() source := q.Get("source") if source == "" { source = "nre" } path := h.logPath(st, source, q.Get("variant")) if path == "" { writeErr(w, http.StatusBadRequest, "unknown log source") return } flusher, ok := w.(http.Flusher) if !ok { writeErr(w, http.StatusInternalServerError, "streaming unsupported") return } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") // Defeat proxy buffering, which would otherwise hold the whole stream. w.Header().Set("X-Accel-Buffering", "no") w.WriteHeader(http.StatusOK) send := func(event, data string) bool { for _, line := range strings.Split(strings.TrimRight(data, "\n"), "\n") { if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, line); err != nil { return false } } flusher.Flush() return true } // Start from the tail so the viewer has context, then follow. if initial, err := logfile.Tail(path, 200); err == nil && len(initial) > 0 { if !send("log", string(initial)) { return } } var offset int64 if fi, err := os.Stat(path); err == nil { offset = fi.Size() } ticker := time.NewTicker(time.Second) defer ticker.Stop() keepalive := time.NewTicker(20 * time.Second) defer keepalive.Stop() ctx := r.Context() for { select { case <-ctx.Done(): return case <-keepalive.C: if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil { return } flusher.Flush() case <-ticker.C: fi, err := os.Stat(path) if err != nil { continue } size := fi.Size() if size < offset { // The file rotated under us; start again from its beginning. offset = 0 if !send("note", "-- log rotated --") { return } } if size == offset { continue } f, err := os.Open(path) if err != nil { continue } buf := make([]byte, size-offset) n, err := f.ReadAt(buf, offset) _ = f.Close() if n > 0 { if !send("log", string(buf[:n])) { return } offset += int64(n) } if err != nil && n == 0 { continue } } } } // overview is the dashboard's single round trip: totals, viewer counts and // the recent activity feed. func (h *Handler) overview(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { writeErr(w, http.StatusMethodNotAllowed, "method not allowed") return } if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { return } list, err := h.Store.ListStreams() if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } var running, down, starting, stopped, onDemandIdle, viewers, needCapture int for i := range list { st := &list[i] if h.Viewers != nil { st.Viewers = h.Viewers.ViewersFor(st.Name) viewers += st.Viewers } if st.NeedsCapture { needCapture++ } switch st.Health { case "ok": running++ case "down": down++ case "starting": starting++ default: stopped++ if st.OnDemand && st.Enabled { onDemandIdle++ } } } _ = h.Store.FlushHistory() recent, _ := h.Store.RecentEvents(25) sessions, _ := h.Store.ListRecentSessions(50) if sessions == nil { sessions = []db.StreamSession{} } out := map[string]any{ "totals": map[string]any{ "streams": len(list), "running": running, "starting": starting, "down": down, "stopped": stopped, "ondemand_idle": onDemandIdle, "viewers": viewers, "needs_capture": needCapture, }, "recent_events": recent, "recent_sessions": sessions, } if h.Scheduler != nil { out["upcoming"] = h.Scheduler.Upcoming(10) } writeJSON(w, http.StatusOK, out) }