* 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>
157 lines
5.6 KiB
Go
157 lines
5.6 KiB
Go
package notifications
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"time"
|
|
)
|
|
|
|
const availabilityDetectTimeout = 2 * time.Minute
|
|
|
|
// AvailabilityDetector turns completed ingest runs into episode_availability
|
|
// facts and release events. It runs after matching/reconcile is complete so
|
|
// a release is tied to an actual resolved episode, and it never blocks or
|
|
// fails the ingest itself.
|
|
type AvailabilityDetector struct {
|
|
releases *ReleaseRepository
|
|
settings *Settings
|
|
logger *slog.Logger
|
|
// nudge wakes the fanout worker after new release events land; may be nil.
|
|
nudge func()
|
|
}
|
|
|
|
// NewAvailabilityDetector creates an AvailabilityDetector.
|
|
func NewAvailabilityDetector(releases *ReleaseRepository, settings *Settings) *AvailabilityDetector {
|
|
return &AvailabilityDetector{
|
|
releases: releases,
|
|
settings: settings,
|
|
logger: slog.Default().With("component", "notifications.availability"),
|
|
}
|
|
}
|
|
|
|
// SetFanoutNudge wires the fanout worker wake signal.
|
|
func (d *AvailabilityDetector) SetFanoutNudge(nudge func()) {
|
|
if d != nil {
|
|
d.nudge = nudge
|
|
}
|
|
}
|
|
|
|
// AvailabilityKinds selects which content kinds an ingest scope covers.
|
|
// Each kind keeps its own seed marker and silent-seeding semantics.
|
|
type AvailabilityKinds struct {
|
|
Episodes bool
|
|
Movies bool
|
|
Audiobooks bool
|
|
Ebooks bool
|
|
}
|
|
|
|
// Any reports whether at least one kind is selected.
|
|
func (k AvailabilityKinds) Any() bool {
|
|
return k.Episodes || k.Movies || k.Audiobooks || k.Ebooks
|
|
}
|
|
|
|
// availabilityKindOps abstracts the per-kind recording calls so episode and
|
|
// movie passes share one detection flow; seed state is kind-keyed in the
|
|
// repository itself.
|
|
type availabilityKindOps struct {
|
|
kind string
|
|
recordForLibrary func(ctx context.Context, libraryID int, emitEvents bool) (int, int, error)
|
|
recordForPaths func(ctx context.Context, libraryID int, scopePaths []string, emitEvents bool) (int, int, error)
|
|
}
|
|
|
|
// HandleIngestCompleted records newly available content for a completed
|
|
// ingest scope. fullLibrary distinguishes whole-library scans (set-based
|
|
// detection, and the scan that seeds a new library) from subtree/file scans
|
|
// (path-bounded detection).
|
|
//
|
|
// Seeding semantics: a library without a seed marker records availability
|
|
// silently — "newly available" means newly released to this server, not newly
|
|
// seen by the notifications feature. The marker is written when a full scan
|
|
// completes successfully, so the next scan onward emits release events.
|
|
func (d *AvailabilityDetector) HandleIngestCompleted(ctx context.Context, libraryID int, fullLibrary bool, scopePaths []string, kinds AvailabilityKinds) {
|
|
if d == nil || d.releases == nil {
|
|
return
|
|
}
|
|
// The scan context is done once the scan finishes; detection runs on its
|
|
// own deadline so cancellation of the parent does not drop availability.
|
|
detectCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), availabilityDetectTimeout)
|
|
defer cancel()
|
|
|
|
if kinds.Episodes {
|
|
d.runKind(detectCtx, libraryID, fullLibrary, scopePaths, availabilityKindOps{
|
|
kind: EventKindEpisode,
|
|
recordForLibrary: d.releases.RecordAvailabilityForLibrary,
|
|
recordForPaths: d.releases.RecordAvailabilityForPaths,
|
|
})
|
|
}
|
|
for _, k := range flatItemKinds {
|
|
if k.Selected(kinds) {
|
|
d.runKind(detectCtx, libraryID, fullLibrary, scopePaths, d.flatKindOps(k))
|
|
}
|
|
}
|
|
}
|
|
|
|
// flatKindOps binds one flat item kind's registry entry to the shared
|
|
// detection flow.
|
|
func (d *AvailabilityDetector) flatKindOps(k flatItemKind) availabilityKindOps {
|
|
return availabilityKindOps{
|
|
kind: k.Kind,
|
|
recordForLibrary: func(ctx context.Context, libraryID int, emitEvents bool) (int, int, error) {
|
|
return d.releases.RecordItemAvailabilityForLibrary(ctx, k, libraryID, emitEvents)
|
|
},
|
|
recordForPaths: func(ctx context.Context, libraryID int, scopePaths []string, emitEvents bool) (int, int, error) {
|
|
return d.releases.RecordItemAvailabilityForPaths(ctx, k, libraryID, scopePaths, emitEvents)
|
|
},
|
|
}
|
|
}
|
|
|
|
func (d *AvailabilityDetector) runKind(ctx context.Context, libraryID int, fullLibrary bool, scopePaths []string, ops availabilityKindOps) {
|
|
seeded, err := d.releases.IsContentSeeded(ctx, libraryID, ops.kind)
|
|
if err != nil {
|
|
d.logger.WarnContext(ctx, "seed state lookup failed",
|
|
"library_id", libraryID, "kind", ops.kind, "error", err)
|
|
return
|
|
}
|
|
emitEvents := seeded && d.settings.ReleaseEventsEnabled(ctx)
|
|
|
|
var inserted, events int
|
|
if fullLibrary {
|
|
inserted, events, err = ops.recordForLibrary(ctx, libraryID, emitEvents)
|
|
} else if seeded {
|
|
inserted, events, err = ops.recordForPaths(ctx, libraryID, scopePaths, emitEvents)
|
|
} else {
|
|
// Subtree/file ingest on an unseeded library: record silently but do
|
|
// not seed-mark — only a successful full scan proves the back catalog
|
|
// has been captured.
|
|
inserted, events, err = ops.recordForPaths(ctx, libraryID, scopePaths, false)
|
|
}
|
|
if err != nil {
|
|
d.logger.WarnContext(ctx, "availability detection failed",
|
|
"library_id", libraryID, "kind", ops.kind, "error", err)
|
|
return
|
|
}
|
|
|
|
if fullLibrary && !seeded {
|
|
if err := d.releases.MarkContentSeeded(ctx, libraryID, ops.kind); err != nil {
|
|
d.logger.WarnContext(ctx, "seed marker write failed",
|
|
"library_id", libraryID, "kind", ops.kind, "error", err)
|
|
} else {
|
|
d.logger.InfoContext(ctx, "library availability seeded",
|
|
"library_id", libraryID, "kind", ops.kind, "availability_rows", inserted)
|
|
}
|
|
}
|
|
|
|
if inserted > 0 || events > 0 {
|
|
d.logger.InfoContext(ctx, "availability recorded",
|
|
"library_id", libraryID,
|
|
"kind", ops.kind,
|
|
"full_library", fullLibrary,
|
|
"availability_rows", inserted,
|
|
"release_events", events,
|
|
)
|
|
}
|
|
if events > 0 && d.nudge != nil {
|
|
d.nudge()
|
|
}
|
|
}
|