navidrome/plugins/manifest.go
Kendall Garner b0c6d2e444
feat(plugins): add scrobbles access to PDK (#5795)
* initial scrobble api

* feat: add scrobble retrieval api

* address feedback (1)

* fix spelling

* be explicit about get

* add primary key field, update index, remove rowid references

* use unix timestamp for input and output

* initial api, some testing

* add tests, add count retrieval

* add docs, test for rejected user

* add permission validation for scrobble retriever

* chore(plugins): fix typos in scrobble retriever

Rename newScrobbleRetreverService, and fix FromTImestamp/nonero in the
ScrobbleRetriever doc comments, which generate into the Go and Rust PDKs.
Also corrects two mislabelled test entries.

* fix(plugins): make scrobble pagination order deterministic

Sorting only by submission_time left the order of equal timestamps up to the
query planner, but the cursor skips ties by offset, so an unstable order can
repeat or drop scrobbles between pages. Break ties on scrobbles.id, which the
existing scrobbles_user_time index already yields for free.

Descending is now honoured for every combination of From/To rather than only
when both or neither is set. This changes the default for a lone ToTimestamp
from newest-first to oldest-first.

* refactor(plugins): return the next page's options from GetScrobbles

Paging previously meant reading NextTimestamp and Cursor off the response and
deciding where each belonged: NextTimestamp into FromTimestamp when ascending
or ToTimestamp when descending, and Cursor copied every time, including when 0.
Both are silent data-loss bugs when a plugin gets them wrong.

GetScrobbles now returns the options for the following page, or nil when the
range is exhausted, so a plugin passes the value straight back and repeats.
ScrobbleCursor and ScrobbleList are gone; the query itself is unchanged.

* docs(plugins): warn against setting ScrobbleOptions.Offset manually

The all-ties carry rule assumes Offset counts already-returned rows at the
boundary timestamp, which only holds for the options GetScrobbles returns.
A hand-built From+Offset combination can silently skip scrobbles, so document
the field as managed pagination state instead of a generic skip.

* docs(plugins): document the ScrobbleRetriever host service in the README

Covers the manifest permissions (including the users requirement), the four
host functions, the options/ref field tables, and the pagination loop with
its two gotchas: the host-managed offset and the adjusted range on the
returned next options.

* chore(plugins): regenerate scrobble retriever stub with nil-safe accessors

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-08-08 22:13:29 -04:00

134 lines
4.4 KiB
Go

package plugins
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// DeclaredNames returns the sorted names of the non-nil permission fields. It
// reflects over the generated json tags so new permission types are picked up
// automatically rather than via a hand-maintained list.
func (p *Permissions) DeclaredNames() []string {
if p == nil {
return nil
}
var names []string
v := reflect.ValueOf(*p)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
f := v.Field(i)
if f.Kind() != reflect.Pointer || f.IsNil() {
continue
}
tag := t.Field(i).Tag.Get("json")
if name, _, _ := strings.Cut(tag, ","); name != "" && name != "-" {
names = append(names, name)
}
}
sort.Strings(names)
return names
}
//go:generate go tool go-jsonschema -p plugins --struct-name-from-title -o manifest_gen.go manifest-schema.json
// ParseManifest unmarshals manifest JSON and performs cross-field validation.
// This is the single entry point for manifest parsing after reading from a file.
func ParseManifest(data []byte) (*Manifest, error) {
var m Manifest
if err := json.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("parsing manifest JSON: %w", err)
}
if err := m.Validate(); err != nil {
return nil, fmt.Errorf("validating manifest: %w", err)
}
return &m, nil
}
// Validate performs cross-field validation that cannot be expressed in JSON Schema.
// This validates rules like "SubsonicAPI permission requires users permission".
func (m *Manifest) Validate() error {
// SubsonicAPI permission requires users permission
if m.Permissions != nil && m.Permissions.Users == nil {
if m.Permissions.Subsonicapi != nil {
return fmt.Errorf("'subsonicapi' permission requires 'users' permission to be declared")
}
if m.Permissions.ScrobbleRetriever != nil {
return fmt.Errorf("'scrobbleRetriever' permission requires 'users' permission to be declared")
}
}
// Matcher returns library content, so it requires the library permission (which
// is what exposes a library scope for configuration).
if m.Permissions != nil && m.Permissions.Matcher != nil {
if m.Permissions.Library == nil {
return fmt.Errorf("'matcher' permission requires 'library' permission to be declared")
}
}
// Validate config schema if present
if m.Config != nil && m.Config.Schema != nil {
if err := validateConfigSchema(m.Config.Schema); err != nil {
return fmt.Errorf("invalid config schema: %w", err)
}
}
return nil
}
// validateConfigSchema validates that the schema is a valid JSON Schema that can be compiled.
func validateConfigSchema(schema map[string]any) error {
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource("schema.json", schema); err != nil {
return fmt.Errorf("invalid schema structure: %w", err)
}
if _, err := compiler.Compile("schema.json"); err != nil {
return err
}
return nil
}
// ValidateWithCapabilities validates the manifest against detected capabilities.
// This must be called after WASM capability detection since Scrobbler capability
// is detected from exported functions, not manifest declarations.
func ValidateWithCapabilities(m *Manifest, capabilities []Capability) error {
// Scrobbler capability requires users permission
if hasCapability(capabilities, CapabilityScrobbler) {
if m.Permissions == nil || m.Permissions.Users == nil {
return fmt.Errorf("scrobbler capability requires 'users' permission to be declared in manifest")
}
}
// Scheduler permission requires SchedulerCallback capability
if m.Permissions != nil && m.Permissions.Scheduler != nil {
if !hasCapability(capabilities, CapabilityScheduler) {
return fmt.Errorf("'scheduler' permission requires plugin to export '%s' function", FuncSchedulerCallback)
}
}
// Task (taskqueue) permission requires TaskWorker capability
if m.Permissions != nil && m.Permissions.Taskqueue != nil {
if !hasCapability(capabilities, CapabilityTaskWorker) {
return fmt.Errorf("'taskqueue' permission requires plugin to export '%s' function", FuncTaskWorkerCallback)
}
}
return nil
}
// HasLibraryFilesystemPermission checks if the manifest grants filesystem permission for libraries.
func (m *Manifest) HasLibraryFilesystemPermission() bool {
return m.Permissions != nil &&
m.Permissions.Library != nil &&
m.Permissions.Library.Filesystem
}
func (m *Manifest) HasStoragePermission() bool {
return m.Permissions != nil && m.Permissions.Storage != nil
}