exec

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: AGPL-3.0 Imports: 36 Imported by: 2 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package exec manages plugin terminal sessions, multiplexed input and output, and bounded output history for reconnecting clients.

Index

Constants

View Source
const (
	// DefaultOutputBufferSize bounds retained output history in bytes per session.
	DefaultOutputBufferSize = 1000000
	// DefaultStreamBufferSize sets terminal read size and output channel capacity.
	DefaultStreamBufferSize = 4096
	// InitialRows sets PTY height before the first resize.
	InitialRows = 27
	// InitialCols sets PTY width before the first resize.
	InitialCols = 72
	// ResizeTimeout bounds delivery to handlers that manage their own resizing.
	ResizeTimeout = 500 * time.Millisecond
)
View Source
const ResourceSessionWireVersion = resourcev2.WireVersion

ResourceSessionWireVersion selects the reviewed canonical resource Value wire.

Variables

View Source
var (
	ErrSessionNotFound = &ExecSessionError{Code: ErrCodeSessionNotFound}
	ErrHandlerNotFound = &ExecSessionError{Code: ErrCodeHandlerNotFound}
	ErrSessionClosed   = &ExecSessionError{Code: ErrCodeSessionClosed}
	ErrTerminalError   = &ExecSessionError{Code: ErrCodeTerminalError}
	ErrSessionExists   = &ExecSessionError{Code: ErrCodeSessionExists}
)

Sentinel errors support classification with errors.Is.

Functions

func RegisterExecPluginServer added in v0.9.0

func RegisterExecPluginServer(registrar grpc.ServiceRegistrar, server execpb.ExecPluginServer)

RegisterExecPluginServer preserves generated handlers except resource admission.

func RegisterPlugin

func RegisterPlugin(
	p *sdk.Plugin,
	opts PluginOpts,
) error

RegisterPlugin installs an exec manager after rejecting duplicate handler keys.

func ValidateNativeCommand added in v0.12.0

func ValidateNativeCommand(command *NativeCommand) error

ValidateNativeCommand checks structured process fields using resource metadata bounds. It does not resolve executables, inspect local files, detect secrets, authorize a launch, or interpret shell syntax. Shell metacharacters stay literal.

func ValidateNativeCommandOptions added in v0.12.0

func ValidateNativeCommandOptions(opts SessionOptions) error

ValidateNativeCommandOptions requires an explicit canonical target and route, and applies the same metadata/body bounds as resource terminal requests.

func ValidateResourceSessionOptions added in v0.9.0

func ValidateResourceSessionOptions(o SessionOptions) error

ValidateResourceSessionOptions checks resource intent, selector consistency, canonical inputs, and metadata/body bounds without resolving a connection. Opaque selectors do not require a body, reference, or resource Get operation.

func ValidateSessionOptions added in v0.9.0

func ValidateSessionOptions(o SessionOptions) error

ValidateSessionOptions bounds and checks ordinary options and optional C01 inputs without resolving a connection or acquiring resource data.

Types

type ActionTargetBuilder

type ActionTargetBuilder struct {
	Label         string            `json:"label"`
	LabelSelector string            `json:"label_selector"`
	Paths         []string          `json:"paths"`
	Selectors     map[string]string `json:"selectors"`
}

ActionTargetBuilder builds a dynamic list of targets for an action.

func ActionTargetBuilderFromProto

func ActionTargetBuilderFromProto(p *commonpb.ActionTargetBuilder) ActionTargetBuilder

ActionTargetBuilderFromProto converts a proto ActionTargetBuilder to the domain type.

func (ActionTargetBuilder) ToProto

ToProto converts ActionTargetBuilder to its proto representation.

type ChannelSink

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

ChannelSink writes StreamOutput to a channel with context-aware sends. This is the production implementation used by Stream(). If the context is cancelled (e.g., gRPC stream closed), sends may be dropped instead of blocking forever on a full channel.

func NewChannelSink

func NewChannelSink(ctx context.Context, out chan<- StreamOutput) *ChannelSink

