plugin

package
v1.17.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package plugin is the host side of service plugins: a kind=service binary under plugins/services/<key>/ is kept running by a Supervisor (spawned at boot, restarted with backoff after a crash, put to sleep after an idle limit when auto-off applies and woken by the next request) and reverse-proxied at /x/{key}/* with auth decided per manifest route.

Index

Constants

View Source
const (
	AutoOffDefault = "default" // follow the plugin's declaration
	AutoOffOn      = "on"      // force auto-off, even when the plugin says it cannot
	AutoOffOff     = "off"     // force always-on
)

Auto-off modes the admin picks per service.

View Source
const (
	StateStopped  = "stopped"
	StateStarting = "starting"
	StateRunning  = "running"
	StateBackoff  = "backoff" // crashed; waiting to restart
	// StateSleeping: stopped by auto-off after the idle limit; the next
	// request starts it again. Not a crash, so no backoff.
	StateSleeping = "sleeping"
)

State of a supervised service.

View Source
const HeaderTokenOwnerID = "X-Wick-Token-Owner-Id"

HeaderTokenOwnerID names, on a Token route, the wick user who created the access token the request carried.

View Source
const LogLines = 200

LogLines is how many trailing log lines a service keeps for its page.

View Source
const ScopeWhoami = "whoami"

ScopeWhoami needs no grant: every callback token may ask who it is.

View Source
const SecretMask = "••••••••"

SecretMask, like "", sent back for a secret keeps the stored value (for clients that echo a masked placeholder).

Variables

View Source
var (
	BackoffMin = time.Second
	BackoffMax = 30 * time.Second

	// StopGrace is how long a process gets after SIGTERM before SIGKILL.
	StopGrace = 5 * time.Second

	// WakeTimeout bounds how long a request waits for a sleeping service to
	// boot before it fails.
	WakeTimeout = 30 * time.Second
)

Backoff bounds between restarts of a crashed service.

View Source
var ErrNotRunning = errors.New("service plugin not running")

ErrNotRunning is returned for a request while the service is down.

View Source
var ErrTokenNotFound = errors.New("token not found")

ErrTokenNotFound is returned for an unknown token id.

View Source
var ErrWakeTimeout = errors.New("service plugin did not wake up in time")

ErrWakeTimeout is returned when a sleeping service did not boot within WakeTimeout.

Functions

func ConfigOwner

func ConfigOwner(key string) string

ConfigOwner is the configs owner of service key's rows.

func SetDefault

func SetDefault(h *Host)

SetDefault records the server's host for packages that only need to look services up (the Team remote_source adapter and wizard).

Types

type AccessToken

type AccessToken struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Hash      string    `json:"hash"`
	Hint      string    `json:"hint"` // last 4 chars, for telling tokens apart
	CreatedAt time.Time `json:"created_at"`
	LastUsed  time.Time `json:"last_used,omitempty"`
	// CreatedBy is the wick user who generated (or last rotated) the token;
	// the service's Host API calls on a token route run as that person.
	CreatedBy string `json:"created_by,omitempty"`
}

AccessToken is one admin-generated bearer for a service's token routes. Only the hash is kept; the plaintext is shown once.

type AutoOffSetting

type AutoOffSetting struct {
	Mode string `json:"mode,omitempty"`
	// IdleSeconds overrides the plugin's idle limit (0 = plugin default).
	IdleSeconds int `json:"idle_seconds,omitempty"`
}

AutoOffSetting is the admin's override of a service's auto-off. The zero value follows the plugin.

type AutoOffView

type AutoOffView struct {
	Supported          bool   `json:"supported"`
	Reason             string `json:"reason,omitempty"`
	DefaultIdleSeconds int    `json:"default_idle_seconds"`
	Mode               string `json:"mode"`
	IdleSeconds        int    `json:"idle_seconds"`
	// Enabled is the effective state; Forced means the admin overrode the
	// plugin (mode on/off).
	Enabled bool `json:"enabled"`
	Forced  bool `json:"forced"`
}

AutoOffView is a service's auto-off as the admin page shows it: what the plugin declares, what the admin set, and the effective result.

func (AutoOffView) String

func (a AutoOffView) String() string

type Caller

type Caller struct {
	Key    string
	Scopes []string
}

Caller is the plugin a callback request came from.

func CallerFrom

func CallerFrom(ctx context.Context) (Caller, bool)

CallerFrom returns the plugin behind a callback request.

type ConfigField

type ConfigField struct {
	Key         string `json:"key"`
	Value       string `json:"value"`
	Type        string `json:"type,omitempty"`
	Options     string `json:"options,omitempty"`
	Description string `json:"description,omitempty"`
	IsSecret    bool   `json:"is_secret"`
	HasValue    bool   `json:"has_value"`
	Required    bool   `json:"required"`
}

ConfigField is one config row as the admin page shows it: a secret's value never leaves the server, only HasValue tells one is stored.

type ConfigStore

type ConfigStore interface {
	EnsureOwned(ctx context.Context, owner string, rows ...entity.Config) error
	ListOwned(owner string) []entity.Config
	SetOwned(ctx context.Context, owner, key, value string) error
}

ConfigStore is the slice of the configs service a host needs.

type Host

type Host struct {
	Tokens *Tokens
	// SessionUser resolves the wick session of a request (nil = none).
	SessionUser func(*http.Request) *User
	// BaseURL is wick's public base URL handed to plugins as WICK_BASE_URL.
	BaseURL func() string
	// Configs stores each service's manifest config rows (owner
	// ConfigOwner(key)); secrets are encrypted at rest by the store.
	Configs ConfigStore
	// Config overrides the values pushed to the plugin after spawn (tests);
	// nil reads them from Configs.
	Config func(key string) map[string]string
	// Audit records an admin change of a service setting (actor, service
	// key, what changed); nil = log only.
	Audit func(actor, key, detail string)
	// HostAPI is the private Host API door (nil = none): its address goes
	// to every process and each proxied request gets a call id.
	HostAPI HostAPIDoor
	// contains filtered or unexported fields
}

Host owns every service plugin: supervision, the /x/{key}/* proxy with per-route auth, access tokens, and the callback token API.

func Default

func Default() *Host

Default returns the server's host (nil before the server built it).

func NewHost

func NewHost(tokens *Tokens, sockDir string) *Host

NewHost returns an empty host whose processes put sockets in sockDir.

func (*Host) Add

func (h *Host) Add(key, version string, sm wickplugin.ServiceModule, binary string) *Service

Add registers one service (not started).

func (*Host) Get

func (h *Host) Get(key string) (*Service, bool)

Get returns service key.

func (*Host) HandleCallback

func (h *Host) HandleCallback(pattern, scope string, fn http.Handler)

HandleCallback exposes h at /x/-{path} ("METHOD /api/..."), reachable only with a callback token whose plugin declared scope in callback_scopes.

func (*Host) Install

func (h *Host) Install(dir, key string, enabled func(string) bool, record func(key, kind, version string) error) bool

Install (re)loads service key from dir after a plugin install or update, so a new service runs without a wick reload and an update picks up its new manifest (routes, configs, scopes). The previous process, if any, is stopped first. Once the host has started, the loaded service is started too. Returns false when key is missing, disabled or fails verification.

func (*Host) List

func (h *Host) List() []*Service

List returns every service, sorted by key.

func (*Host) Load

func (h *Host) Load(dir string, enabled func(string) bool, record func(key, kind, version string) error) int

Load registers every enabled, verified service plugin under dir.

func (*Host) RegisterAdmin

func (h *Host) RegisterAdmin(mux *http.ServeMux, wrap func(http.Handler) http.Handler)

RegisterAdmin mounts the admin API under /manager/api/service-plugins; wrap is the admin middleware.

func (*Host) RemoteSources

func (h *Host) RemoteSources() []ServiceView

RemoteSources lists the services that declare remote_source (the "Plugin" choices of the Team Remote agent wizard).

func (*Host) Remove

func (h *Host) Remove(key string) bool

Remove stops service key and forgets it, ahead of an uninstall deleting its files. Reports whether it was loaded.

func (*Host) ServeHTTP

func (h *Host) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves /x/{key}/*.

func (*Host) SetConfig

func (h *Host) SetConfig(ctx context.Context, s *Service, values map[string]string) error

SetConfig stores values (manifest keys only; an empty or masked secret keeps the stored one) and pushes the new config to the running process.

func (*Host) Shutdown

func (h *Host) Shutdown()

Shutdown stops every service process in parallel (SIGTERM, then SIGKILL after StopGrace) and waits for them. Called on wick shutdown and before a reload hands over, so the successor spawns its own processes and no plugin outlives the wick that started it.

func (*Host) Start

func (h *Host) Start()

Start starts every service (always-on) once.

func (*Host) StopAll

func (h *Host) StopAll()

StopAll stops every service.

func (*Host) View

func (h *Host) View(s *Service, full bool) ServiceView

View builds s's admin view; full adds tokens and logs.

type HostAPIDoor added in v1.16.0

type HostAPIDoor interface {
	URL() string
	// BeginCallFrom records who one proxied request runs for; the plugin
	// echoes the id on its Host API calls. end forgets it.
	BeginCallFrom(key, kind, userID, source, sessionID string) (callID string, end func())
	// ServeAs serves a Host API request for an already authenticated plugin.
	ServeAs(w http.ResponseWriter, r *http.Request, key, kind string, scopes []string)
}

HostAPIDoor is the Host API side the service host needs (hostapi.Bridge satisfies it).

type RingLog

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

RingLog keeps the last n lines written to it.

func NewRingLog

func NewRingLog(n int) *RingLog

NewRingLog keeps n lines.

func (*RingLog) Lines

func (l *RingLog) Lines() []string

Lines returns a copy of the kept lines, oldest first.

func (*RingLog) Printf

func (l *RingLog) Printf(format string, a ...any)

Printf adds one host-side line (spawn, exit, restart).

func (*RingLog) Write

func (l *RingLog) Write(p []byte) (int, error)

type Service

type Service struct {
	Key, Version string
	Manifest     wickplugin.ServiceModule
	Sup          *Supervisor
}

Service is one loaded service plugin.

type ServiceView

type ServiceView struct {
	Key             string                    `json:"key"`
	Name            string                    `json:"name"`
	Description     string                    `json:"description,omitempty"`
	Version         string                    `json:"version"`
	Path            string                    `json:"path"`
	Status          Status                    `json:"status"`
	Routes          []wickplugin.ServiceRoute `json:"routes"`
	Capabilities    []string                  `json:"capabilities,omitempty"`
	CallbackScopes  []string                  `json:"callback_scopes,omitempty"`
	CallbackRevoked bool                      `json:"callback_revoked"`
	AutoOff         AutoOffView               `json:"auto_off"`
	Configs         []ConfigField             `json:"configs,omitempty"`
	Tokens          []TokenView               `json:"tokens,omitempty"`
	Logs            []string                  `json:"logs,omitempty"`
}

ServiceView is one service as the admin page shows it.

type Status

type Status struct {
	State     string    `json:"state"`
	Restarts  int       `json:"restarts"`
	StartedAt time.Time `json:"started_at,omitempty"`
	NextStart time.Time `json:"next_start,omitempty"`
	LastError string    `json:"last_error,omitempty"`
	// SleptAt is when auto-off last put the service to sleep.
	SleptAt time.Time `json:"slept_at,omitempty"`
	// LastActive is when a request or remote turn last touched it.
	LastActive time.Time `json:"last_active,omitempty"`
	// LastWakeMS is how long the last wake took, from the request that
	// woke it until the process was ready.
	LastWakeMS int64 `json:"last_wake_ms,omitempty"`
}

Status is what the admin page shows.

type Supervisor

type Supervisor struct {
	Logs *RingLog
	// contains filtered or unexported fields
}

Supervisor keeps one service plugin process running: spawn, push config, watch for exit, restart with backoff 1s→30s until Stop.

func (*Supervisor) Reconfigure

func (s *Supervisor) Reconfigure()

Reconfigure pushes the current config to the running process. A plugin that rejects the push is restarted so it boots with the new config. A stopped service picks the config up on its next start.

func (*Supervisor) Restart

func (s *Supervisor) Restart()

Restart stops and starts again, resetting the backoff.

func (*Supervisor) Start

func (s *Supervisor) Start()

Start begins supervising (no-op when already started; wakes a sleeping service).

func (*Supervisor) Status

func (s *Supervisor) Status() Status

Status returns the current status.

func (*Supervisor) Stop

func (s *Supervisor) Stop()

Stop terminates the process (SIGTERM, then SIGKILL after StopGrace), removes its socket and stops restarting it. It returns once the supervise loop is gone, so no spawn still in flight outlives it.

func (*Supervisor) Transport

func (s *Supervisor) Transport() (http.RoundTripper, error)

Transport returns the round tripper of the running process. A sleeping service is woken and the call waits (up to WakeTimeout) for it to boot; concurrent callers share that one boot. A service stopped by the admin or crashed is not woken.

type TokenView

type TokenView struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Hint      string    `json:"hint"`
	CreatedAt time.Time `json:"created_at"`
	LastUsed  time.Time `json:"last_used,omitempty"`
}

TokenView is an access token without its hash.

type Tokens

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

Tokens holds the access tokens (persisted, hashed) and the live callback tokens (in memory, one per running process) of every service plugin.

func NewTokens

func NewTokens(path string) *Tokens

NewTokens loads path ("" = memory only).

func (*Tokens) AutoOffSetting

func (t *Tokens) AutoOffSetting(key string) AutoOffSetting

AutoOffSetting returns the admin's auto-off setting of key (zero = follow the plugin with its idle limit).

func (*Tokens) CallbackRevoked

func (t *Tokens) CallbackRevoked(key string) bool

CallbackRevoked reports whether key's callback access is revoked.

func (*Tokens) Generate

func (t *Tokens) Generate(key, name string) (AccessToken, string, error)

Generate makes a new access token for key and returns its plaintext — the only time it is ever available.

func (*Tokens) GenerateBy added in v1.16.0

func (t *Tokens) GenerateBy(key, name, by string) (AccessToken, string, error)

GenerateBy is Generate recording the admin who made the token.

func (*Tokens) IssueCallback

func (t *Tokens) IssueCallback(key string, scopes []string) (string, bool)

IssueCallback makes the callback token for a new process of key (scoped to scopes), dropping the previous one. ok is false when the admin revoked key's callback access.

func (*Tokens) List

func (t *Tokens) List(key string) []AccessToken

List returns key's access tokens (hashes included; callers strip them).

func (*Tokens) LookupCallback

func (t *Tokens) LookupCallback(bearer string) (key string, scopes []string, ok bool)

LookupCallback resolves a callback bearer to its plugin and scopes.

func (*Tokens) Revoke

func (t *Tokens) Revoke(key, id string) error

Revoke deletes token id.

func (*Tokens) Rotate

func (t *Tokens) Rotate(key, id string) (AccessToken, string, error)

Rotate replaces token id's secret, keeping its name; the old secret stops working at once.

func (*Tokens) RotateBy added in v1.16.0

func (t *Tokens) RotateBy(key, id, by string) (AccessToken, string, error)

RotateBy is Rotate recording the admin who rotated it ("" keeps the previous owner).

func (*Tokens) SetAutoOffSetting

func (t *Tokens) SetAutoOffSetting(key string, v AutoOffSetting) error

SetAutoOffSetting stores key's auto-off setting; the zero value is dropped (back to the plugin default).

func (*Tokens) SetCallbackRevoked

func (t *Tokens) SetCallbackRevoked(key string, revoked bool) error

SetCallbackRevoked revokes (true) or re-allows key's callback token. A revoke takes effect immediately; re-allowing issues a token on the next (re)start.

func (*Tokens) Verify

func (t *Tokens) Verify(key, bearer string) bool

Verify reports whether bearer is a live access token of key.

func (*Tokens) VerifyOwner added in v1.16.0

func (t *Tokens) VerifyOwner(key, bearer string) (string, bool)

VerifyOwner is Verify that also returns who created the token ("" for a token made before owners were recorded).

type User

type User struct {
	ID, Email, Name string
	Admin           bool
}

User is the signed-in wick user of a request.

Directories

Path Synopsis
Package hostapi serves the plugin Host API (wick.host.v1): the calls a plugin makes back into wick.
Package hostapi serves the plugin Host API (wick.host.v1): the calls a plugin makes back into wick.
Package plugintest runs the real example_a2a_repeater service plugin under a service plugin Host for end-to-end tests outside internal/services/plugin.
Package plugintest runs the real example_a2a_repeater service plugin under a service plugin Host for end-to-end tests outside internal/services/plugin.

Jump to

Keyboard shortcuts

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