plugin

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package plugin is the Go SDK for writing source plugins for Panelarr.

A plugin implements Plugin and calls Main (or Serve) from its main function. The same binary then works in both run modes:

  • managed: the host starts the binary as a child process and talks to it over gRPC on a local socket (HashiCorp go-plugin handshake);
  • standalone: the binary is started with --listen and serves gRPC and Connect on that address, and the host connects to it by URL.

Embed Unimplemented to get "not supported" answers for the calls a plugin does not need.

Index

Constants

View Source
const (
	CodeInvalidArgument    = connect.CodeInvalidArgument
	CodeNotFound           = connect.CodeNotFound
	CodeUnimplemented      = connect.CodeUnimplemented
	CodeUnavailable        = connect.CodeUnavailable
	CodeResourceExhausted  = connect.CodeResourceExhausted
	CodeFailedPrecondition = connect.CodeFailedPrecondition
	CodeUnauthenticated    = connect.CodeUnauthenticated
	CodePermissionDenied   = connect.CodePermissionDenied
	CodeInternal           = connect.CodeInternal
	CodeAlreadyExists      = connect.CodeAlreadyExists
)

Codes plugins return most often.

View Source
const ErrorDomain = "source.panelarr"

ErrorDomain is the google.rpc.ErrorInfo domain of source errors.

View Source
const ImageChunkSize = 64 << 10

ImageChunkSize is how many bytes SendImage puts in one message.

View Source
const MaxMessageSize = 16 << 20

MaxMessageSize bounds a single message between host and plugin. Images are streamed in chunks, so no single message needs to be large.

View Source
const PluginName = "source"

PluginName is the name the plugin is dispensed under in go-plugin.

View Source
const Protocol = "panelarr.source.v1"

Protocol is the protocol package plugins built with this SDK speak.

Variables

View Source
var Handshake = goplugin.HandshakeConfig{
	ProtocolVersion:  1,
	MagicCookieKey:   "PANELARR_SOURCE_PLUGIN",
	MagicCookieValue: "8d2e6a31-panelarr.source.v1",
}

Handshake is the go-plugin handshake shared by hosts and managed source plugins. The cookie only stops people from running a plugin binary by hand by mistake; it is not a security measure.

View Source
var InstanceID = func() string {
	b := make([]byte, 8)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}()

InstanceID identifies this run of the process: random, set at start. The SDK puts it in Health answers that don't carry their own, so hosts notice a restart and push configuration and profiles again.

View Source
var PackageIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)

PackageIDPattern is what package IDs look like: no ':', which HTTP paths read as a custom verb (as in ":install").

Functions

func FromConnectError

func FromConnectError(err error) error

FromConnectError converts an error returned by a Connect client into an *Error. Context errors are returned unchanged.

func FromGRPCError

func FromGRPCError(err error) error

FromGRPCError converts an error returned by a gRPC client into an *Error.

func IsManaged

func IsManaged() bool

IsManaged reports whether the process was started by a host through the go-plugin handshake.

func Main

func Main(p Plugin, opts ...MainOption)

Main runs a plugin from its main function. It reads the standard flags and environment variables and calls Serve:

--listen addr    standalone mode on addr (env PLUGIN_LISTEN)
--api-key key    key callers must send in standalone mode (env PLUGIN_API_KEY)
--config file    plugin-level configuration as JSON (env PLUGIN_CONFIG)

Started by a host (managed), it ignores --listen and --config: the host sends the configuration with SetConfig. Run by hand without --listen (and without WithDefaultListen), it prints usage and exits.

func NewHTTPServer

func NewHTTPServer(p Plugin, apiKey string, routes ...Route) *http.Server

NewHTTPServer returns an HTTP server (HTTP/1.1 and cleartext HTTP/2) that serves the plugin over gRPC, gRPC-Web and Connect, plus an unauthenticated GET /healthz and any extra routes. Use it to embed a plugin in your own server or in tests.

func NewHandler

