Documentation
¶
Overview ¶
Package emulator implements a small, deterministic, stateful CLI emulator. It models terminal interactions, not a switch data or control plane.
Index ¶
- Variables
- type Action
- type Answer
- type ArgumentCompletion
- type ArgumentSpec
- type AttachOptions
- type Command
- type Completion
- type ConfigurationSection
- type Definition
- type Device
- func (d *Device) Advance(delta time.Duration) error
- func (d *Device) Attach(o AttachOptions) (*Session, error)
- func (d *Device) Close() error
- func (d *Device) ControlHandler(token string) (http.Handler, error)
- func (d *Device) Inject(e Event) error
- func (d *Device) Reboot() error
- func (d *Device) Run(ctx context.Context) error
- func (d *Device) Serve(ctx context.Context, stream io.ReadWriteCloser, options AttachOptions) error
- func (d *Device) ServeConsole(ctx context.Context, listener net.Listener, name string) error
- func (d *Device) ServeControl(ctx context.Context, listener net.Listener, token string) error
- func (d *Device) SetEventOutput(enabled bool) error
- func (d *Device) Snapshot() Snapshot
- func (d *Device) Trace() []Trace
- type Dialog
- type Event
- type HelpEntry
- type HelpFormat
- type Login
- type Match
- type Mode
- type Options
- type ParseError
- type Profile
- func (p *Profile) Complete(mode, line string) Completion
- func (p *Profile) CompleteWithState(mode, line string, state map[string]any) Completion
- func (p *Profile) Help(mode, line string) []string
- func (p *Profile) HelpEntries(mode, line string) []HelpEntry
- func (p *Profile) HelpEntriesWithState(mode, line string, state map[string]any) []HelpEntry
- func (p *Profile) HelpWithState(mode, line string, state map[string]any) []string
- func (p *Profile) Parse(mode, line string) (Match, error)
- func (p *Profile) RenderConfiguration(name string, selection map[string]string, config map[string]any) (string, error)
- func (p *Profile) RenderHelp(mode, line string) string
- func (p *Profile) RenderHelpWithState(mode, line string, state map[string]any) string
- func (p *Profile) ValidateConfiguration(config map[string]any) error
- type Scenario
- type Session
- func (s *Session) Close() error
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Err() error
- func (s *Session) Input(data []byte) error
- func (s *Session) Output() <-chan []byte
- func (s *Session) Read(p []byte) (int, error)
- func (s *Session) Resize(columns, rows int) error
- func (s *Session) Serve(ctx context.Context, stream io.ReadWriteCloser) error
- type SessionSnapshot
- type Snapshot
- type Terminal
- type Trace
- type Trigger
- type Validation
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
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 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 ¶
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"`
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 (*Device) Advance ¶
Advance runs scheduled events in timestamp/sequence order without sleeping.
func (*Device) ControlHandler ¶
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 ¶
Inject emits a validated event immediately. It is useful as a test control API.
func (*Device) Run ¶
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 ¶
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 ¶
ServeControl serves only on a TCP loopback listener, disabled unless explicitly enabled.
func (*Device) SetEventOutput ¶
SetEventOutput controls asynchronous raw/log events, not command output or readiness.
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 ¶
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 ParseError ¶
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 ¶
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 ¶
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 ¶
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 ¶
HelpEntriesWithState includes declared values from the supplied configuration.
func (*Profile) HelpWithState ¶
HelpWithState resolves declared argument values from the supplied configuration.
func (*Profile) Parse ¶
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 ¶
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 ¶
RenderHelpWithState formats help against a live/session configuration snapshot.
func (*Profile) ValidateConfiguration ¶
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 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) Output ¶
Output exposes owned output chunks as an alternative to Read. Do not mix the two.
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 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 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