NewChannelSink creates a ChannelSink wrapping the given output channel. The context controls the lifetime — sends may be dropped after cancellation. If ctx is nil, context.Background is used. If out is nil, a buffered drop channel is created (output is silently discarded).

func (*ChannelSink) OnOutput

func (s *ChannelSink) OnOutput(output StreamOutput)

OnOutput sends output or drops it after cancellation; a nil receiver does nothing.

type CommandHandler

type CommandHandler func(
	ctx *types.PluginContext,
	opts SessionOptions,
) (stdout io.Reader, stderr io.Reader, err error)

CommandHandler is the expected signature for a non-TTY handler. It should immediately return its standard output and error readers.

type ErrorCode

type ErrorCode int

ErrorCode classifies exec errors for programmatic handling.

const (
	// ErrCodeSessionNotFound identifies an unknown session ID.
	ErrCodeSessionNotFound ErrorCode = iota + 1
	// ErrCodeHandlerNotFound identifies an unsupported handler key.
	ErrCodeHandlerNotFound
	// ErrCodeSessionClosed identifies a session that no longer accepts work.
	ErrCodeSessionClosed
	// ErrCodeTerminalError identifies a terminal operation failure.
	ErrCodeTerminalError
	// ErrCodeSessionExists identifies a duplicate session ID.
	ErrCodeSessionExists
)

func (ErrorCode) String

func (c ErrorCode) String() string

String returns the stable error classification, or UNKNOWN for an invalid code.

type ExecError

type ExecError struct {
	Err           error
	Title         string
	Message       string
	Suggestion    string
	Retryable     bool
	RetryCommands []string
}

ExecError is a structured error type that plugins use to provide classified exec errors with user-facing information.

func (*ExecError) Error

func (e *ExecError) Error() string

Error returns the wrapped failure's text; Err must be nonnil.

func (*ExecError) Unwrap

func (e *ExecError) Unwrap() error

Unwrap exposes the underlying failure for error classification.

type ExecSessionError

type ExecSessionError struct {
	Code      ErrorCode
	SessionID string
	Message   string
	Err       error // optional wrapped error
}

ExecSessionError is a structured error for exec operations.

func NewHandlerNotFoundError

func NewHandlerNotFoundError(handlerKey string, available []string) *ExecSessionError

NewHandlerNotFoundError reports the requested key and available handlers.

func NewSessionClosedError

func NewSessionClosedError(sessionID string) *ExecSessionError

NewSessionClosedError records a session that no longer accepts work.

func NewSessionExistsError

func NewSessionExistsError(sessionID string) *ExecSessionError

NewSessionExistsError reports an attempt to reuse a live session ID.

func NewSessionNotFoundError

func NewSessionNotFoundError(sessionID string) *ExecSessionError

NewSessionNotFoundError records the session ID that could not be found.

func NewTerminalError

func NewTerminalError(sessionID string, err error) *ExecSessionError

NewTerminalError wraps err while retaining the affected session ID.

func (*ExecSessionError) Error

func (e *ExecSessionError) Error() string

Error formats the classification and optional session ID; a nil receiver is safe.

func (*ExecSessionError) Is

func (e *ExecSessionError) Is(target error) bool

Is reports whether target matches this error's code.

func (*ExecSessionError) Unwrap

func (e *ExecSessionError) Unwrap() error

Unwrap returns the underlying failure, or nil for a nil receiver.

type Handler

type Handler struct {
	Plugin         string              `json:"plugin"`
	Resource       string              `json:"resource"`
	TargetBuilder  ActionTargetBuilder `json:"target_builder"`
	DefaultCommand []string            `json:"default_command"`
	TTYHandler     TTYHandlerFunc      `json:"-"`
	CommandHandler CommandHandler      `json:"-"`
	// NativeCommandHandler optionally plans a fresh process without a TTY callback.
	NativeCommandHandler NativeCommandHandler `json:"-"`
	// SupportsNativeCommand advertises planning support in remote metadata.
	// Local support is determined by NativeCommandHandler, not this flag.
	SupportsNativeCommand bool `json:"supports_native_command"`
	// HandlesResize: if true, resize events are sent through the channel
	// instead of via terminal.Resize().
	HandlesResize bool `json:"-"`
}

