Files
silo-server/internal/plugins/event_dispatcher.go
91e1164090 feat(metadata): local NFO metadata and sidecar artwork (builtin chain provider) (#390)
* feat(metadata): register builtin NFO provider and broaden parsing

Phases A and B of the #216 local-NFO work, implemented test-first.

Registration & hint-first identity (Phase A):
- Migration seeds a reserved kind='builtin' silo.builtin installation
  and an 'nfo' metadata capability (default_enabled=false, priority 1
  for movie/series) with a partial unique index and documented Down.
- In-process builtin provider registry (internal/metadata/builtin.go);
  buildProviders returns the registered provider for builtin rows.
- Guard rails keep the reserved row out of every plugin surface (user
  plugin-settings, installations list, image resolvers, preload,
  auto-update, store Delete, mutation handlers -> 409); silo.builtin is
  a reserved manifest id.
- Startup sync materializes legacy content_level='' chains per level,
  then appends builtin capabilities disabled via
  AppendProviderToAllChains (idempotent); resolveEnabledProvidersBy
  priority now respects default_enabled=false.
- NFO uniqueids seed the trusted-hint machinery via IdentityHintProvider
  with per-mode conflict policy (stored IDs win on scheduled refresh,
  NFO wins on manual refresh, Identify skips NFO); ID-less candidates
  are excluded from provider-priority tie-breaks and nfo never counts
  as corroboration.
- Web chain-editor empty-state gate is now server-derived so builtin
  providers are reachable on plugin-less servers.

Parser breadth & sidecar hardening (Phase B):
- Parser covers the practical Kodi/Jellyfin field set for <movie> and
  <tvshow>: original title, tagline, runtime, dates, content rating,
  genres/studios/countries/tags, multi-source ratings with scale
  normalization, cast with roles/order, director/credits. Empty
  collections stay nil so merge early-returns apply.
- findNFO parses candidates and falls through on read/parse failure or
  root-type mismatch, so a stray movie.nfo cannot shadow tvshow.nfo;
  GetMetadata gains the same ContentType guard Search has.
- New FieldReleaseDates lock gates Year/ReleaseDate/First+LastAirDate
  in merge (Go) and the edit-metadata dialog (web), closing the gap
  where a manual refresh re-applied NFO dates over admin corrections.
- Merge-contract tests pin NFO fill semantics, genres whole-list
  first-provider-wins, and NFO edits propagating on manual refresh only.
- Docs: new admin wiki page (supported fields, merge semantics,
  naming-supplies-structure contract), index bullet, sidecar wording
  revision, v1-scope feature-detection note.

Zero behavior change while the provider is disabled (default); pinned
by CI-mode and DB-gated test suites.

Part of #216

AI-use disclosure: implemented with Claude Code (Fable 5) via
spec-driven TDD and agent-assisted implementation.

* feat(metadata): ingest local sidecar artwork and read series-depth NFO

Phases C and D of the #216 local-NFO work, implemented test-first, plus
the mixed-library use-case pins. Together these deliver the headline
case: a series absent from every remote database (e.g. a fitness
library) scans into a fully presented show -> named seasons -> titled
episodes tree from NFO files and sidecar art alone.

Local sidecar artwork through the S3 image cache (Phase C):
- The NFO provider implements ImageProvider: poster/backdrop/logo
  sidecar discovery with a fixed precedence map, symlink/non-regular
  rejection, an 8 MiB cap, and file:// source URLs at rating 0. Generic
  filenames apply only via the sidecar search paths, so a shared
  folder.jpg in a flat multi-movie directory applies to none.
- file:// becomes a live local source scheme: routed into *_source_path
  (never *_path), accepted by every image enqueue gate, attributed as
  provider "local", excluded from cached-path detection.
- The image-cache processor caches local files with lexical-on-logical
  confinement to the library roots, open-handle reads with re-checks,
  the same variant widths as remote art, and stable (7-day) failure
  classification. Keys land under
  local/{contentType}/{contentID}/{hash8}/{imageType}; superseded
  prefixes are cleaned on re-cache and item deletion.
- applyIfBetter gains a local exemption so rating-0 local art can fill
  matched items without being stickily displaced; ImageRequest carries
  additive sidecar path context.

Series depth (Phase D):
- SeasonsRequest/EpisodesRequest carry additive local path context
  (series roots, per-season directories, per-episode file paths),
  derived from naming at match time and reconstructed on refresh.
- season.nfo supplies season name/plot; NFO season numbers are advisory
  (directory-derived number wins with a Warn - naming owns structure).
  <episodedetails> gains aired/runtime/ratings; <basename>.nfo titles
  episodes and <basename>-thumb.ext supplies thumbs; filename SxxEyy
  wins over NFO numbers.
- Episode NFOs work without a season.nfo (provider seasons unioned with
  on-disk seasons); SynthesizeFallbackEpisodes always runs after persist
  so NFO-less episodes keep synthesized rows. Season/episode file:// art
  rides the Phase C pipeline unchanged.
- Migration adds season:1/episode:1 to the builtin NFO capability's
  default_priority (still default_enabled=false).

Mixed sports-library use case (tests only, no product change):
- Pins the classification contract for one library holding movie-shaped
  and show-shaped content (WWE PPV events as movies next to a "WWE
  SmackDown" show, NASCAR/F1/FIFA with partial TVDB/TMDB data): naming
  decides movie-vs-series per file before any provider runs; the NFO
  supplies metadata/identity but never flips type (ContentType guard);
  the per-root Type override is the correction path.
- NFO-driven type classification at scan time is recorded as an explicit
  deferred open question.

Part of #216

AI-use disclosure: implemented with Claude Code (Fable 5) via
spec-driven TDD and agent-assisted implementation.

* docs(metadata): document local NFO metadata architecture

Add a single as-built architecture page
(docs/architecture/local-nfo-metadata.md) for the #216 local-NFO
feature: the builtin registration model, hint-first identity semantics,
the file:// -> S3 artwork pipeline and its deployment constraint, series
depth, the mixed-library classification contract, and known limitations.

This replaces the working implementation plan, the per-phase specs, and
the narrow sidecar-artwork note, which were planning drafts and are left
untracked; admin-facing behavior remains in the wiki.

Part of #216

AI-use disclosure: planned, drafted, and consolidated with Claude Code
(Fable 5) using multi-agent exploration and adversarial review.

* fix(metadata): address PR review findings on NFO builtin provider

Fold in the valid, low-risk fixes surfaced by automated review on #390:

- imagecache: extract validateCacheRequest so CacheBytes (the local
  sidecar season/episode path) enforces the same episode-requires-season
  guard as Cache, preventing distinct episodes' art from colliding under
  one S3 key.
- image_cache_processor: close the sidecar symlink-swap window by
  rejecting the opened handle unless os.SameFile matches the Lstat'd
  file, so a leaf swapped to a symlink can't pull an out-of-root target
  into the public cache.
- plugins: guard the reserved builtin installation row in the store's
  Update, matching Delete, so its version/enabled/capabilities can never
  be rewritten even if a mutation slips past the HTTP layer.
- cmd/silo: bound SyncBuiltinProviderChains with a 30s timeout so a stuck
  DB round-trip fails fast at startup instead of hanging.
- metadata: panic instead of silently no-op'ing on an invalid
  RegisterBuiltinProvider call (init-time programmer error).
- docs: correct the media-folder-and-naming NFO paragraph to state
  season/episode NFOs and sidecar artwork are actively read.

---------

Co-authored-by: Quick104 <31828688+Quick104@users.noreply.github.com>
2026-07-16 17:55:36 -04:00

257 lines
7.7 KiB
Go

package plugins
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"sync"
"google.golang.org/protobuf/types/known/structpb"
pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1"
"github.com/Silo-Server/silo-server/internal/cache"
"github.com/Silo-Server/silo-server/internal/events"
"github.com/Silo-Server/silo-server/internal/pluginhost"
)
type eventConsumerClient interface {
HandleEvent(ctx context.Context, req *pluginv1.HandleEventRequest) (*pluginv1.HandleEventResponse, error)
}
type eventConsumerResolver interface {
EventConsumerClient(ctx context.Context, installationID int, capabilityID string) (eventConsumerClient, error)
}
// EventDispatcher delivers host events to plugin event_consumer.v1 capabilities
// whose manifest "subscriptions" list matches the event name. It listens on
// two sources:
//
// - The cache.EventBus channels (catalog/admin/playback) for events that
// direct callers — host code in api/handlers and worker packages —
// publish via the bus.
// - The events.Hub for envelopes routed through the in-process hub. This is
// the path plugin-published events take (RuntimeHostServer.PublishEvent
// stamps `plugin.<id>.` and writes an envelope on ChannelPlugins). Without
// this subscription, plugin↔plugin events never reach consumers.
//
// Dispatch is fan-out only: every subscriber to event_name receives the event.
// Plugins wanting to address a single peer should embed a target identifier
// in the payload and have subscribers filter on it.
type EventDispatcher struct {
bus cache.EventBus
hub *events.Hub
installations taskInstallationStore
resolver eventConsumerResolver
concurrency int
sem chan struct{}
hubUnsubscribe func()
}
func NewEventDispatcher(
bus cache.EventBus,
hub *events.Hub,
installations taskInstallationStore,
resolver eventConsumerResolver,
concurrency int,
) *EventDispatcher {
if concurrency < 1 {
concurrency = 4
}
return &EventDispatcher{
bus: bus,
hub: hub,
installations: installations,
resolver: resolver,
concurrency: concurrency,
sem: make(chan struct{}, concurrency),
}
}
func NewEventDispatcherWithTypedResolver(
bus cache.EventBus,
hub *events.Hub,
installations taskInstallationStore,
resolver interface {
EventConsumerClient(ctx context.Context, installationID int, capabilityID string) (*pluginhost.EventConsumerClient, error)
},
concurrency int,
) *EventDispatcher {
return NewEventDispatcher(bus, hub, installations, eventConsumerResolverFunc(func(
ctx context.Context,
installationID int,
capabilityID string,
) (eventConsumerClient, error) {
return resolver.EventConsumerClient(ctx, installationID, capabilityID)
}), concurrency)
}
func (d *EventDispatcher) Start(ctx context.Context) error {
for _, channel := range []string{cache.ChannelCatalog, cache.ChannelAdmin, cache.ChannelPlayback} {
channel := channel
if err := d.bus.Subscribe(ctx, channel, func(event cache.Event) {
d.dispatchBusEvent(ctx, event)
}); err != nil {
return fmt.Errorf("subscribe plugin event dispatcher to %s: %w", channel, err)
}
}
if d.hub != nil {
envCh, unsub := d.hub.Subscribe()
d.hubUnsubscribe = unsub
go d.consumeHub(ctx, envCh)
}
return nil
}
func (d *EventDispatcher) Stop() {
if d.hubUnsubscribe != nil {
d.hubUnsubscribe()
d.hubUnsubscribe = nil
}
}
func (d *EventDispatcher) consumeHub(ctx context.Context, ch <-chan events.Envelope) {
for {
select {
case <-ctx.Done():
return
case env, ok := <-ch:
if !ok {
return
}
d.dispatchEnvelope(ctx, env)
}
}
}
func (d *EventDispatcher) dispatchBusEvent(ctx context.Context, event cache.Event) {
d.fanOut(ctx, events.Envelope{Event: event.Type}, decodeStringPayload(event.Payload))
}
func (d *EventDispatcher) dispatchEnvelope(ctx context.Context, env events.Envelope) {
d.fanOut(ctx, env, decodeRawJSON(env.Data))
}
// decodeStringPayload tries to JSON-decode a cache.Event.Payload string into a
// structpb. Plugin consumers expect top-level fields (e.g. p["libraryId"]), so
// when the payload parses we pass it through as-is. If it doesn't parse — the
// payload is an opaque id rather than JSON — we still hand the raw value over
// under "raw" so the consumer can ignore it without misreading nil fields.
func decodeStringPayload(raw string) *structpb.Struct {
if raw == "" {
return nil
}
var m map[string]any
if err := json.Unmarshal([]byte(raw), &m); err == nil {
s, _ := structpb.NewStruct(m)
return s
}
s, _ := structpb.NewStruct(map[string]any{"raw": raw})
return s
}
func decodeRawJSON(raw json.RawMessage) *structpb.Struct {
if len(raw) == 0 {
return nil
}
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil
}
s, _ := structpb.NewStruct(m)
return s
}
// fanOut dispatches env to every plugin event_consumer.v1 capability that
// declares an exact-name subscription matching env.Event.
func (d *EventDispatcher) fanOut(ctx context.Context, env events.Envelope, payload *structpb.Struct) {
installations, err := d.installations.ListEnabled(ctx)
if err != nil {
slog.WarnContext(ctx, "plugin event dispatcher: list installations failed", "component", "plugins", "error", err)
return
}
var wg sync.WaitGroup
for _, installation := range installations {
// Builtin installations are metadata-only and never launchable;
// defense-in-depth alongside the capability-type filter below.
if installation.IsBuiltin() {
continue
}
if env.TargetPluginID != "" && installation.PluginID != env.TargetPluginID {
continue
}
capabilities, err := d.installations.ListCapabilities(ctx, installation.ID)
if err != nil {
slog.WarnContext(ctx, "plugin event dispatcher: list capabilities failed", "component", "plugins", "installation_id", installation.ID, "error", err)
continue
}
for _, capability := range capabilities {
if capability == nil || capability.Type != "event_consumer.v1" {
continue
}
if !subscribesTo(capability, env.Event) {
continue
}
wg.Add(1)
d.sem <- struct{}{}
go func(installationID int, capabilityID string) {
defer wg.Done()
defer func() { <-d.sem }()
client, err := d.resolver.EventConsumerClient(ctx, installationID, capabilityID)
if err != nil {
slog.WarnContext(ctx, "plugin event dispatcher: resolve client failed", "component", "plugins", "installation_id", installationID, "capability_id", capabilityID, "error", err)
return
}
if _, err := client.HandleEvent(ctx, &pluginv1.HandleEventRequest{
EventName: env.Event,
Payload: payload,
}); err != nil {
slog.WarnContext(ctx, "plugin event dispatcher: delivery failed", "component", "plugins", "installation_id", installationID, "capability_id", capabilityID, "error", err)
}
}(installation.ID, capability.ID)
// Deliver to the first matching event_consumer.v1 capability per
// installation to preserve one-delivery-per-install semantics.
break
}
}
wg.Wait()
}
func subscribesTo(capability *Capability, eventType string) bool {
if capability == nil {
return false
}
subscriptions, ok := capability.Metadata["subscriptions"]
if !ok {
return false
}
values, err := toStringSlice(subscriptions)
if err != nil {
return false
}
for _, subscription := range values {
if subscription == eventType {
return true
}
}
return false
}
type eventConsumerResolverFunc func(ctx context.Context, installationID int, capabilityID string) (eventConsumerClient, error)
func (f eventConsumerResolverFunc) EventConsumerClient(
ctx context.Context,
installationID int,
capabilityID string,
) (eventConsumerClient, error) {
return f(ctx, installationID, capabilityID)
}