emulator

package
v1.3.25 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 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 emulator implements a small, deterministic, stateful CLI emulator. It models terminal interactions, not a switch data or control plane.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClosed       = errors.New("emulator closed")
	ErrNotReady     = errors.New("device login service not ready")
	ErrConsoleBusy  = errors.New("console already attached")
	ErrSlowConsumer = errors.New("terminal output queue full")
	ErrReboot       = errors.New("device rebooted")
)

Functions

This section is empty.

Types

type Action

type Action struct {
	Op      string            `yaml:"op"`
	Mode    string            `yaml:"mode"`
	Context map[string]string `yaml:"context"`
	Path    []string          `yaml:"path"`
	Value   any               `yaml:"value"`
	Text    string            `yaml:"text"`
	Config  string            `yaml:"config"`
	Prefix  string            `yaml:"prefix"`
	Suffix  string            `yaml:"suffix"`
	File    string            `yaml:"file"`
	After   time.Duration     `yaml:"after"`
	Dialog  string            `yaml:"dialog"`
	Name    string            `yaml:"name"`
}

Action is deliberately a closed set of operations, not arbitrary Go or shell code. Strings in text, path, context and value may use Go text/template expressions.

type Answer

type Answer struct {
	Input   string   `yaml:"input"`
	Actions []Action `yaml:"actions"`
}

type ArgumentCompletion

type ArgumentCompletion struct {
	StatePath   []string `yaml:"statePath"`
	Prefix      string   `yaml:"prefix"`
	StripPrefix bool     `yaml:"stripPrefix"`
}

ArgumentCompletion supplies advisory values for a word argument. StatePath selects a configuration map whose keys are offered; it never validates or changes the argument. Values are resolved for each query, not cached globally.

type ArgumentSpec

type ArgumentSpec struct {
	Enum      []string `yaml:"enum"`
	MinValue  *uint32  `yaml:"minValue"`
	MaxValue  *uint32  `yaml:"maxValue"`
	Hint      string   `yaml:"hint"`
	MinLength int      `yaml:"minLength"`
	MaxLength int      `yaml:"maxLength"`
}

ArgumentSpec customizes hints and constraints for named typed arguments. Hint is display-only; word lengths count code points, numeric bounds are uint32. The terminal input editor remains ASCII-only.

type AttachOptions

type AttachOptions struct {
	// Console names a persistent line. Empty means a new management session.
	Console       string
	Columns, Rows int
	// Authenticated is set only by a transport which has authenticated Username.
	// Console access always uses its own login, independent of transport auth.
	Authenticated bool
	Username      string
}

type Command

type Command struct {
	Abbreviations *bool                         `yaml:"abbreviations"`
	Arguments     map[string]ArgumentSpec       `yaml:"arguments"`
	Completions   map[string]ArgumentCompletion `yaml:"completions"`
	Help          []string                      `yaml:"help"`
	ID            string                        `yaml:"id"`
	Modes         []string                      `yaml:"modes"`
	Syntax        string                        `yaml:"syntax"`
	Actions       []Action                      `yaml:"actions"`
}

type Completion

type Completion struct {
	Line       string
	Candidates []string
}

Completion describes pure token completion, never command execution. Line is the edited buffer. Candidates contains sorted keywords and display-only argument/<cr> hints. Declared state-backed argument values are also insertable.

type ConfigurationSection

type ConfigurationSection struct {
	ID       string                 `yaml:"id"`
	Path     []string               `yaml:"path"`
	Each     bool                   `yaml:"each"`
	Header   string                 `yaml:"header"`
	Lines    []string               `yaml:"lines"`
	Footer   string                 `yaml:"footer"`
	Children []ConfigurationSection `yaml:"children"`
}

ConfigurationSection describes a subtree, independent of the command displaying it. Path is relative to the parent value. Each enumerates a map in sorted key order. Templates receive Config (whole tree), Value, Key and Keys (ancestor selections).