func NewHandler(p Plugin, apiKey string, routes ...Route) http.Handler

NewHandler returns the plugin's HTTP handler (see NewHTTPServer).

func PluginSet

func PluginSet(impl Plugin) goplugin.PluginSet

PluginSet is the go-plugin plugin set for source plugins.

func RegisterGRPC

func RegisterGRPC(s *grpc.Server, p Plugin)

RegisterGRPC registers p on a gRPC server, for hosts and tests that run their own grpc-go server.

func SendImage

func SendImage(send ImageSendFunc, contentType string, size int64, r io.Reader) error

SendImage streams an image to the host: the metadata first, then the bytes of r in chunks. size is the total length, or 0 when unknown.

func Serve

func Serve(ctx context.Context, p Plugin, cfg Config) error

Serve runs p until ctx is cancelled (standalone) or the host ends the plugin (managed).

func ToConnectError

func ToConnectError(err error) error

ToConnectError converts err for a Connect handler.

func ToGRPCError

func ToGRPCError(err error) error

ToGRPCError converts err for a gRPC handler.

Types

type Code

type Code = connect.Code

Code is a status code. The values are the gRPC/Connect codes.

func ErrorCode

func ErrorCode(err error) Code

ErrorCode returns the code of err: the code of an *Error, CodeCanceled or CodeDeadlineExceeded for context errors, CodeInternal otherwise.

type Config

type Config struct {
	// Listen is the address for standalone mode, e.g. ":8904". Empty means
	// managed mode (started by a host).
	Listen string
	// APIKey, when set, is required as "Authorization: Bearer <key>" on
	// every standalone call except Health and the /healthz probe.
	APIKey string
	// ConfigFile, when set, is a JSON file with the plugin-level
	// configuration, applied with SetConfig before serving (standalone mode).
	ConfigFile string
	// Routes are extra HTTP routes served next to the API in standalone
	// mode, e.g. /metrics or icons.
	Routes []Route
	// Logger defaults to JSON on stderr.
	Logger *slog.Logger
}

Config controls how Serve runs a plugin.

type Error

type Error struct {
	Code    Code
	Reason  Reason
	Message string
	// RetryAfter tells the caller when to try again, e.g. after the source
	// rate-limited the plugin. Zero means no hint.
	RetryAfter time.Duration
	// CurrentRunID is the running run, when starting a job that is already
	// running (reason ALREADY_RUNNING).
	CurrentRunID string
	// Metadata is extra detail for the ErrorInfo, e.g. the job_id of
	// JOB_DISABLED.
	Metadata map[string]string
}

Error is an error with a status code and, for upstream failures, a reason, carried across the process or network boundary between plugin and host.

func ErrAlreadyRunning

func ErrAlreadyRunning(runID, format string, args ...any) *Error

ErrAlreadyRunning says a job can't start because it is running already, as the run runID.

func ErrChallenge

func ErrChallenge(format string, args ...any) *Error

ErrChallenge says an anti-bot challenge blocked the request and no solver passed it.

func ErrInvalidArgument

func ErrInvalidArgument(format string, args ...any) *Error

ErrInvalidArgument says the request (or the settings) can't be used.

func ErrJobDisabled

func ErrJobDisabled(jobID, reason string) *Error

ErrJobDisabled says a job can't run now, for the reason given.

func ErrLoginRequired

func ErrLoginRequired(format string, args ...any) *Error

ErrLoginRequired says the upstream wants a login the plugin doesn't have.

func ErrNotFound

func ErrNotFound(format string, args ...any) *Error

ErrNotFound says the source, series, chapter or page doesn't exist.

func ErrRateLimited

func ErrRateLimited(retryAfter time.Duration, format string, args ...any) *Error

ErrRateLimited says the upstream is rate-limiting the plugin.

func ErrSourceDown

func ErrSourceDown(format string, args ...any) *Error

ErrSourceDown says the upstream is unreachable, timed out or failing.

func ErrStoreFetchFailed