Handler handles running commands and creating sessions for a resource.

func HandlerFromProto

func HandlerFromProto(p *execpb.ExecHandler) Handler

HandlerFromProto decodes metadata only; nil yields a zero-value handler.

func (Handler) ID

func (h Handler) ID() string

ID returns the plugin/resource routing key.

func (Handler) String

func (h Handler) String() string

String returns the handler's routing key.

func (Handler) ToProto

func (h Handler) ToProto() *execpb.ExecHandler

ToProto exports handler metadata without serializing executable callbacks.

type Manager

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

Manager manages the lifecycle of terminal sessions within a plugin process.

func NewManager

func NewManager(cfg ManagerConfig) *Manager

NewManager creates a new Manager with the given config.

func (*Manager) AttachSession

func (m *Manager) AttachSession(
	pluginctx *types.PluginContext,
	sessionID string,
) (*Session, []byte, error)

AttachSession marks a session as attached and returns its current output buffer.

func (*Manager) BindConnectionContextProvider added in v0.9.0

func (m *Manager) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider binds resource utility admission to the active registry.

func (*Manager) Close

func (m *Manager) Close()

Close cancels all active sessions and waits for their goroutines to finish.

func (*Manager) CloseSession

func (m *Manager) CloseSession(pluginctx *types.PluginContext, sessionID string) error

CloseSession cancels the session's context, triggering cleanup.

func (*Manager) CreateResourceSession added in v0.9.0

func (m *Manager) CreateResourceSession(pluginctx *types.PluginContext, opts SessionOptions) (*Session, error)

CreateResourceSession admits resource inputs before invoking the shared terminal engine. The body is utility input, never an authorization grant.

func (*Manager) CreateSession

func (m *Manager) CreateSession(
	pluginctx *types.PluginContext,
	opts SessionOptions,
) (*Session, error)

CreateSession creates a new terminal session with a given command.

func (*Manager) DetachSession

func (m *Manager) DetachSession(pluginctx *types.PluginContext, sessionID string) (*Session, error)

DetachSession marks a session as not attached, stopping output broadcast.

func (*Manager) GetSession

func (m *Manager) GetSession(_ *types.PluginContext, sessionID string) (*Session, error)

GetSession returns a session by ID.

func (*Manager) GetSupportedResources

func (m *Manager) GetSupportedResources(_ *types.PluginContext) []Handler

GetSupportedResources returns registered terminal handlers.

func (*Manager) ListSessions

func (m *Manager) ListSessions(_ *types.PluginContext) ([]*Session, error)

ListSessions returns a list of details for all active sessions.

func (*Manager) PlanNativeCommand added in v0.12.0

func (m *Manager) PlanNativeCommand(pluginctx *types.PluginContext, opts SessionOptions) (*NativeCommand, error)

PlanNativeCommand revalidates explicit resource admission and plans a fresh shell/process without allocating a PTY or changing sessions. The connection lease ends on return. A plan is not a reusable authorization grant: callers must request it immediately before launch, and resource state can still change between planning and launch. The handler must verify authoritative identity.

func (*Manager) ResizeSession

func (m *Manager) ResizeSession(
	_ *types.PluginContext,
	sessionID string,
	rows, cols int32,
) error

ResizeSession resizes a session.

func (*Manager) Stream

func (m *Manager) Stream(ctx context.Context, in chan StreamInput) (chan StreamOutput, error)

Stream creates a new stream to multiplex sessions.

type ManagerConfig

type ManagerConfig struct {
	Logger          logging.Logger
	Settings        settings.Provider
	Handlers        map[string]Handler
	Sink            OutputSink      // nil → ChannelSink created by Stream()
	TerminalFactory TerminalFactory // nil → NewRealTerminalFactory()
	Clock           timeutil.Clock  // nil → timeutil.RealClock
}

ManagerConfig configures the Manager.

type NativeCommand added in v0.12.0

