Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ release builds resolve the SDK from a published module tag.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability` — stable capability type constants for manifests and peer discovery.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/config` — config-schema helpers.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/convert` — type conversions.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events` — the host event catalog: event names, access classes, and typed payloads (see [docs/events.md](docs/events.md)).
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/httpclient` — credentialed JSON-over-HTTP client with bounded responses and typed status errors.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/imagevariant` — canonical image-size variant strings.
- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest` — manifest loading/rendering.
Expand Down
8 changes: 8 additions & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ with a `default` arm rather than an exhaustive match, and do not assume the
constants shipped in any given SDK tag are the complete set. The same rule
applies to any future open vocabulary added to `v1`.

Event subscriptions are open too. The manifest validator doesn't check them,
so manifests that predate the event catalog keep loading, and a plugin built
against a newer SDK loads on an older host, which ignores an event it doesn't
deliver. `manifest.SubscriptionProblems` reports names no host delivers, for a
plugin's own tests. The catalog and its payload types in `pkg/pluginsdk/events`
change additively: an event or a payload field is never renamed or removed
(see [events.md](events.md)).

`FetchMarkersRequest.episode_numbering` and `SubmitMarkerRequest.episode_numbering`
are open too. Hosts send an external ID key, today `tvdb` or `tmdb`, or leave the
field empty when they cannot tell. A marker provider treats a value it does not
Expand Down
123 changes: 123 additions & 0 deletions docs/events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Host events

An `event_consumer.v1` capability lists event names in its manifest
`subscriptions`, and the host calls `EventConsumer.HandleEvent` for each one
(see [runtime-host.md](runtime-host.md#receiving-events) for delivery
guarantees). This page lists the events a host delivers and their payloads.
The Go names and payload types are in
[`pkg/pluginsdk/events`](../pkg/pluginsdk/events).

A host delivers two kinds of events:

- **Catalog events**, listed below.
- **Plugin events**, named `plugin.<publisher plugin_id>.<name>`. The host
stamps the prefix when a plugin calls `PublishEvent`, so no plugin can
publish a catalog event.

The host delivers no other event name. A subscription to one is ignored.

## Decoding payloads

`HandleEventRequest.payload` is a JSON object. Decode it into the event's
payload type:

```go
import "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events"

