pluginhost

package
v4.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package pluginhost supervises local Control package processes. Package requests enter only after the kernel has completed admission and routing.

Index

Constants

View Source
const (
	HostStateRunning    = "running"
	HostStateRestarting = "restarting"
	HostStateFailed     = "failed"
	HostStateExited     = "exited"
	HostStateStopped    = "stopped"
)

Host supervision states reported by HostStats.State.

View Source
const (
	DefaultRemoteBindTimeout = 2 * time.Minute
)

Remote runtime defaults.

Variables

View Source
var (
	ErrHostUnavailable       = errors.New("plugin host unavailable")
	ErrHostNotFound          = errors.New("plugin host not found")
	ErrHostIncompatible      = errors.New("plugin host incompatible")
	ErrPackageFailed         = errors.New("plugin package failed")
	ErrGenerationUnavailable = errors.New("plugin host generation unavailable")
)
View Source
var ErrLegacyUnavailable = errors.New("plugin route has no kernel legacy handler")

ErrLegacyUnavailable reports that the kernel cannot serve a request with its legacy handler without the package host: the route has no legacy bridge operation.

View Source
var ErrResponseTooLarge = errors.New("plugin response exceeds its limit")

ErrResponseTooLarge reports a package response above the configured response limit (codes.ResourceExhausted from the host, or a host message the kernel client refused to receive). It is always wrapped together with ErrHostUnavailable so existing callers keep failing closed.

Functions

func BridgeRequest added in v4.1.0

func BridgeRequest(input DispatchInput) (packagebridge.Request, error)

BridgeRequest is the request state a dispatch's bridge capability retains: the body as the client sent it (BridgeBody, when the host reads one with sealed secrets), the principal, the kernel-side metadata and the sealed request.

func SetDefaultManager

func SetDefaultManager(manager Manager)

SetDefaultManager installs the process-wide supervisor used by HTTP route handlers. A nil value deliberately leaves route dispatch fail-closed.

Types

type ArtifactRef

type ArtifactRef struct {
	PackageID        string
	Version          string
	ArtifactPath     string
	ArtifactSHA256   string
	EntrypointPath   string
	EntrypointSHA256 string
	ManifestPath     string
	ManifestSHA256   string
	// MigrationIndexSHA256 and Migrations describe the verified migration
	// index of the release; Migrations is empty when it declares no steps.
	MigrationIndexSHA256 string
	Migrations           []MigrationStep
	// Storage is set when the signed manifest declares kernel.storage.v1.
	// Only such releases run their migration index through the kernel's
	// migration ledger when the host starts.
	Storage bool
}

ArtifactRef describes files materialized by a caller that has already bound them to a signed package release. The manager verifies every supplied digest again immediately before starting the entrypoint.

type DispatchInput

type DispatchInput struct {
	PackageID        string
	Version          string
	Generation       uint64
	RequestID        string
	IdempotencyKey   string
	RouteID          string
	Method           string
	Body             []byte
	PrincipalJSON    []byte
	Metadata         RequestMetadata
	BridgeCapability []byte
	Deadline         time.Time
	// BridgeBody is the body the bridge capability retains for the
	// kernel's legacy handler when the host reads another one: the request
	// as the client sent it, while Body has its node secrets sealed. Nil
	// retains Body.
	BridgeBody []byte
	// SealedRequest names the request's sealed secrets; the capability
	// carries it so that KernelNodeOps resolves them for this request only.
	SealedRequest string
}

type DispatchOutput

type DispatchOutput struct {
	StatusCode  uint32
	Body        []byte
	Headers     []Header
	OperationID string
	FailureCode string
}

type DrainResult

type DrainResult struct {
	Drained  bool
	InFlight uint64
}
type Header struct {
	Name  string
	Value string
}

type HostHealth

type HostHealth struct {
	Healthy     bool
	LeaseID     string
	DetailsJSON string
}

type HostStats added in v4.1.0

type HostStats struct {
	PackageID  string
	Version    string
	Generation uint64
	// State is one of the HostState* constants.
	State string
	// Starts counts host processes that became healthy, explicit and
	// watchdog starts alike.
	Starts uint64
	// UnexpectedExits counts host exits not caused by Drain, Stop,
	// replacement, or Shutdown.
	UnexpectedExits uint64
	// Restarts counts watchdog restart attempts, successful or not.
	Restarts uint64
	// Failures counts how often the restart budget was exhausted and the
	// host was marked failed.
	Failures uint64
	// HealthDetailsJSON is the details document of the host's last successful
	// Health call made by PollHealth, and HealthCheckedAt its time.
	HealthDetailsJSON string
	HealthCheckedAt   time.Time
}