type NativeCommand struct {
	Executable string            `json:"executable"`
	Args       []string          `json:"args"`
	Env        map[string]string `json:"env"`
	Cwd        string            `json:"cwd"`
}

NativeCommand describes a fresh local process, not a running PTY or session. Executable is a program name or path. Args are literal arguments, never shell source. Env adds environment entries to inherited local credentials; Cwd is optional. Plans must not contain secrets, tokens, passwords, or embedded credentials, including in arguments and environment values. Only reusable local credential references or inherited authentication are supported.

type NativeCommandHandler added in v0.12.0

type NativeCommandHandler func(*types.PluginContext, SessionOptions) (*NativeCommand, error)

NativeCommandHandler plans a fresh process for an admitted resource. It must verify the authoritative resource identity/incarnation and reject unsupported authentication. ResourceData is input, not authorization. No existing terminal state, remote working directory, shell history, or session is transferred.

type NativeCommandProvider added in v0.12.0

type NativeCommandProvider interface {
	PlanNativeCommand(*types.PluginContext, SessionOptions) (*NativeCommand, error)
}

NativeCommandProvider is an optional planning capability. Existing Provider implementations need not implement it. Planning never launches a process.

type OutputBuffer

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

OutputBuffer stores terminal output bytes, providing a fixed-size cyclic buffer.

func NewDefaultOutputBuffer

func NewDefaultOutputBuffer() *OutputBuffer

NewDefaultOutputBuffer creates an OutputBuffer with DefaultOutputBufferSize.

func NewOutputBuffer

func NewOutputBuffer(capacity int) *OutputBuffer

NewOutputBuffer initializes an OutputBuffer with a specified capacity. If capacity is <= 0, a minimum capacity of 0 is used (all appends are discarded).

func (*OutputBuffer) Append

func (b *OutputBuffer) Append(data []byte)

Append adds data to the buffer, evicting the oldest bytes when capacity is exceeded. The backing array never grows beyond capacity to avoid retaining oversized memory.

func (*OutputBuffer) GetAll

func (b *OutputBuffer) GetAll() []byte

GetAll retrieves a copy of all stored bytes in the buffer.

func (*OutputBuffer) Len

func (b *OutputBuffer) Len() int

Len returns the current number of bytes in the buffer.

type OutputSink

type OutputSink interface {
	OnOutput(output StreamOutput)
}

OutputSink receives stream output from the Manager. Tests inject RecordingOutput; production uses ChannelSink.

type Plugin

type Plugin struct {
	plugin.Plugin

	Impl Provider
}

Plugin exposes a Provider through HashiCorp's gRPC plugin protocol.

func (*Plugin) BindConnectionContextProvider added in v0.9.0

func (p *Plugin) BindConnectionContextProvider(provider resourcev2.ConnectionContextProvider)

BindConnectionContextProvider forwards registry binding to the native provider.

func (*Plugin) GRPCClient

func (p *Plugin) GRPCClient(
	_ context.Context,
	_ *plugin.GRPCBroker,
	c *grpc.ClientConn,
) (any, error)

GRPCClient constructs the host-side exec provider using c.

func (*Plugin) GRPCServer

func (p *Plugin) GRPCServer(_ *plugin.GRPCBroker, s *grpc.Server) error

GRPCServer registers exec RPCs backed by Impl on s.

type PluginClient

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

PluginClient forwards exec operations to a remote plugin; the server owns sessions.

func (*PluginClient) AttachSession

func (c *PluginClient) AttachSession(
	ctx *types.PluginContext,
	sessionID string,
) (*Session, []byte, error)

AttachSession attaches remotely and returns the buffered output snapshot.

func (*PluginClient) Close

func (c *PluginClient) Close()

Close is a no-op on the client side — the server manages session lifecycle.

func (*PluginClient) CloseSession

func (c *PluginClient) CloseSession(ctx *types.PluginContext, sessionID string) error

CloseSession asks the server to terminate and release the session.

func (*PluginClient) CreateResourceSession added in v0.9.0

func (c *PluginClient) CreateResourceSession(ctx *types.PluginContext, opts SessionOptions) (*Session, error)