type Definition

type Definition struct {
	Configuration *ConfigurationSection `yaml:"configuration"`
	Validation    *Validation           `yaml:"validation"`
	APIVersion    string                `yaml:"apiVersion"`
	Name          string                `yaml:"name"`
	InitialMode   string                `yaml:"initialMode"`
	InitialState  map[string]any        `yaml:"initialState"`
	Abbreviations bool                  `yaml:"abbreviations"`
	Modes         map[string]Mode       `yaml:"modes"`
	Commands      []Command             `yaml:"commands"`
	Dialogs       map[string]Dialog     `yaml:"dialogs"`
	Terminal      Terminal              `yaml:"terminal"`
	Login         Login                 `yaml:"login"`
	Boot          []Event               `yaml:"boot"`
	Errors        map[string]string     `yaml:"errors"`
}

Definition is the versioned source format. LoadProfile validates and compiles it.

type Device

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

Device serializes all state transitions under one lock. No transition does network I/O or waits for a consumer. Manual Advance and Run are exclusive.

func New

func New(profile *Profile, options Options) (*Device, error)

func (*Device) Advance

func (d *Device) Advance(delta time.Duration) error

Advance runs scheduled events in timestamp/sequence order without sleeping.

func (*Device) Attach

func (d *Device) Attach(o AttachOptions) (*Session, error)

func (*Device) Close

func (d *Device) Close() error

func (*Device) ControlHandler

func (d *Device) ControlHandler(token string) (http.Handler, error)

ControlHandler exposes a test-only API. Tokens are never recorded in trace. The caller must serve it on loopback; ServeControl enforces that restriction.

func (*Device) Inject

func (d *Device) Inject(e Event) error

Inject emits a validated event immediately. It is useful as a test control API.

func (*Device) Reboot

func (d *Device) Reboot() error

func (*Device) Run

func (d *Device) Run(ctx context.Context) error

Run drives logical time using a 5 ms wall-clock tick. It does not accelerate the clocks or deadlines of external clients. Cancel does not close Device.

func (*Device) Serve

func (d *Device) Serve(ctx context.Context, stream io.ReadWriteCloser, options AttachOptions) error

Serve attaches a byte-stream transport. Exactly one goroutine writes stream. Closing stream must unblock both Read and Write, as net.Conn/ssh.Channel do.

func (*Device) ServeConsole

func (d *Device) ServeConsole(ctx context.Context, listener net.Listener, name string) error

ServeConsole exposes one persistent console over raw TCP, not Telnet/RFC2217. Only one attachment can own this line at a time. No old output is replayed.

func (*Device) ServeControl

func (d *Device) ServeControl(ctx context.Context, listener net.Listener, token string) error

ServeControl serves only on a TCP loopback listener, disabled unless explicitly enabled.

func (*Device) SetEventOutput

func (d *Device) SetEventOutput(enabled bool) error

SetEventOutput controls asynchronous raw/log events, not command output or readiness.

func (*Device) Snapshot

func (d *Device) Snapshot() Snapshot

func (*Device) Trace

func (d *Device) Trace() []Trace

type Dialog

type Dialog struct {
	Prompt  string   `yaml:"prompt"`
	Secret  bool     `yaml:"secret"`
	Answers []Answer `yaml:"answers"`
}

type Event

type Event struct {
	At     time.Duration `yaml:"at"`
	Kind   string        `yaml:"kind"`
	Text   string        `yaml:"text"`
	File   string        `yaml:"file"`
	Source string        `yaml:"source"`
	Route  string        `yaml:"route"`
	Policy string        `yaml:"policy"`
}

Event times are relative to device boot, never to attachment or login. raw events deliver exact fixture bytes; log events use terminal log policy.

type HelpEntry

type HelpEntry struct {
	Token       string
	Description string
	Kind        string
}

HelpEntry describes exactly one immediate grammar child, never a full path. Kind is "keyword", "value", "argument", or "end" (the <cr> marker).