func ErrStoreFetchFailed(format string, args ...any) *Error

ErrStoreFetchFailed says a package's origin, or a file it lists, couldn't be downloaded.

func ErrStoreInvalid

func ErrStoreInvalid(format string, args ...any) *Error

ErrStoreInvalid says a package's origin, or a file it lists, can't be used: unreadable, or signed with a key that doesn't match.

func ErrUnimplemented

func ErrUnimplemented(method string) *Error

ErrUnimplemented says the plugin does not support a call.

func ErrUnsupported

func ErrUnsupported(format string, args ...any) *Error

ErrUnsupported says the source does not support a call, e.g. Latest on a source without the LATEST capability.

func Errorf

func Errorf(code Code, format string, args ...any) *Error

Errorf returns an *Error with the code and a formatted message.

func (*Error) Error

func (e *Error) Error() string

type GRPCPlugin

type GRPCPlugin struct {
	goplugin.NetRPCUnsupportedPlugin
	Impl Plugin
}

GRPCPlugin is the go-plugin glue for source plugins. Hosts use it with a nil Impl to dispense a client; plugins serve with Impl set.

func (*GRPCPlugin) GRPCClient

func (g *GRPCPlugin) GRPCClient(_ context.Context, _ *goplugin.GRPCBroker, c *grpc.ClientConn) (any, error)

GRPCClient returns a gRPC client for the plugin service.

func (*GRPCPlugin) GRPCServer

func (g *GRPCPlugin) GRPCServer(_ *goplugin.GRPCBroker, s *grpc.Server) error

GRPCServer registers the plugin on the go-plugin gRPC server.

type ImageSendFunc

type ImageSendFunc func(*sourcev1.FetchImageResponse) error

ImageSendFunc sends one FetchImage message to the host. It returns an error when the host has gone away; the plugin should then stop.

type MainOption

type MainOption func(*mainOptions)

MainOption changes how Main behaves.

func WithDefaultListen

func WithDefaultListen(addr string) MainOption

WithDefaultListen makes the plugin serve standalone on addr when it is run by hand without --listen. Standalone plugins use ports from 8903 up.

func WithRoutes

func WithRoutes(routes ...Route) MainOption

WithRoutes adds HTTP routes to the standalone server (see Route).

type Plugin