CreateResourceSession validates options and response admission without legacy fallback.

func (*PluginClient) CreateSession

func (c *PluginClient) CreateSession(
	ctx *types.PluginContext,
	opts SessionOptions,
) (*Session, error)

CreateSession routes resource-bearing options through the versioned resource RPC.

func (*PluginClient) DetachSession

func (c *PluginClient) DetachSession(
	ctx *types.PluginContext,
	sessionID string,
) (*Session, error)

DetachSession detaches remotely without closing the underlying session.

func (*PluginClient) GetSession

func (c *PluginClient) GetSession(
	ctx *types.PluginContext,
	sessionID string,
) (*Session, error)

GetSession fetches metadata for one remote session.

func (*PluginClient) GetSupportedResources

func (c *PluginClient) GetSupportedResources(ctx *types.PluginContext) []Handler

GetSupportedResources returns remote handler metadata, or nil if discovery fails.

func (*PluginClient) ListSessions

func (c *PluginClient) ListSessions(ctx *types.PluginContext) ([]*Session, error)

ListSessions fetches all remote session metadata.

func (*PluginClient) PlanNativeCommand added in v0.12.0

func (c *PluginClient) PlanNativeCommand(ctx *types.PluginContext, opts SessionOptions) (*NativeCommand, error)

PlanNativeCommand requests a fresh command plan without creating a session. The response is not an authorization grant for a later launch. Calls without a caller deadline have a 30-second timeout.

func (*PluginClient) ResizeSession

func (c *PluginClient) ResizeSession(
	ctx *types.PluginContext,
	sessionID string,
	rows, cols int32,
) error

ResizeSession forwards terminal dimensions for server-side validation.

func (*PluginClient) Stream

func (c *PluginClient) Stream(
	ctx context.Context,
	in chan StreamInput,
) (chan StreamOutput, error)

Stream multiplexes input and output until the RPC ends; the receiver closes output.

type PluginOpts

type PluginOpts struct {
	Handlers []Handler `json:"handlers"`
}

PluginOpts contains the options for the exec plugin.

type PluginServer

type PluginServer struct {
	execpb.UnimplementedExecPluginServer

	Impl Provider
	// contains filtered or unexported fields
}

PluginServer adapts a Provider to exec RPCs and validates resource admission.

func (*PluginServer) AttachSession

AttachSession attaches the session and returns its buffered output.

func (*PluginServer) CloseSession

CloseSession releases the session and maps provider failures to RPC status.

func (*PluginServer) CreateResourceSession added in v0.9.0

func (s *PluginServer) CreateResourceSession(
	ctx context.Context,
	in *execpb.SessionOptions,
) (*execpb.ResourceSessionResponse, error)

CreateResourceSession validates wire admission and the returned session binding.

func (*PluginServer) CreateSession

CreateSession accepts only ordinary sessions; resource intent requires the versioned RPC.

func (*PluginServer) DetachSession

DetachSession detaches the session without terminating it.

func (*PluginServer) GetSession

GetSession returns session metadata or a classified RPC error.

func (*PluginServer) GetSupportedResources

func (s *PluginServer) GetSupportedResources(
	ctx context.Context,
	_ *emptypb.Empty,
) (*execpb.GetSupportedResourcesResponse, error)

GetSupportedResources encodes supported handler metadata without callbacks.

func (*PluginServer) ListSessions

func (s *PluginServer) ListSessions(
	ctx context.Context,
	in *emptypb.Empty,
) (*execpb.ListSessionsResponse, error)

ListSessions returns snapshots of the provider's current sessions.

func (*PluginServer) PlanNativeCommand added in v0.12.0

PlanNativeCommand validates resource admission and returns a plan, never a session.

func (*PluginServer) ResizeSession

ResizeSession forwards dimensions to the provider for terminal validation.

func (*PluginServer) Stream

Stream multiplexes session input and output for the lifetime of the RPC.

type Provider