HostStats is a read-only snapshot of one package's host supervision counters since the supervisor was created.

type HostStatsProvider added in v4.1.0

type HostStatsProvider interface {
	Stats() []HostStats
}

HostStatsProvider is implemented by supervisors that expose per-package host counters, for example to a metrics endpoint.

type ManagerConfig

type ManagerConfig struct {
	RuntimeDir     string
	StartupTimeout time.Duration
	BridgeFactory  packagebridge.SessionFactory
	// MaxResponseBytes is plugins.control_host_max_response_bytes. It is
	// passed to hosts as ANIX_CONTROL_HOST_MAX_RESPONSE_BYTES and bounds the
	// kernel client's receive size. Zero selects the 1 MiB default.
	MaxResponseBytes int64
	// PackageEnvironment adds "NAME=value" entries to one package's local
	// host environment, for secrets that package alone needs (the identity
	// key-encryption key). Hosts otherwise inherit nothing from the kernel.
	PackageEnvironment map[string][]string
}

type MigrationCheckpointRecorder

type MigrationCheckpointRecorder func(context.Context, MigrationOutput) error

MigrationCheckpointRecorder must durably persist each host reply before the migration caller can observe it. A nil recorder is rejected fail-closed.

type MigrationInput

type MigrationInput struct {
	PackageID   string
	Version     string
	MigrationID string
	Checkpoint  string
	Generation  uint64
	// BridgeCapability is minted only by Supervisor and is never caller-owned.
	BridgeCapability []byte
	Deadline         time.Time
}

MigrationInput is passed through to the verified package host. Checkpoint and migration identifier values are package-owned opaque strings.

type MigrationManager

type MigrationManager interface {
	Migrate(context.Context, MigrationInput, MigrationCheckpointRecorder) (MigrationOutput, error)
}

MigrationManager is intentionally separate from Manager so existing route dispatch consumers do not gain a migration capability by accident.

type MigrationOutput

type MigrationOutput struct {
	Checkpoint       string
	ValidationDigest string
	Complete         bool
	FailureCode      string
	HealthLeaseID    string
	HealthGeneration uint64
}

MigrationOutput is the opaque reply returned by a package host. The kernel only persists and fences these values; it does not interpret their domain meaning.

type MigrationStep added in v4.1.0

type MigrationStep struct {
	ID     string
	Path   string
	SHA256 string
}

MigrationStep is one verified step of a package migration index.

type RemoteConfig added in v4.1.0

type RemoteConfig struct {
	Instances RemoteInstances
	// TLS is the kernel's client identity for dialing modules.
	TLS     moduletls.Source
	Cluster string
	// IsRemote reports whether a package's installation runs remotely.
	IsRemote func(ctx context.Context, packageID string) (bool, error)
	// BindTimeout bounds how long Start waits for a healthy instance.
	BindTimeout time.Duration
}

RemoteConfig enables the remote runtime of a Supervisor.

type RemoteInstances added in v4.1.0

type RemoteInstances interface {
	Instances(packageID string, generation uint64) []packagebridge.BoundInstance
}

RemoteInstances lists the module instances bound to a generation; the kernel's packagebridge.ModuleBridge implements it.

type RequestMetadata

type RequestMetadata struct {
	Path                             string              `json:"path,omitempty"`
	Query                            map[string][]string `json:"query,omitempty"`
	Headers                          map[string][]string `json:"headers,omitempty"`
	PathParams                       map[string]string   `json:"path_params,omitempty"`
	ClientIP                         string              `json:"client_ip,omitempty"`
	UserAgent                        string              `json:"user_agent,omitempty"`
	NodeID                           uint                `json:"node_id,omitempty"`
	TrustedAgentWebSocketAuth        bool                `json:"trusted_agent_websocket_auth,omitempty"`
	TrustedAgentWebSocketForwardNode bool                `json:"trusted_agent_websocket_forward_node,omitempty"`
	// Host and TLS describe the original request address as
	// internal/requestorigin resolves it: the Host header and whether the
	// connection was TLS, or X-Forwarded-Host/Proto when the peer is a
	// trusted reverse proxy (server.trusted_proxies). Host is kept only when
	// it is a plain host[:port] (validPackageRequestHost). They are never request metadata JSON
	// keys, because hosts built with the v4.0.0 SDK reject unknown keys. The
	// kernel's bridge snapshot carries them as "host" and "tls", and package
	// hosts receive them as the DispatchRequest and WebSocketOpen fields
	// request_host and request_scheme, which older hosts skip.
	Host string `json:"-"`
	TLS  bool   `json:"-"`
}

RequestMetadata preserves the request address independently from the package route identifier. Query values remain multi-valued because v2 clients may repeat a key.