type Plugin interface {
	GetInfo(ctx context.Context, req *sourcev1.GetInfoRequest) (*sourcev1.GetInfoResponse, error)
	// GetConfig and SetConfig carry the plugin-level configuration described
	// by PluginInfo.config_schema. [PluginConfig] implements both.
	GetConfig(ctx context.Context, req *sourcev1.GetConfigRequest) (*sourcev1.GetConfigResponse, error)
	SetConfig(ctx context.Context, req *sourcev1.SetConfigRequest) (*sourcev1.SetConfigResponse, error)
	Health(ctx context.Context, req *sourcev1.HealthRequest) (*sourcev1.HealthResponse, error)
	ListSources(ctx context.Context, req *sourcev1.ListSourcesRequest) (*sourcev1.ListSourcesResponse, error)
	GetSource(ctx context.Context, req *sourcev1.GetSourceRequest) (*sourcev1.GetSourceResponse, error)
	GetFilters(ctx context.Context, req *sourcev1.GetFiltersRequest) (*sourcev1.GetFiltersResponse, error)
	Popular(ctx context.Context, req *sourcev1.PopularRequest) (*sourcev1.PopularResponse, error)
	Latest(ctx context.Context, req *sourcev1.LatestRequest) (*sourcev1.LatestResponse, error)
	Search(ctx context.Context, req *sourcev1.SearchRequest) (*sourcev1.SearchResponse, error)
	ResolveUrl(ctx context.Context, req *sourcev1.ResolveUrlRequest) (*sourcev1.ResolveUrlResponse, error) //nolint:revive // named after the RPC
	GetSeries(ctx context.Context, req *sourcev1.GetSeriesRequest) (*sourcev1.GetSeriesResponse, error)
	ListChapters(ctx context.Context, req *sourcev1.ListChaptersRequest) (*sourcev1.ListChaptersResponse, error)
	ListPages(ctx context.Context, req *sourcev1.ListPagesRequest) (*sourcev1.ListPagesResponse, error)
	// FetchImage streams one image through send: the metadata first, then
	// the bytes. [SendImage] does that from an io.Reader.
	FetchImage(ctx context.Context, req *sourcev1.FetchImageRequest, send ImageSendFunc) error
	GetSettingsSchema(ctx context.Context, req *sourcev1.GetSettingsSchemaRequest) (*sourcev1.GetSettingsSchemaResponse, error)
	GetSettings(ctx context.Context, req *sourcev1.GetSettingsRequest) (*sourcev1.GetSettingsResponse, error)
	SetSettings(ctx context.Context, req *sourcev1.SetSettingsRequest) (*sourcev1.SetSettingsResponse, error)
	// The package calls, for plugins with the PACKAGES capability: see the proto.
	// Package IDs must match [PackageIDPattern].
	ListPackages(ctx context.Context, req *sourcev1.ListPackagesRequest) (*sourcev1.ListPackagesResponse, error)
	GetPackage(ctx context.Context, req *sourcev1.GetPackageRequest) (*sourcev1.GetPackageResponse, error)
	InstallPackage(ctx context.Context, req *sourcev1.InstallPackageRequest) (*sourcev1.InstallPackageResponse, error)
	UpdatePackage(ctx context.Context, req *sourcev1.UpdatePackageRequest) (*sourcev1.UpdatePackageResponse, error)
	UninstallPackage(ctx context.Context, req *sourcev1.UninstallPackageRequest) (*sourcev1.UninstallPackageResponse, error)
	SetPackageSettings(ctx context.Context, req *sourcev1.SetPackageSettingsRequest) (*sourcev1.SetPackageSettingsResponse, error)
	// ListOrigins, RefreshOrigin and ReloadPackage are package calls too.
	ListOrigins(ctx context.Context, req *sourcev1.ListOriginsRequest) (*sourcev1.ListOriginsResponse, error)
	RefreshOrigin(ctx context.Context, req *sourcev1.RefreshOriginRequest) (*sourcev1.RefreshOriginResponse, error)
	ReloadPackage(ctx context.Context, req *sourcev1.ReloadPackageRequest) (*sourcev1.ReloadPackageResponse, error)
	// SetSourceHealthCheck turns a source's scheduled checks on or off, for
	// plugins with the HEALTH_CHECKS capability.
	SetSourceHealthCheck(ctx context.Context, req *sourcev1.SetSourceHealthCheckRequest) (*sourcev1.SetSourceHealthCheckResponse, error)
	// GetNetworkProfile returns the profile a source uses and where it comes
	// from (optional).
	GetNetworkProfile(ctx context.Context, req *sourcev1.GetNetworkProfileRequest) (*sourcev1.GetNetworkProfileResponse, error)
	// SetNetworkProfile receives a source's network profile from the host.
	// Plugins that declare the network profile common service apply it to
	// every request for that source; httpx.Sources does that for them.
	SetNetworkProfile(ctx context.Context, req *sourcev1.SetNetworkProfileRequest) (*sourcev1.SetNetworkProfileResponse, error)
	// The job calls, for plugins with the JOBS capability: see the proto and
	// panelarr.jobs.v1. The jobs package implements them.
	ListJobs(ctx context.Context, req *sourcev1.ListJobsRequest) (*sourcev1.ListJobsResponse, error)
	GetJob(ctx context.Context, req *sourcev1.GetJobRequest) (*sourcev1.GetJobResponse, error)
	ListJobRuns(ctx context.Context, req *sourcev1.ListJobRunsRequest) (*sourcev1.ListJobRunsResponse, error)
	GetJobRun(ctx context.Context, req *sourcev1.GetJobRunRequest) (*sourcev1.GetJobRunResponse, error)
	RunJob(ctx context.Context, req *sourcev1.RunJobRequest) (*sourcev1.RunJobResponse, error)
	CancelJobRun(ctx context.Context, req *sourcev1.CancelJobRunRequest) (*sourcev1.CancelJobRunResponse, error)
}

