Files
silo-server/internal/api/handlers/playback_lazy_markers.go
203a18ae83 feat(observability): OpenTelemetry logs+traces with secret redaction and slog standardization (#290)
* feat(observability): OpenTelemetry logs+traces with secret redaction

Part of #265. Adds opt-in OpenTelemetry (logs + traces) alongside the existing
stderr + opslog pipeline, plus secret redaction on all sinks. Default-off: with
no OTEL_* / SILO_OTEL_ENABLED config, behavior is unchanged.

Bootstrap (internal/telemetry):
- Setup() builds one shared resource, a TracerProvider (parent-based trace-id
  ratio sampler), a LoggerProvider, and the W3C TraceContext+Baggage propagator
  from env. It installs NO MeterProvider — metrics stay on Prometheus, and the
  built-in no-op global MeterProvider keeps the trace instrumentation libs from
  double-emitting. Shutdown is deferred with a flush timeout.
- Logs are bridged via otelslog fan-out (slog.MultiHandler), level-gated by the
  shared LevelVar and best-effort so a failing collector can't break the console
  or DB branches. stderr + opslog stay untouched.

Secret redaction (internal/logredact):
- A slog.Handler masks secret-keyed attributes (password, token, api_key,
  authorization, cookie, ...) — including .With-bound attrs, nested groups,
  secret-keyed group subtrees, and values behind a LogValuer — on the console
  and OTLP sinks, with a no-op fast path when a record has no secret keys.
  opslog.shouldRedact delegates to logredact.SecretKey so all sinks share one
  marker list.

Rotation is infra-managed (no custom file sink): container runtime for stderr,
collector/backend for OTLP, opslog partition-pruning for the DB. Documented in
docs/architecture/observability.md.

Verification: go build ./..., go vet, gofmt -l — clean; go test
./internal/telemetry/ ./internal/logredact/ -race pass.

AI-use disclosure: implemented with AI assistance (Claude Code), including
adversarial reviews that hardened the bootstrap and fixed two redaction leak
paths; reviewed by the author.

* refactor(observability): slog context+component sweep, sloglint gate (phase 3)

Part of #265. Builds on the OTel bootstrap + redaction commit.

Standardizes every log call site onto the context-carrying slog variants so
records correlate with the active OpenTelemetry trace, and locks the standard
in with a machine gate so future code (human- or AI-authored) can't drift back.

- Call-site sweep: converted the remaining slog.<Level>(...) calls to the
  slog.<Level>Context(ctx, ...) form wherever a context.Context is in scope
  (background/init calls with no ctx are left as-is), across 183 files. Applied
  via a type-aware AST codemod. Log levels and message strings are preserved
  verbatim; a component attr (canonical per-package name) is added to direct
  package-level slog calls. Bound-logger calls keep their existing .With
  bindings. The main.go and telemetry package conversions rode with their file
  in the previous commit to keep each file within a single commit.
- Enforcement (.golangci.yml): enable sloglint with context=scope, static-msg,
  key-naming-case=snake, no-mixed-args. After the sweep all four report zero
  violations repo-wide (tests included), so make lint / CI now blocks any
  regression to the non-context form. The gate ships with the sweep because it
  cannot be green until the legacy sites are converted.

Metrics remain on Prometheus; no behavior change to /metrics or Grafana.

Verification: go build ./..., go vet ./..., gofmt -l — clean; sloglint (all 4
rules) 0 violations repo-wide; log levels verified unchanged.

AI-use disclosure: implemented with AI assistance (Claude Code), including the
codemod; reviewed by the author.

* fix(observability): honor per-signal OTLP protocol and secret WithGroup names

Two Codex review findings on PR #290:

- telemetry: OTEL_EXPORTER_OTLP_{TRACES,LOGS}_PROTOCOL now override the
  generic OTEL_EXPORTER_OTLP_PROTOCOL per signal, so mixed collector
  setups (e.g. HTTP logs + gRPC traces) build the right exporter.
- logredact: entering a group whose name is secret-bearing (e.g.
  WithGroup("authorization")) now masks every leaf in that subtree,
  matching how slog.Group("authorization", ...) is masked as a whole.

* fix(observability): address review feedback on telemetry bootstrap

- Telemetry setup failure no longer kills boot: Setup returns usable
  no-op providers alongside the error and main logs and continues with
  telemetry disabled, honoring the best-effort contract.
- Honor OTEL_TRACES_SAMPLER (always_on/off, traceidratio, parentbased_*
  variants); unsupported values fall back to parentbased_traceidratio.
- Attach node identity as semconv service.instance.id instead of the
  non-semconv node.name.
- Rename opslog retention-scope log attrs to target_component/target_level
  so they no longer collide with the canonical component routing key, and
  tag those lines with component=opslog.
- Fix stale levelGated comment casing; use WarnContext in the telemetry
  shutdown defer; document the LogValuer double-resolve on the redaction
  slow path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 08:53:52 -04:00

404 lines
12 KiB
Go

package handlers
import (
"context"
"log/slog"
"strings"
"time"
"github.com/Silo-Server/silo-server/internal/markers"
"github.com/Silo-Server/silo-server/internal/models"
"github.com/Silo-Server/silo-server/internal/playback"
"github.com/Silo-Server/silo-server/internal/scanner"
)
const playbackLazyMarkerTimeout = 10 * time.Minute
type PlaybackIntroEligibilityChecker interface {
IntroDetectionEligibleForPlayback(ctx context.Context, fileID int) (bool, error)
IsFileInEnabledLibrary(ctx context.Context, fileID int) (bool, error)
}
type PlaybackMarkerUpdateNotifier interface {
MarkersUpdated(ctx context.Context, file *models.MediaFile)
}
// PlaybackMarkerUpserter narrows scanner.FileRepository down to just the
// marker write path so tests can supply a fake without dragging in the
// full repository.
type PlaybackMarkerUpserter interface {
UpsertMarkers(ctx context.Context, fileID int, update scanner.MarkerUpdate) (bool, error)
}
func (h *PlaybackHandler) maybeQueueLazyPlaybackMarkers(
ctx context.Context,
session *playback.Session,
file *models.MediaFile,
) {
if h == nil || session == nil || file == nil || file.ID <= 0 {
return
}
if file.MediaFolderID <= 0 {
return
}
isEpisode := strings.TrimSpace(file.EpisodeID) != ""
isMovie := !isEpisode && strings.TrimSpace(file.ContentID) != ""
if !isEpisode && !isMovie {
return
}
if h.SettingsRepo == nil || h.IntroRepository == nil {
return
}
lazy, err := h.SettingsRepo.Get(ctx, markers.SettingLazyPlayback)
if err != nil {
slog.WarnContext(ctx, "playback lazy markers: load lazy setting failed", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"error", err)
return
}
if strings.ToLower(strings.TrimSpace(lazy)) != "true" {
return
}
rawMode, err := h.SettingsRepo.Get(ctx, markers.SettingMode)
if err != nil {
slog.WarnContext(ctx, "playback lazy markers: load marker mode failed", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"error", err)
return
}
mode := markers.NormalizeMode(rawMode)
if mode == markers.ModeOff {
slog.DebugContext(ctx, "playback lazy markers: skipped; marker mode is off", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"episode_id", file.EpisodeID)
return
}
hasOnline := h.hasOnlineMarkerProviders()
shouldRunLocal := markers.ShouldRunLocal(mode)
shouldRunOnline := (mode == markers.ModeOnline || mode == markers.ModeBoth) && hasOnline
if shouldRunOnline && hasOnlineSourcedMarkers(file) {
shouldRunOnline = false
}
if shouldRunOnline {
// Online providers work for any enabled library (movies and series alike).
ok, err := h.IntroRepository.IsFileInEnabledLibrary(ctx, file.ID)
if err != nil {
slog.WarnContext(ctx, "playback lazy markers: online eligibility check failed", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"error", err)
shouldRunOnline = false
}
if !ok {
shouldRunOnline = false
}
}
if shouldRunLocal {
// Local chromaprint is only meaningful for series libraries that
// opted in to expensive fingerprinting and requires an analyzer.
ok, err := h.IntroRepository.IntroDetectionEligibleForPlayback(ctx, file.ID)
if err != nil {
slog.WarnContext(ctx, "playback lazy markers: local eligibility check failed", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode,
"error", err)
shouldRunLocal = false
}
if !ok || h.IntroAnalyzer == nil || !isEpisode {
shouldRunLocal = false
}
}
if !shouldRunOnline && !shouldRunLocal {
slog.DebugContext(ctx, "playback lazy markers: skipped; no eligible detection path", "component", "api",
"session_id", session.ID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode)
return
}
if _, loaded := h.MarkerLazyInFlight.LoadOrStore(file.ID, struct{}{}); loaded {
return
}
sessionID := session.ID
fileSnapshot := *file
slog.InfoContext(ctx, "playback lazy markers: queued", "component", "api",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode,
"run_online", shouldRunOnline,
"run_local", shouldRunLocal)
go h.runLazyPlaybackMarkers(sessionID, &fileSnapshot, mode, shouldRunOnline, shouldRunLocal)
}
func (h *PlaybackHandler) runLazyPlaybackMarkers(
sessionID string,
file *models.MediaFile,
mode markers.Mode,
runOnline bool,
runLocal bool,
) {
if file == nil {
return
}
defer h.MarkerLazyInFlight.Delete(file.ID)
base := h.MarkerLazyContext
if base == nil {
base = context.Background()
}
ctx, cancel := context.WithTimeout(base, playbackLazyMarkerTimeout)
defer cancel()
slog.Info("playback lazy markers: started",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode)
if runOnline {
wrote, err := h.fetchOnlineMarkersForPlayback(ctx, file)
if err != nil {
slog.Warn("playback lazy markers: online fetch failed",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode,
"error", err)
}
if wrote {
if refreshed := h.reloadPlaybackMarkerFile(ctx, file.ID); hasAnyMarker(refreshed) {
h.notifyPlaybackMarkers(ctx, sessionID, refreshed, mode)
if !runLocal || hasLocalDetectionMarkers(refreshed) {
return
}
}
}
}
// A concurrent session may have populated markers since we queued; check
// before falling through to the (expensive) local analyzer.
if refreshed := h.reloadPlaybackMarkerFile(ctx, file.ID); hasAnyMarker(refreshed) {
h.notifyPlaybackMarkers(ctx, sessionID, refreshed, mode)
if !runLocal || hasLocalDetectionMarkers(refreshed) {
return
}
}
if runLocal {
slog.Info("playback lazy markers: local analyzer started",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode)
summary, err := h.IntroAnalyzer.AnalyzeEpisode(ctx, file.EpisodeID)
if err != nil {
slog.Warn("playback lazy markers: local analyzer failed",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode,
"error", err)
return
}
slog.Info("playback lazy markers: local analyzer finished",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode,
"files_considered", summary.FilesConsidered,
"season_groups_considered", summary.SeasonGroupsConsidered,
"chapter_markers_written", summary.ChapterMarkersWritten,
"chromaprint_markers_written", summary.ChromaprintMarkersWritten,
"fingerprint_cache_hits", summary.FingerprintCacheHits,
"fingerprints_computed", summary.FingerprintsComputed,
"errors", len(summary.Errors))
if refreshed := h.reloadPlaybackMarkerFile(ctx, file.ID); hasAnyMarker(refreshed) {
h.notifyPlaybackMarkers(ctx, sessionID, refreshed, mode)
}
}
}
func (h *PlaybackHandler) hasOnlineMarkerProviders() bool {
return h != nil && h.MarkerRegistry != nil && len(h.MarkerRegistry.Providers()) > 0
}
// fetchOnlineMarkersForPlayback resolves external IDs for the given file,
// asks the marker registry for the first hit, and persists the result via
// the scanner upserter. Returns true when at least one segment was
// actually written to storage.
func (h *PlaybackHandler) fetchOnlineMarkersForPlayback(ctx context.Context, file *models.MediaFile) (bool, error) {
if h == nil || file == nil || !h.hasOnlineMarkerProviders() {
return false, nil
}
if h.MarkerResolver == nil || h.MarkerUpserter == nil {
slog.DebugContext(ctx, "playback lazy markers: online fetch skipped; resolver or upserter missing", "component", "api",
"file_id", file.ID)
return false, nil
}
ids, err := h.MarkerResolver.ResolveForFile(ctx, file)
if err != nil {
return false, err
}
if !ids.HasAnyID() {
slog.DebugContext(ctx, "playback lazy markers: online fetch skipped; no external IDs available", "component", "api",
"file_id", file.ID,
"episode_id", file.EpisodeID,
"content_id", file.ContentID)
return false, nil
}
req := markers.Request{
Kind: ids.Kind,
ExternalIDs: ids.AsRequestMap(),
SeasonNumber: ids.SeasonNumber,
EpisodeNumber: ids.EpisodeNumber,
Duration: time.Duration(file.Duration) * time.Second,
}
result, ok, err := h.MarkerRegistry.FetchMerged(ctx, req)
if err != nil {
return false, err
}
if !ok || len(result.Markers) == 0 {
return false, nil
}
payload := markers.BuildUpdatePayload(result)
if !payload.HasAnySegment() {
return false, nil
}
wrote, err := h.MarkerUpserter.UpsertMarkers(ctx, file.ID, markerUpdateFromPayload(payload))
if err != nil {
return false, err
}
return wrote, nil
}
func (h *PlaybackHandler) reloadPlaybackMarkerFile(ctx context.Context, fileID int) *models.MediaFile {
if h == nil || h.fileResolver == nil || fileID <= 0 {
return nil
}
refreshed, err := h.fileResolver.GetByID(ctx, fileID)
if err != nil {
slog.WarnContext(ctx, "playback lazy markers: reload file failed", "component", "api", "file_id", fileID, "error", err)
return nil
}
return refreshed
}
func (h *PlaybackHandler) notifyPlaybackMarkers(
ctx context.Context,
sessionID string,
file *models.MediaFile,
mode markers.Mode,
) {
if h == nil || h.MarkerUpdateNotifier == nil || file == nil {
return
}
h.MarkerUpdateNotifier.MarkersUpdated(ctx, file)
slog.InfoContext(ctx, "playback lazy markers: emitted marker update", "component", "api",
"session_id", sessionID,
"file_id", file.ID,
"episode_id", file.EpisodeID,
"mode", mode)
}
// hasOnlineSourcedMarkers reports whether the file already has at least one
// marker written by a non-local source. We short-circuit lazy online fetch
// in that case to avoid refetching every playback start — TheIntroDB often
// returns only intro+credits and never recap/preview for a given episode, so
// requiring all four kinds before skipping would loop forever on partial data.
// Markers from the scanner/s3 path remain refetchable since online sources
// outrank them.
func hasOnlineSourcedMarkers(file *models.MediaFile) bool {
if file == nil {
return false
}
isOnlineSource := func(source *string) bool {
if source == nil {
return false
}
switch *source {
case models.MarkerSourceOnline, models.MarkerSourcePlugin, models.MarkerSourceManual:
return true
}
return false
}
return isOnlineSource(file.IntroMarkersSource) ||
isOnlineSource(file.CreditsMarkersSource) ||
isOnlineSource(file.RecapMarkersSource) ||
isOnlineSource(file.PreviewMarkersSource)
}
// hasAnyMarker reports whether the file has at least one populated marker
// segment. Used to decide whether to emit a markers_updated event.
func hasAnyMarker(file *models.MediaFile) bool {
if file == nil {
return false
}
return (file.IntroStart != nil && file.IntroEnd != nil) ||
(file.CreditsStart != nil && file.CreditsEnd != nil) ||
(file.RecapStart != nil && file.RecapEnd != nil) ||
(file.PreviewStart != nil && file.PreviewEnd != nil)
}
func hasLocalDetectionMarkers(file *models.MediaFile) bool {
if file == nil {
return false
}
return (file.IntroStart != nil && file.IntroEnd != nil) ||
(file.CreditsStart != nil && file.CreditsEnd != nil)
}
// markerUpdateFromPayload adapts the generic markers.MarkerUpdatePayload to
// the scanner.MarkerUpdate shape consumed by FileRepository.UpsertMarkers.
// Kept narrow on purpose — the packages it bridges should not need to import
// each other.
func markerUpdateFromPayload(p markers.MarkerUpdatePayload) scanner.MarkerUpdate {
return scanner.MarkerUpdate{
IntroStart: p.Intro.Start,
IntroEnd: p.Intro.End,
CreditsStart: p.Credits.Start,
CreditsEnd: p.Credits.End,
RecapStart: p.Recap.Start,
RecapEnd: p.Recap.End,
PreviewStart: p.Preview.Start,
PreviewEnd: p.Preview.End,
MarkersSource: p.SummarySource(),
MarkersConfidence: p.SummaryConfidence(),
IntroProvenance: segmentProvenance(p.Intro),
CreditsProvenance: segmentProvenance(p.Credits),
RecapProvenance: segmentProvenance(p.Recap),
PreviewProvenance: segmentProvenance(p.Preview),
}
}
func segmentProvenance(s markers.SegmentPayload) *scanner.SegmentProvenance {
if !s.Present() {
return nil
}
return &scanner.SegmentProvenance{
Source: s.Source,
Provider: s.Provider,
Confidence: s.Confidence,
Algorithm: s.Algorithm,
}
}