type HelpFormat

type HelpFormat struct {
	LineWidth          int      `yaml:"lineWidth"`
	NestedKeywordWidth *int     `yaml:"nestedKeywordWidth"`
	TailOrder          []string `yaml:"tailOrder"`
	BlankLineAfter     bool     `yaml:"blankLineAfter"`
	RootHeader         string   `yaml:"rootHeader"`
	Indent             int      `yaml:"indent"`
	KeywordWidth       int      `yaml:"keywordWidth"`
	EchoQuestion       bool     `yaml:"echoQuestion"`
}

HelpFormat controls only '?' rendering. Tab retains its compact suggestions. A nil format preserves the original unadorned, one-token-per-line output.

type Login

type Login struct {
	UsernamePrompt string `yaml:"usernamePrompt"`
	PasswordPrompt string `yaml:"passwordPrompt"`
	Failure        string `yaml:"failure"`
	Attempts       int    `yaml:"attempts"`
}

type Match

type Match struct {
	Command string
	Args    map[string]string
}

type Mode

type Mode struct {
	Prompt string `yaml:"prompt"`
}

type Options

type Options struct {
	Username     string
	Password     string
	Scenario     *Scenario
	OutputBuffer int
}

type ParseError

type ParseError struct {
	Kind   string
	Offset int
}

ParseError distinguishes grammar errors independently of vendor error rendering.

func (*ParseError) Error

func (e *ParseError) Error() string

type Profile

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

Profile is immutable after compilation and may be shared by independent devices.

func LoadProfile

func LoadProfile(r io.Reader, files fs.FS) (*Profile, error)

LoadProfile resolves fixtures only inside files; pass nil when none are used.

func (*Profile) Complete

func (p *Profile) Complete(mode, line string) Completion

Complete uses the initial configuration for declared argument values. One keyword/value match expands to its canonical spelling plus a space; several matches expand only their common prefix. Unconfigured free-form arguments and preceding words/whitespace are preserved. Keywords can be completed even when execution abbreviations are disabled.

func (*Profile) CompleteWithState

func (p *Profile) CompleteWithState(mode, line string, state map[string]any) Completion

CompleteWithState completes keywords and explicitly configured argument values. It reads, but never changes, the supplied configuration.

func (*Profile) Help

func (p *Profile) Help(mode, line string) []string

Help returns sorted keyword/argument hints for the current grammar position. Unlike Complete, word help also lists longer siblings of an exact keyword.

func (*Profile) HelpEntries

func (p *Profile) HelpEntries(mode, line string) []HelpEntry

HelpEntries uses the same one-level grammar query as Help and Complete. Without a trailing space it filters the current word; after a space it lists only the next words. Shared prefixes appear once, with their own help.

func (*Profile) HelpEntriesWithState

func (p *Profile) HelpEntriesWithState(mode, line string, state map[string]any) []HelpEntry

HelpEntriesWithState includes declared values from the supplied configuration.

func (*Profile) HelpWithState

func (p *Profile) HelpWithState(mode, line string, state map[string]any) []string

HelpWithState resolves declared argument values from the supplied configuration.

func (*Profile) Parse

func (p *Profile) Parse(mode, line string) (Match, error)

Parse implements context-dependent unique keyword abbreviations. An exact keyword takes precedence over its longer siblings. Argument spelling is kept.

func (*Profile) RenderConfiguration

func (p *Profile) RenderConfiguration(name string, selection map[string]string, config map[string]any) (string, error)

RenderConfiguration formats an entire tree or a section. Selection keys name Each sections; values select a map key. No input is mutated. Output is capped at 1 MiB.

func (*Profile) RenderHelp

func (p *Profile) RenderHelp(mode, line string) string

RenderHelp returns LF-terminated help text without echo, surrounding newlines or a prompt. Device applies terminal newlines and restores the input buffer.

func (*Profile) RenderHelpWithState