type Provider interface {
	// GetSupportedResources returns the supported resource types
	GetSupportedResources(ctx *types.PluginContext) []Handler
	// GetSession returns a session by ID
	GetSession(ctx *types.PluginContext, sessionID string) (*Session, error)
	// ListSessions returns all of the sessions
	ListSessions(ctx *types.PluginContext) ([]*Session, error)
	// CreateSession creates a new session
	CreateSession(ctx *types.PluginContext, opts SessionOptions) (*Session, error)
	// AttachSession attaches a session
	AttachSession(ctx *types.PluginContext, sessionID string) (*Session, []byte, error)
	// DetachSession detaches a session
	DetachSession(ctx *types.PluginContext, sessionID string) (*Session, error)
	// CloseSession closes a session
	CloseSession(ctx *types.PluginContext, sessionID string) error
	// ResizeSession resizes a session
	ResizeSession(ctx *types.PluginContext, sessionID string, rows, cols int32) error
	// Stream starts a new stream to multiplex sessions
	Stream(context.Context, chan StreamInput) (chan StreamOutput, error)
	// Close shuts down the provider, releasing all resources.
	Close()
}

Provider is the interface satisfied by the plugin server and client to provide the exec functionality.

type ResourceSessionProvider added in v0.9.0

type ResourceSessionProvider interface {
	CreateResourceSession(*types.PluginContext, SessionOptions) (*Session, error)
}

ResourceSessionProvider adds explicit resource-scoped creation while reusing ordinary exec session IDs and attach/output/resize/close lifecycle. The body and opaque utility selectors are input, never authorization. Existing routing does not require a resource Get grant or an invented canonical reference.

type Session

type Session struct {
	CreatedAt time.Time         `json:"created_at"`
	Labels    map[string]string `json:"labels"`
	Params    map[string]string `json:"params"`
	ID        string            `json:"id"`
	Command   []string          `json:"command"`
	Attached  bool              `json:"attached"`
}

Session is a snapshot of public terminal-session metadata, not a live view. Manager snapshots own their maps and command slice. Callers may read a snapshot concurrently, but must synchronize mutations to those containers.

func NewSessionFromProto

func NewSessionFromProto(s *execpb.Session) *Session

NewSessionFromProto converts public session metadata and returns nil for nil input. Command, Labels, and Params share the input message's containers; the result does not own or control the lifetime of a running terminal session.

func (*Session) ToProto

func (s *Session) ToProto() *execpb.Session

ToProto converts session metadata without changing session lifetime or state. A nil receiver returns nil. The result shares Command, Labels, and Params with the snapshot; callers must synchronize mutations while either value is in use.

type SessionHandler

type SessionHandler func(
	ctx *types.PluginContext,
	opts SessionOptions,
) (stdin io.Writer, stdout io.Reader, stderr io.Reader, err error)

SessionHandler is the expected signature for a function that creates a new session, returning the standard input, output, and error streams which will be multiplexed to the client.

type SessionOptions

type SessionOptions struct {
	Params         map[string]string             `json:"params"`
	Labels         map[string]string             `json:"labels"`
	ID             string                        `json:"id"`
	ResourcePlugin string                        `json:"resource_plugin"`
	ResourceKey    string                        `json:"resource_key"`
	ResourceData   *resourcev2.Value             `json:"resource_data,omitempty"`
	Reference      *resourcev2.ResourceReference `json:"reference,omitempty"`
	Route          *resourcev2.AccessRoute       `json:"route,omitempty"`
	Command        []string                      `json:"command"`
	TTY            bool                          `json:"tty"`
}

SessionOptions describes a terminal session and optional resource intent. ResourcePlugin and ResourceKey are opaque selectors, not authorization. ResourceData, when present, must be a canonical tagged map; scalar types remain exact through JSON and protobuf conversion. A Reference requires an explicit Route and must agree with any supplied selectors. Neither selectors nor a reference require a body or an unrelated resource Get operation.

Validation and normalization do not acquire a connection or copy mutable containers. Callers must not mutate options concurrently with SDK use.

func NewSessionOptionsFromProto

func NewSessionOptionsFromProto(p *execpb.SessionOptions) (*SessionOptions, error)