func (s *server) HandleEvent(ctx context.Context, req *pluginv1.HandleEventRequest) (*pluginv1.HandleEventResponse, error) {
switch req.GetEventName() {
case events.SessionStarted:
var event events.SessionEvent
if err := events.Decode(req.GetPayload(), &event); err != nil {
return &pluginv1.HandleEventResponse{}, nil // malformed: ignore, don't retry
}
session := event.Session // nil when no server has a live record
// ...
}
return &pluginv1.HandleEventResponse{}, nil
}
```

Integers in payloads, such as counts and season numbers, fit in 53 bits, the
range a JSON number and a `google.protobuf.Value` hold exactly. Identifiers
are always strings.

To check that every subscription names an event a host delivers, call
`manifest.SubscriptionProblems` from the plugin's tests.

Payloads change additively:

- A field is never renamed, removed, retyped or given a new meaning. New fields
arrive only with an SDK release that adds them to the payload type, since a
host projects every payload through `events.Project`. Ignore fields you
don't know.
- A change that can't be made additively ships as a new event name; the old
event keeps its shape.
- An event never moves to a different access class.
- A field the host can leave out is a pointer (or an `omitempty` string), so
"absent" never reads as a zero ID, `0` or the zero time.

Vocabularies such as a job's `job_type` or a notification's `type` are open:
treat an unknown value as something you don't handle.

## Access

Each catalog event has an access class, which says whose data the payload
carries. A host may, in a later release, ask an administrator to approve the
`admin` and `user_data` classes before it delivers them, so subscribe only to
the events the plugin uses.

| Access | Carries |
|---|---|
| `public` | The catalog and libraries. Never names an account or profile. Plugin events are `public`. |
| `admin` | Server operations: playback activity, scans and jobs. Can name accounts, profiles, devices and network addresses, as the admin activity views do. |
| `user_data` | One profile's personal data, such as the notifications in its inbox. |

## Catalog

| Event | Access | Payload | When |
|---|---|---|---|
| `catalog.library.changed` | public | `LibraryChanged` | A scan or refresh changed a library. |
| `catalog.item.changed` | public | `ItemChanged` | A catalog item's metadata or artwork changed. |
| `session.started` | admin | `SessionEvent` | A playback session started. |
| `session.paused` | admin | `SessionEvent` | A playback session paused. |
| `session.resumed` | admin | `SessionEvent` | A paused session resumed. |
| `session.stopped` | admin | `SessionEvent` | A playback session ended. |
| `scan.started` | admin | `ScanEvent` | A library scan started. |
| `scan.completed` | admin | `ScanEvent` | A library scan finished. |
| `scan.failed` | admin | `ScanEvent` | A library scan failed. |
| `scan.cancelled` | admin | `ScanEvent` | A library scan was cancelled. |
| `job.created` | admin | `JobEvent` | An admin job was queued. |
| `job.completed` | admin | `JobEvent` | An admin job finished. |
| `job.failed` | admin | `JobEvent` | An admin job failed. |
| `job.cancelled` | admin | `JobEvent` | An admin job was cancelled. |
| `notification.created` | user_data | `Notification` | Silo added a notification to a profile's inbox. Provisional, see below. |

Notes on specific payloads:

- **`SessionEvent`** carries the live session (`session`, on started, paused
and resumed) or the history entry the end recorded (`history`, on stopped).
They carry the fields of `PlaybackSession` and `PlaybackHistoryEntry` and
no others: a field the host adds to its `/api/v2` `AdminPlaybackSession`
or `AdminPlaybackHistoryEntry` schema reaches plugins only when an SDK
release adds it to these types. A session's events can arrive out of
order; `seq` orders them.
- **`Notification`** identifies its recipient by `user_id` and `profile_id`
together. Profile IDs repeat across accounts. `reason_flags` carries the
fields of `NotificationReason`: `next_up` on a new episode, and the title
(`request_id`, `tmdb_id`, `media_type`, `title`, `year`, the decline
`reason`, `follower`) on a request or watchlist notification.
- **`notification.created` is provisional.** A plugin that sends a profile's
notifications somewhere else (Pushover, ntfy and the like) should provide a
`notification_channel.v1` destination, which gets the host's preferences,
queue and retries. This event may leave the catalog before SDK 1.0.
Comment on lines +110 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

#!/bin/bash
# Check capability declarations and service contracts at the reviewed revision.
rg -n -C 3 'notification_channel\.v1|NotificationChannel|notification_channel' README.md pkg

Repository: Silo-Server/silo-plugin-sdk

Length of output: 697


Script executed:

#!/bin/bash
git rev-parse HEAD
git cat-file -e edbb9223220981a1470a16893c9e67afcb4a74a2^{commit} && git cat-file -e 484878a049ba599ff34205482062eff58984bbd7^{commit} && git diff 484878a049ba599ff34205482062eff58984bbd7 edbb9223220981a1470a16893c9e67afcb4a74a2 -- docs/events.md
printf '\n--- project-wide notification contract references ---\n'
rg -n -i 'notification.channel|notificationchannel|notification_channel' --glob '!go.sum' . || test "$?" -eq 1
printf '\n--- files defining capability and service contracts ---\n'
rg -n -i 'capabilit(y|ies)|^service ' README.md pkg/pluginsdk/manifest proto/silo/plugin/v1 | sed -n '1,220p'
printf '\n--- repo guidance ---\n'
cat AGENTS.md CONTRIBUTING.md

Repository: Silo-Server/silo-plugin-sdk

Length of output: 35367


Script executed:

#!/bin/bash
nl -ba pkg/pluginsdk/capability/capability.go
nl -ba pkg/pluginsdk/manifest/manifest.go | sed -n '18,75p;80,145p'
nl -ba README.md | sed -n '22,48p'

Repository: Silo-Server/silo-plugin-sdk

Length of output: 8101


Do not recommend an unavailable notification destination.

The SDK does not define notification_channel.v1, and manifest.Validate rejects that capability type. Describe it as a future option rather than one plugin authors can implement now.

- Every identifier is a JSON string, as in `/api/v2`: `library_id`,
`user_id`, `created_by_user_id`, `content_id`, `profile_id`. Don't parse or
compare them as numbers. The one exception is `reason_flags.tmdb_id`, TMDB's
own numeric ID.

## Hosts

A host delivers only the events above and plugin events, after
`events.Project` rewrites each payload into its public shape. Adding an event
to the catalog, or a field to a payload type, is an additive SDK change.
4 changes: 3 additions & 1 deletion docs/runtime-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ events.

An `event_consumer.v1` capability lists the event names it wants in its
manifest `subscriptions`, and the host calls `EventConsumer.HandleEvent` for
each matching event. Once Silo has stored an event, it delivers it to each
each matching event. The host delivers the catalog events in
[events.md](events.md), which also documents their payloads, and plugin
events; it ignores a subscription to any other name. Once Silo has stored an event, it delivers it to each
Comment thread
Quick104 marked this conversation as resolved.
Resolved
subscribing installation at least once, however many Silo servers run,
unless every attempt fails:

Expand Down
217 changes: 217 additions & 0 deletions pkg/pluginsdk/events/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
// Package events is the catalog of host events an event_consumer.v1
// capability can subscribe to: their names, who their payloads are about, and
// the Go types their payloads decode into.
//
// The catalog is the public contract. A host delivers only the events listed
// here, and plugin events (names starting with PluginEventPrefix). Payloads
// change additively: a field is never renamed, removed, or given a new
// meaning, so decoding into the types in this package keeps working as hosts
// add fields. See docs/events.md.
package events

import (
"encoding/json"
"fmt"
"regexp"
"slices"
"strings"

"google.golang.org/protobuf/types/known/structpb"
)

// Access says who an event's payload is about, and so what an administrator
// approves before the host delivers it to a plugin.
type Access string

const (
// AccessPublic events describe the catalog and libraries, or come from
// plugins. They never name an account or profile.
AccessPublic Access = "public"
// AccessAdmin events describe server operations, such as playback
// activity, scans and jobs. They can name accounts, profiles, devices and
// network addresses, the way the admin activity views do.
AccessAdmin Access = "admin"
// AccessUserData events carry one profile's personal data, such as the
// notifications Silo adds to its inbox.
AccessUserData Access = "user_data"
)

// Valid reports whether a is one of the access classes this SDK knows.
func (a Access) Valid() bool {
switch a {
case AccessPublic, AccessAdmin, AccessUserData:
return true
}
return false
}

// Event names in the catalog.
const (
// CatalogLibraryChanged: a scan or refresh changed a library. Payload
// LibraryChanged.
CatalogLibraryChanged = "catalog.library.changed"
// CatalogItemChanged: one catalog item's metadata or artwork changed.
// Items a scan adds, removes or re-files are reported by
// CatalogLibraryChanged, not one by one. Payload ItemChanged.
CatalogItemChanged = "catalog.item.changed"

// SessionStarted, SessionPaused, SessionResumed and SessionStopped follow
// a playback session. Payload SessionEvent.
SessionStarted = "session.started"
SessionPaused = "session.paused"
SessionResumed = "session.resumed"
SessionStopped = "session.stopped"

// ScanStarted, ScanCompleted, ScanFailed and ScanCancelled follow a
// library scan. Payload ScanEvent.
ScanStarted = "scan.started"
ScanCompleted = "scan.completed"
ScanFailed = "scan.failed"
ScanCancelled = "scan.cancelled"

// JobCreated, JobCompleted, JobFailed and JobCancelled follow an admin
// job, such as a refresh or an export. Payload JobEvent.
JobCreated = "job.created"
JobCompleted = "job.completed"
JobFailed = "job.failed"
JobCancelled = "job.cancelled"

// NotificationCreated: Silo added a notification to a profile's inbox,
// such as a new episode or a request update. Payload Notification.
//
// Provisional: a plugin that delivers notifications should provide a
// notification_channel.v1 destination instead. This event may leave the
// catalog before SDK 1.0.
NotificationCreated = "notification.created"
)

// PluginEventPrefix starts the name of every event a plugin publishes. The
// host stamps it as plugin.<publisher plugin_id>.<name>, so a plugin cannot
// publish a host event. Plugin events are AccessPublic.
const PluginEventPrefix = "plugin."

// Definition describes one catalog event.
type Definition struct {
Name string
Access Access
Description string
newPayload func() any
}

// NewPayload returns a pointer to a new value of the event's payload type,
// for json.Unmarshal or Decode.
func (d Definition) NewPayload() any { return d.newPayload() }

func define[T any](name string, access Access, description string) Definition {
return Definition{Name: name, Access: access, Description: description, newPayload: func() any { return new(T) }}
}

var catalog = []Definition{
define[LibraryChanged](CatalogLibraryChanged, AccessPublic, "A scan or refresh changed a library."),
define[ItemChanged](CatalogItemChanged, AccessPublic, "A catalog item's metadata or artwork changed."),

define[SessionEvent](SessionStarted, AccessAdmin, "A playback session started."),
define[SessionEvent](SessionPaused, AccessAdmin, "A playback session paused."),
define[SessionEvent](SessionResumed, AccessAdmin, "A paused playback session resumed."),
define[SessionEvent](SessionStopped, AccessAdmin, "A playback session ended."),

define[ScanEvent](ScanStarted, AccessAdmin, "A library scan started."),
define[ScanEvent](ScanCompleted, AccessAdmin, "A library scan finished."),
define[ScanEvent](ScanFailed, AccessAdmin, "A library scan failed."),
define[ScanEvent](ScanCancelled, AccessAdmin, "A library scan was cancelled."),

define[JobEvent](JobCreated, AccessAdmin, "An admin job was queued."),
define[JobEvent](JobCompleted, AccessAdmin, "An admin job finished."),
define[JobEvent](JobFailed, AccessAdmin, "An admin job failed."),
define[JobEvent](JobCancelled, AccessAdmin, "An admin job was cancelled."),

define[Notification](NotificationCreated, AccessUserData, "Silo added a notification to a profile's inbox."),
}

var byName = func() map[string]Definition {
out := make(map[string]Definition, len(catalog))
for _, d := range catalog {
out[d.Name] = d
}
return out
}()

// Catalog returns every catalog event, in a stable order.
func Catalog() []Definition { return slices.Clone(catalog) }

// Lookup returns the catalog event named name. Plugin events aren't in the
// catalog; use AccessOf for them.
func Lookup(name string) (Definition, bool) {
d, ok := byName[name]
return d, ok
}

// IsPluginEvent reports whether name is an event a plugin published: the
// prefix, then a publisher plugin_id and an event name, both nonempty.
func IsPluginEvent(name string) bool {
rest, ok := strings.CutPrefix(name, PluginEventPrefix)
i := strings.LastIndexByte(rest, '.')
return ok && i > 0 && i < len(rest)-1
}

// AccessOf returns the access class of a catalog or plugin event. It reports
// false for any other name: the host doesn't deliver it.
func AccessOf(name string) (Access, bool) {
if d, ok := byName[name]; ok {
return d.Access, true
}
if IsPluginEvent(name) {
return AccessPublic, true
}
return "", false
}

// namePattern is the shape of an event name: dot-separated lowercase
// segments. Plugin IDs may contain hyphens, so segments may too.
var namePattern = regexp.MustCompile(`^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$`)

// ValidName reports whether name has the shape of an event name. It does
// not check the catalog; AccessOf does.
func ValidName(name string) bool {
return len(name) <= 256 && namePattern.MatchString(name)
}

// Decode decodes an event payload, as HandleEventRequest carries it, into
// out, which is usually a pointer to one of this package's payload types.
// Payload integers fit in 53 bits, which a protobuf Value holds exactly.
func Decode(payload *structpb.Struct, out any) error {
if payload == nil {
return fmt.Errorf("events: payload is empty")
}
raw, err := json.Marshal(payload.AsMap())
if err != nil {
return fmt.Errorf("events: encode payload: %w", err)
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("events: decode payload: %w", err)
}
return nil
}

// Project rewrites a catalog event's JSON payload into its public shape: the
// fields of the event's payload type, and nothing else. Hosts call it before
// delivering an event so internal fields don't reach plugins. Plugin events
// pass through unchanged. Any other name is an error.
func Project(name string, raw []byte) ([]byte, error) {
if IsPluginEvent(name) {
return raw, nil
}
d, ok := byName[name]
if !ok {
return nil, fmt.Errorf("events: %q is not a catalog event", name)
}
payload := d.NewPayload()
if err := json.Unmarshal(raw, payload); err != nil {
return nil, fmt.Errorf("events: decode %s payload: %w", name, err)
}
out, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("events: encode %s payload: %w", name, err)
}
return out, nil
}
Loading
Loading