type Supervisor

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

func NewManager

func NewManager(config ManagerConfig) (*Supervisor, error)

func (*Supervisor) BindInstance added in v4.1.0

BindInstance admits a remote instance to the generation it may serve: a starting generation of its version, or the active one. It implements packagebridge.Binder.

func (*Supervisor) Close

func (m *Supervisor) Close() error

Close retires every host and releases the pinned runtime-root descriptor.

func (*Supervisor) Dispatch

func (m *Supervisor) Dispatch(ctx context.Context, input DispatchInput) (DispatchOutput, error)

func (*Supervisor) DispatchLegacy added in v4.1.0

func (m *Supervisor) DispatchLegacy(ctx context.Context, input DispatchInput) (DispatchOutput, error)

DispatchLegacy serves a request with the kernel's legacy handler for its route, as the host's legacy mode would relay it, without the package host: the v2 gateway's fail-closed path when a request's node secrets cannot be sealed (node-ops-service.md section 3.7). The host's current generation must be the request's.

func (*Supervisor) Drain

func (m *Supervisor) Drain(ctx context.Context, packageID, version string, generation uint64, deadline time.Time) error

func (*Supervisor) EnableRemote added in v4.1.0

func (m *Supervisor) EnableRemote(config RemoteConfig) error

EnableRemote turns on the remote runtime. It must be called before the first Start of a remote package.

func (*Supervisor) Health

func (m *Supervisor) Health(ctx context.Context, packageID, version string, generation uint64) (HostHealth, error)

func (*Supervisor) Migrate

Migrate forwards one resumable migration step to the active host, persists its reply through recorder, and treats a completed response as activation only after the host health lease still matches the requested generation.

func (*Supervisor) OpenWebSocket

func (m *Supervisor) OpenWebSocket(ctx context.Context, input WebSocketInput) (*WebSocketRelay, error)

func (*Supervisor) PackageConn added in v4.1.0

func (m *Supervisor) PackageConn(packageID string) (grpc.ClientConnInterface, error)

PackageConn returns a connection to the running host of packageID, for the contracts a package serves beside the host protocol (such as IdentityService). A remote package yields one of its bound instances. Callers must not keep it: restarts and rebinds replace connections.

func (*Supervisor) PollHealth added in v4.1.0

func (m *Supervisor) PollHealth(ctx context.Context, interval time.Duration)

PollHealth calls Health on every running host each interval until ctx ends and records the returned details document in the host's stats, so metrics and diagnostics can read route modes and shadow counters. A failed call leaves the previous details in place.

func (*Supervisor) Rollback

func (m *Supervisor) Rollback(ctx context.Context, packageID, version string, generation uint64) error

func (*Supervisor) Shutdown

func (m *Supervisor) Shutdown(ctx context.Context) error

func (*Supervisor) Start

func (m *Supervisor) Start(ctx context.Context, ref ArtifactRef, generation uint64) error

func (*Supervisor) Stats added in v4.1.0

func (m *Supervisor) Stats() []HostStats

Stats returns a snapshot of every package's supervision counters, sorted by package ID. It never waits for a lifecycle operation.

func (*Supervisor) Stop

func (m *Supervisor) Stop(ctx context.Context, packageID, version string, generation uint64) error

type WebSocketClose

type WebSocketClose struct {
	Code   uint32
	Reason string
}

type WebSocketFrame

type WebSocketFrame struct {
	Data  []byte
	Close *WebSocketClose
}

WebSocketFrame is a post-open relay frame. A nil Close represents a data frame, including an empty opaque payload.

type WebSocketInput

type WebSocketInput struct {
	PackageID        string
	Version          string
	Generation       uint64
	RouteID          string
	PrincipalJSON    []byte
	Metadata         RequestMetadata
	RequestID        string
	IdempotencyKey   string
	BridgeCapability []byte
	Deadline         time.Time
}

type WebSocketManager

type WebSocketManager interface {
	OpenWebSocket(context.Context, WebSocketInput) (*WebSocketRelay, error)
}

WebSocketManager is separate from unary route dispatch so callers must consciously opt into the bidirectional package-host transport.

type WebSocketRelay

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

WebSocketRelay owns one verified package-host stream. Callers may make one Send and one Recv call concurrently; concurrent writes are serialized.

func (*WebSocketRelay) Close

func (r *WebSocketRelay) Close(close WebSocketClose) error

func (*WebSocketRelay) Recv

func (r *WebSocketRelay) Recv() (WebSocketFrame, error)

func (*WebSocketRelay) Send

func (r *WebSocketRelay) Send(frame WebSocketFrame) error

Jump to

Keyboard shortcuts

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