NewSessionOptionsFromProto has no Struct or float64 fallback. Resource intent selects wire version two before body conversion; old nonresource options keep their ordinary terminal path. Nil input and invalid or oversized messages fail. Optional references, routes, and tagged bodies retain presence and are decoded into new domain values; Command, Params, and Labels share the input containers.

func NormalizeResourceSessionOptions added in v0.9.0

func NormalizeResourceSessionOptions(o SessionOptions) (SessionOptions, error)

NormalizeResourceSessionOptions derives only redundant opaque selectors from an actual supplied reference. It never invents a reference, route, authority, body, native scope, or a Get permission requirement.

func (SessionOptions) HasResourceIntent added in v0.9.0

func (o SessionOptions) HasResourceIntent() bool

HasResourceIntent prevents resource requests from falling back to an older terminal method, including selectors without a body and optional C01 inputs.

func (*SessionOptions) ToProto

func (o *SessionOptions) ToProto() (*execpb.SessionOptions, error)

ToProto validates options and encodes resource intent with the current wire version, preserving tagged scalar types and optional reference/route presence. It rejects nil options and oversized frames before allocating a protobuf body. Command, Params, and Labels remain shared with the caller; do not mutate them concurrently with serialization or use of the returned message.

func (*SessionOptions) UnmarshalJSON added in v0.9.0

func (o *SessionOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON validates raw evidence before ordinary decoding can erase duplicates or replace malformed Unicode. The explicit field switch also rejects case-folded aliases; opaque selector and identifier values are data. Tagged scalar types and explicit optional-field presence survive decoding. A decoding or validation error leaves the receiver unchanged.

type SessionResizeInput

type SessionResizeInput struct {
	Rows int32 `json:"rows"`
	Cols int32 `json:"cols"`
}

SessionResizeInput carries resize dimensions for a session.

type StreamError

type StreamError struct {
	Title         string   `json:"title"`
	Message       string   `json:"message"`
	Suggestion    string   `json:"suggestion"`
	Retryable     bool     `json:"retryable"`
	RetryCommands []string `json:"retry_commands,omitempty"`
}

StreamError contains structured error information from a failed exec session.

func NewStreamErrorFromProto

func NewStreamErrorFromProto(p *execpb.StreamError) *StreamError

NewStreamErrorFromProto decodes an error, preserving nil and sharing retry commands.

func (*StreamError) ToProto

func (e *StreamError) ToProto() *execpb.StreamError

ToProto encodes the error, preserving nil and sharing RetryCommands storage.

type StreamInput

type StreamInput struct {
	// SessionID
	SessionID string `json:"session_id"`
	// Data
	Data []byte `json:"data"`
}

StreamInput carries bytes to write to a session's terminal.

func NewStreamInputFromProto

func NewStreamInputFromProto(p *execpb.StreamInput) StreamInput

NewStreamInputFromProto decodes input, sharing Data; nil yields the zero value.

func (*StreamInput) ToProto

func (i *StreamInput) ToProto() *execpb.StreamInput

ToProto encodes input, sharing Data storage; nil yields an empty message.

type StreamOutput

type StreamOutput struct {
	SessionID string       `json:"session_id"`
	Data      []byte       `json:"data"`
	Target    StreamTarget `json:"target"`
	Signal    StreamSignal `json:"signal"`
	Error     *StreamError `json:"error,omitempty"`
	Seq       uint64       `json:"seq"`
}

StreamOutput carries session data or a lifecycle event and its output sequence.

func NewStreamOutputFromProto

func NewStreamOutputFromProto(p *execpb.StreamOutput) StreamOutput

NewStreamOutputFromProto decodes output, sharing Data; nil yields the zero value.

func (*StreamOutput) ToProto

func (o *StreamOutput) ToProto() *execpb.StreamOutput

ToProto encodes output, sharing Data storage; nil yields an empty message.

type StreamResize

type StreamResize struct {
	SessionID string `json:"session_id"`
	Cols      uint16 `json:"cols"`
	Rows      uint16 `json:"rows"`
}

StreamResize requests nonzero terminal dimensions measured in characters.

func NewStreamResizeFromProto

func NewStreamResizeFromProto(p *execpb.ResizeSessionRequest) (StreamResize, error)

NewStreamResizeFromProto rejects nil requests and dimensions outside 1..65535.

func (*StreamResize) ToProto

ToProto encodes dimensions; nil yields an empty request.

type StreamSignal

type StreamSignal int

StreamSignal identifies process signals and stream lifecycle notifications.

const (
	// StreamSignalNone carries data without a signal.
	StreamSignalNone StreamSignal = iota
	// StreamSignalClose marks stream closure rather than a process signal.
	StreamSignalClose
	// StreamSignalSigint requests interrupt.
	StreamSignalSigint
	// StreamSignalSigquit requests quit.
	StreamSignalSigquit
	// StreamSignalSigterm requests termination.
	StreamSignalSigterm
	// StreamSignalSigkill requests immediate termination.
	StreamSignalSigkill
	// StreamSignalSighup requests hangup.
	StreamSignalSighup
	// StreamSignalSigusr1 carries the first user-defined signal.
	StreamSignalSigusr1
	// StreamSignalSigusr2 carries the second user-defined signal.
	StreamSignalSigusr2
	// StreamSignalSigwinch reports a terminal size change.
	StreamSignalSigwinch
	// StreamSignalError marks a structured session failure.
	StreamSignalError
)

func NewStreamSignalFromProto

func NewStreamSignalFromProto(p execpb.StreamSignal) StreamSignal

NewStreamSignalFromProto decodes a wire signal, treating unknown values as none.

func (StreamSignal) String

func (s StreamSignal) String() string

String returns the signal name, defaulting to NONE for unknown values.

func (StreamSignal) ToProto

func (s StreamSignal) ToProto() execpb.StreamSignal

ToProto converts a StreamSignal value to its proto representation.

type StreamTarget

type StreamTarget int

StreamTarget identifies which process output channel carries a chunk.

const (
	// StreamTargetStdOut selects standard output and is the zero value.
	StreamTargetStdOut StreamTarget = iota
	// StreamTargetStdErr selects standard error.
	StreamTargetStdErr
)

func (StreamTarget) String

func (t StreamTarget) String() string

String returns the channel name, or unknown for an invalid target.

type TTYHandlerFunc

type TTYHandlerFunc func(
	ctx *types.PluginContext,
	opts SessionOptions,
	tty *os.File,
	stopCh chan error,
	resize <-chan SessionResizeInput,
) error

TTYHandlerFunc is the expected signature for a function that creates a new session with a TTY. It is passed the TTY file descriptor, a stop channel for signalling errors, and a receive-only resize channel.

The manager closes tty when the session ends, which interrupts a pending Read or Write on it. Calling tty.Fd() switches the TTY to blocking mode; after that, the close waits for a pending Read to return.

Renamed from TTYHandler to avoid confusion with the Handler struct.

type Terminal

type Terminal interface {
	// MasterFd returns the PTY (master) side — the manager reads output from here.
	MasterFd() *os.File
	// SlaveFd returns the TTY (slave) side — passed to the handler.
	SlaveFd() *os.File
	// Resize sets the terminal dimensions.
	Resize(rows, cols uint16) error
	// Close releases both file descriptors.
	Close() error
}

Terminal abstracts a PTY/TTY pair so tests can inject fakes.

type TerminalFactory

type TerminalFactory func() (Terminal, error)

TerminalFactory creates a new Terminal. The default factory opens a real PTY via creack/pty. Tests inject a factory that returns FakeTerminal.

func NewRealTerminalFactory

func NewRealTerminalFactory() TerminalFactory

NewRealTerminalFactory returns a TerminalFactory that creates real PTY terminals. The slave is set to raw mode and the terminal is sized to the given initial dimensions.

Directories

Path Synopsis
Package exectest exercises exec managers with pipe-backed terminals and synchronized output recording.
Package exectest exercises exec managers with pipe-backed terminals and synchronized output recording.

Jump to

Keyboard shortcuts

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