Files
silo-server/internal/api/handlers/subtitle_ai.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

266 lines
9.8 KiB
Go

package handlers
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
apimw "github.com/Silo-Server/silo-server/internal/api/middleware"
"github.com/Silo-Server/silo-server/internal/catalog"
"github.com/Silo-Server/silo-server/internal/subtitles/ai"
"github.com/Silo-Server/silo-server/internal/userstore"
)
// SubtitleAIHandler exposes on-demand AI subtitle translation backed by the
// configured OpenAI-compatible engine. Generated tracks are stored as ordinary
// downloaded subtitles, so they reach every client through the existing
// subtitle pipeline.
type SubtitleAIHandler struct {
service *ai.Service
FileAuthorizer *MediaFileAuthorizer
// StoreProvider resolves household profiles for the transcription quota
// exemption check; when nil the whole admin account is exempt.
StoreProvider userstore.UserStoreProvider
}
// NewSubtitleAIHandler creates a handler backed by the given service.
func NewSubtitleAIHandler(service *ai.Service) *SubtitleAIHandler {
return &SubtitleAIHandler{service: service}
}
// authorizeMediaFileAccess verifies the caller may access the given media file.
// Shared by the subtitle handlers so authorization stays in one place.
func authorizeMediaFileAccess(w http.ResponseWriter, r *http.Request, authorizer *MediaFileAuthorizer, fileID int) bool {
if authorizer == nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Media file authorization is not configured")
return false
}
if _, err := authorizer.Authorize(r, fileID); err != nil {
switch {
case errors.Is(err, catalog.ErrItemNotFound), errors.Is(err, catalog.ErrEpisodeNotFound):
writeError(w, http.StatusNotFound, "not_found", "Media file not found")
default:
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to authorize media file")
}
return false
}
return true
}
type translateSubtitleRequest struct {
MediaFileID int `json:"media_file_id"`
// Kind selects the job: "translate" (default), "transcribe", or
// "transcribe_translate". For ASR kinds, source_index is the audio track
// index (-1 = default track) and target_language is optional for plain
// transcribe (acts as a language hint).
Kind string `json:"kind"`
SourceIndex int `json:"source_index"`
SourceLanguage string `json:"source_language"`
TargetLanguage string `json:"target_language"`
SessionID string `json:"session_id"`
StartPosition float64 `json:"start_position"`
}
// HandleStatus reports whether AI subtitle translation / ASR generation are
// available, so the player can show or hide the entry points.
// GET /api/v1/subtitles/ai/status
func (h *SubtitleAIHandler) HandleStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"enabled": h.service.Enabled(),
"transcribe_enabled": h.service.TranscribeEnabled(),
})
}
// WriteSubtitleAIDisabledStatus answers the AI status capability probe with a
// 200 {"enabled": false} when no AI handler is wired, so the client gets a clean
// negative instead of a 404 (the 2-segment /ai/status path is not shadowed by the
// 1-segment /{media_file_id} route — they never compete in chi's router).
func WriteSubtitleAIDisabledStatus(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "transcribe_enabled": false})
}
// HandleTranslate enqueues a translation job. POST /api/v1/subtitles/ai/translate
func (h *SubtitleAIHandler) HandleTranslate(w http.ResponseWriter, r *http.Request) {
var req translateSubtitleRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "Invalid request body")
return
}
if req.MediaFileID <= 0 {
writeError(w, http.StatusBadRequest, "bad_request", "media_file_id is required")
return
}
kind := ai.JobKind(req.Kind)
if kind == "" {
kind = ai.JobKindTranslate
}
// A plain transcribe produces a track in the spoken language, so the
// target is optional; every other kind needs one.
if req.TargetLanguage == "" && kind != ai.JobKindTranscribe {
writeError(w, http.StatusBadRequest, "bad_request", "target_language is required")
return
}
if !authorizeMediaFileAccess(w, r, h.FileAuthorizer, req.MediaFileID) {
return
}
var requestedBy *int
if userID := apimw.GetUserID(r.Context()); userID != 0 {
requestedBy = &userID
}
job, err := h.service.Enqueue(r.Context(), ai.JobRequest{
MediaFileID: req.MediaFileID,
Kind: kind,
SourceIndex: req.SourceIndex,
SourceLanguage: req.SourceLanguage,
TargetLanguage: req.TargetLanguage,
RequestedBy: requestedBy,
QuotaExempt: h.quotaExempt(r),
SessionID: req.SessionID,
StartPosition: req.StartPosition,
})
if err != nil {
switch {
case errors.Is(err, ai.ErrEngineNotConfigured):
writeError(w, http.StatusServiceUnavailable, "not_configured",
"AI subtitle translation is not configured on this server")
case errors.Is(err, ai.ErrQuotaExceeded):
writeError(w, http.StatusTooManyRequests, "quota_exceeded", quotaExceededMessage(err))
case errors.Is(err, ai.ErrInvalidRequest):
writeError(w, http.StatusBadRequest, "bad_request", err.Error())
default:
slog.ErrorContext(r.Context(), "failed to enqueue subtitle translation", "component", "api",
"media_file_id", req.MediaFileID, "error", err)
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to start translation")
}
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job})
}
// quotaExempt reports whether the caller is exempt from the transcription
// quota: an admin account acting as itself (no profile context) or through
// its primary (household parent) profile. Other profiles on an admin account
// — e.g. a kid's profile — stay subject to the quota even though the account
// holds the admin role. X-Profile-Id is client-asserted, so this is a
// budgeting gate, not a security boundary; the quota itself is account-scoped.
func (h *SubtitleAIHandler) quotaExempt(r *http.Request) bool {
ctx := r.Context()
if !apimw.IsAdmin(ctx) {
return false
}
profileID := apimw.GetProfileID(ctx)
if profileID == "" {
profileID = r.Header.Get("X-Profile-Id")
}
if profileID == "" || h.StoreProvider == nil {
return true
}
store, err := h.StoreProvider.ForUser(ctx, apimw.GetUserID(ctx))
if err != nil {
return false // fail closed: the quota still applies
}
profile, err := store.GetProfile(ctx, profileID)
if err != nil || profile == nil {
return false
}
return profile.IsPrimary
}
// quotaExceededMessage turns a quota error into a user-facing message with the
// limit and window when available.
func quotaExceededMessage(err error) string {
var qe *ai.QuotaExceededError
if errors.As(err, &qe) {
return fmt.Sprintf(
"You've reached your transcription limit (%d per %s). Try again later or ask an admin to raise it.",
qe.Limit, qe.Period)
}
return "You've reached your transcription limit. Try again later or ask an admin to raise it."
}
// HandleQuota reports the calling user's transcription quota usage, so the
// player can show how many jobs they have left before they start one.
// GET /api/v1/subtitles/ai/quota
func (h *SubtitleAIHandler) HandleQuota(w http.ResponseWriter, r *http.Request) {
quota, err := h.service.TranscribeQuota(r.Context(), apimw.GetUserID(r.Context()), h.quotaExempt(r))
if err != nil {
slog.ErrorContext(r.Context(), "failed to load transcription quota", "component", "api", "error", err)
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load transcription quota")
return
}
writeJSON(w, http.StatusOK, quota)
}
// HandleGetJob returns a job's current state. GET /api/v1/subtitles/ai/jobs/{job_id}
func (h *SubtitleAIHandler) HandleGetJob(w http.ResponseWriter, r *http.Request) {
job, ok := h.loadAuthorizedJob(w, r)
if !ok {
return
}
writeJSON(w, http.StatusOK, map[string]any{"job": job})
}
// HandleCancelJob cancels a job. POST /api/v1/subtitles/ai/jobs/{job_id}/cancel
func (h *SubtitleAIHandler) HandleCancelJob(w http.ResponseWriter, r *http.Request) {
job, ok := h.loadAuthorizedJob(w, r)
if !ok {
return
}
if err := h.service.Cancel(r.Context(), job.ID); err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to cancel job")
return
}
w.WriteHeader(http.StatusNoContent)
}
// HandleListJobs lists recent jobs for a media file.
// GET /api/v1/subtitles/ai/jobs?media_file_id=N
func (h *SubtitleAIHandler) HandleListJobs(w http.ResponseWriter, r *http.Request) {
mediaFileID, err := strconv.Atoi(r.URL.Query().Get("media_file_id"))
if err != nil || mediaFileID <= 0 {
writeError(w, http.StatusBadRequest, "invalid_id", "Invalid or missing media_file_id")
return
}
if !authorizeMediaFileAccess(w, r, h.FileAuthorizer, mediaFileID) {
return
}
jobs, err := h.service.ListJobs(r.Context(), mediaFileID)
if err != nil {
writeError(w, http.StatusInternalServerError, "list_error", "Failed to list jobs")
return
}
writeJSON(w, http.StatusOK, map[string]any{"jobs": jobs})
}
// loadAuthorizedJob parses the job_id param, loads the job, and authorizes
// access against its media file. It writes the error response on failure.
func (h *SubtitleAIHandler) loadAuthorizedJob(w http.ResponseWriter, r *http.Request) (*ai.Job, bool) {
id, err := strconv.ParseInt(chi.URLParam(r, "job_id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_id", "Invalid job ID")
return nil, false
}
job, err := h.service.GetJob(r.Context(), id)
if err != nil {
if errors.Is(err, ai.ErrJobNotFound) {
writeError(w, http.StatusNotFound, "not_found", "Job not found")
return nil, false
}
writeError(w, http.StatusInternalServerError, "internal_error", "Failed to load job")
return nil, false
}
if !authorizeMediaFileAccess(w, r, h.FileAuthorizer, job.MediaFileID) {
return nil, false
}
return job, true
}