func (p *Profile) RenderHelpWithState(mode, line string, state map[string]any) string

RenderHelpWithState formats help against a live/session configuration snapshot.

func (*Profile) ValidateConfiguration

func (p *Profile) ValidateConfiguration(config map[string]any) error

ValidateConfiguration checks a proposed complete configuration without changing it. validate(config) receives a recursively frozen copy and returns None to accept or a non-empty string to reject. Any interpreter failure also rejects the change, but is not classified as a ValidationError.

type Scenario

type Scenario struct {
	APIVersion string    `yaml:"apiVersion"`
	Timeline   []Event   `yaml:"timeline"`
	Triggers   []Trigger `yaml:"triggers"`
}

func LoadScenario

func LoadScenario(r io.Reader, files fs.FS) (*Scenario, error)

type Session

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

Session is one attachment. Read supports one reader; Input and Close may be called concurrently. A persistent console's state survives Session.Close.

func (*Session) Close

func (s *Session) Close() error

func (*Session) Done

func (s *Session) Done() <-chan struct{}

func (*Session) Err

func (s *Session) Err() error

func (*Session) Input

func (s *Session) Input(data []byte) error

func (*Session) Output

func (s *Session) Output() <-chan []byte

Output exposes owned output chunks as an alternative to Read. Do not mix the two.

func (*Session) Read

func (s *Session) Read(p []byte) (int, error)

func (*Session) Resize

func (s *Session) Resize(columns, rows int) error

Resize changes terminal dimensions. Zero preserves a dimension (RFC 4254).

func (*Session) Serve

func (s *Session) Serve(ctx context.Context, stream io.ReadWriteCloser) error

Serve pumps a previously attached session. It owns this attachment and stream until return; callers must not concurrently read its Output/Read or call Serve.

type SessionSnapshot

type SessionSnapshot struct {
	ID          uint64         `json:"id"`
	Console     string         `json:"console"`
	Attached    bool           `json:"attached"`
	Username    string         `json:"username"`
	Mode        string         `json:"mode"`
	Interaction string         `json:"interaction"`
	Candidate   map[string]any `json:"candidate"`
	Columns     int            `json:"columns"`
	Rows        int            `json:"rows"`
}

type Snapshot

type Snapshot struct {
	Now                time.Duration     `json:"now"`
	Lifecycle          string            `json:"lifecycle"`
	LoginReady         bool              `json:"loginReady"`
	EventOutputEnabled bool              `json:"eventOutputEnabled"`
	Running            map[string]any    `json:"running"`
	Startup            map[string]any    `json:"startup"`
	Sessions           []SessionSnapshot `json:"sessions"`
}

type Terminal

type Terminal struct {
	HistorySize *int        `yaml:"historySize"`
	Help        *HelpFormat `yaml:"help"`
	Echo        string      `yaml:"echo"`
	Newline     string      `yaml:"newline"`
	PageLines   int         `yaml:"pageLines"`
	Pager       string      `yaml:"pager"`
	LogPolicy   string      `yaml:"logPolicy"`
	MaxInput    int         `yaml:"maxInput"`
}

type Trace

type Trace struct {
	At      time.Duration `json:"at"`
	Session uint64        `json:"session"`
	Kind    string        `json:"kind"`
	Detail  string        `json:"detail"`
}

Trace describes semantic events only: passwords and raw input are never stored.

type Trigger

type Trigger struct {
	On    string        `yaml:"on"`
	After time.Duration `yaml:"after"`
	Event Event         `yaml:"event"`
}

type Validation

type Validation struct {
	Starlark string `yaml:"starlark"`
	File     string `yaml:"file"`
	MaxSteps uint64 `yaml:"maxSteps"`
}

Validation defines a read-only configuration invariant. Exactly one of Starlark (inline source) and File (relative to the profile FS) must be set.

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError is an intentional rejection returned by validate(config). Interpreter errors and invalid return types are ordinary errors instead.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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