Plugin is what a source plugin implements. The methods mirror the SourcePluginService RPCs; see the proto for their contracts.

Return an *Error (see Errorf and the Err* helpers) to control the status code and error reason the host sees. Any other error is reported as an internal error.

type PluginConfig

type PluginConfig struct {
	// contains filtered or unexported fields
}

PluginConfig holds a plugin's plugin-level configuration, described by a JSON Schema, and implements the GetConfig and SetConfig calls. Embed it in a plugin (it then answers those calls) and put PluginConfig.SchemaStruct in PluginInfo.config_schema.

Properties the schema marks "writeOnly" (secrets) are never returned, and an empty value for one keeps the current value, so a configuration read with GetConfig can be sent back unchanged.

func NewPluginConfig

func NewPluginConfig(schema *settings.Schema, apply func(ctx context.Context, values map[string]any) error) *PluginConfig

NewPluginConfig returns a configuration with the schema's defaults. apply is called with the full new configuration (defaults filled in) before a change takes effect; an error rejects the change. It may be nil.

func (*PluginConfig) GetConfig

GetConfig implements the RPC.

func (*PluginConfig) Schema

func (c *PluginConfig) Schema() *settings.Schema

Schema returns the configuration schema.

func (*PluginConfig) SchemaStruct

func (c *PluginConfig) SchemaStruct() *structpb.Struct

SchemaStruct returns the schema for PluginInfo.config_schema.

func (*PluginConfig) Set

func (c *PluginConfig) Set(ctx context.Context, values map[string]any) error

Set validates values and makes them the configuration.

func (*PluginConfig) SetConfig

SetConfig implements the RPC.

func (*PluginConfig) Values

func (c *PluginConfig) Values() map[string]any

Values returns a copy of the configuration in effect, secrets included.

type Reason

type Reason string

Reason is why a request failed because of the upstream source: an ErrorReason name without its prefix, e.g. "SOURCE_DOWN". It travels as the reason of a google.rpc.ErrorInfo.

const (
	ReasonChallenge     Reason = "CLOUDFLARE_CHALLENGE"
	ReasonRateLimited   Reason = "RATE_LIMITED"
	ReasonSourceDown    Reason = "SOURCE_DOWN"
	ReasonNotFound      Reason = "NOT_FOUND"
	ReasonLoginRequired Reason = "LOGIN_REQUIRED"
	ReasonUnsupported   Reason = "UNSUPPORTED"
	// Package origins (e.g. extension stores).
	ReasonStoreFetchFailed Reason = "STORE_FETCH_FAILED"
	ReasonStoreInvalid     Reason = "STORE_INVALID"
	// Jobs.
	ReasonAlreadyRunning Reason = "ALREADY_RUNNING"
	ReasonJobDisabled    Reason = "JOB_DISABLED"
)

Reasons of the source API (sourcev1.ErrorReason).

func ErrorReason

func ErrorReason(err error) Reason

ErrorReason returns the reason of err, or "" when it has none.

func ReasonOf

func ReasonOf(r sourcev1.ErrorReason) Reason

ReasonOf turns an ErrorReason value into its wire name.

type Route

type Route struct {
	// Pattern is an http.ServeMux pattern, e.g. "GET /metrics".
	Pattern string
	Handler http.Handler
	Public  bool
}

Route is an extra HTTP route of a standalone plugin. It needs the API key like the API unless Public is set.

type Unimplemented

type Unimplemented struct{}

Unimplemented answers every call with CodeUnimplemented (reason UNSUPPORTED), except Health (always serving), GetFilters (no filters) and the settings calls (no settings). Embed it in a plugin and override what the plugin supports.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL