Documentation
¶
Overview ¶
Package expect automates interactive byte streams with bounded waits, continuation callbacks and reusable response rules. Session owns a supplied duplex transport; Console adapts a PTY on Linux and macOS. Callers own process lifecycle, connection establishment, device policy and command success checks.
Matching uses unmodified input. Diagnostics and output copies use explicit streaming secret redaction. Result fields are raw, detached snapshots.
Copyright 2018 Netflix, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy at https://www.apache.org/licenses/LICENSE-2.0
Index ¶
- Variables
- type Action
- type Capture
- type Case
- type Console
- type ConsoleOption
- type Event
- type ExpectOption
- type Handler
- type Observer
- type Pattern
- type Redactor
- type Responder
- type Response
- type ResponseError
- type Result
- type Rule
- type Session
- func (s *Session) Close() error
- func (s *Session) Expect(ctx context.Context, cases []Case, opts ...ExpectOption) (Result, error)
- func (s *Session) Poll(ctx context.Context, cases []Case, opts ...ExpectOption) (Result, error)
- func (s *Session) Redact(secrets ...string) error
- func (s *Session) Send(ctx context.Context, text string) (n int, err error)
- func (s *Session) SendAll(ctx context.Context, text string) (int, error)
- func (s *Session) SendAllPoll(ctx context.Context, text string) (int, error)
- func (s *Session) SendLine(ctx context.Context, text string) (int, error)
- type SessionOption
- func WithBufferLimit(n int) SessionOption
- func WithDefaultTimeout(d time.Duration) SessionOption
- func WithLineEnding(s string) SessionOption
- func WithLogger(l *log.Logger) SessionOption
- func WithOSPolling() SessionOption
- func WithObserver(observers ...Observer) SessionOption
- func WithOutput(writers ...io.Writer) SessionOption
- func WithTranscript(w io.Writer) SessionOption
- func WithWriteTimeout(d time.Duration) SessionOption
- type WriteError
Constants ¶
This section is empty.
Variables ¶
var ( ErrClosed = errors.New("expect: session closed") ErrBusy = errors.New("expect: another expect operation is active") ErrTimeout = errors.New("expect: timeout") ErrIdleTimeout = errors.New("expect: idle timeout") ErrBufferLimit = errors.New("expect: buffer limit reached") ErrEmptyMatch = errors.New("expect: empty match") ErrPollUnsupported = errors.New("expect: OS polling unsupported") )
Functions ¶
This section is empty.
Types ¶
type Action ¶
type Action uint8
Action determines whether a matched Case returns or continues waiting.
type Console ¶
type Console struct {
// contains filtered or unexported fields
}
Console adapts an owned PTY to Session. It does not start, wait for, signal or reap processes. TTY is intended for a caller-owned exec.Cmd or local device.
func NewConsole ¶
func NewConsole(opts ...ConsoleOption) (*Console, error)
NewConsole creates a PTY and a Session. Failure closes every acquired handle.
type ConsoleOption ¶
type ConsoleOption func(*consoleOptions) error
ConsoleOption configures the PTY adapter.
func WithRaw ¶
func WithRaw() ConsoleOption
WithRaw configures the slave in raw mode, including disabling echo.
func WithSessionOptions ¶
func WithSessionOptions(opts ...SessionOption) ConsoleOption
WithSessionOptions configures the Console's underlying Session.
type ExpectOption ¶
type ExpectOption func(*expectOptions) error
ExpectOption configures matching or timing for a single Expect operation.
func WithDeclarationPriority ¶ added in v0.1.1
func WithDeclarationPriority() ExpectOption
WithDeclarationPriority selects the first declared matching case, regardless of its byte position. Without this option the earliest byte wins.
func WithIdleTimeout ¶
func WithIdleTimeout(d time.Duration) ExpectOption
WithIdleTimeout limits time without new input; zero disables it.
func WithStreamingFallback ¶ added in v0.1.1
func WithStreamingFallback(handler Handler) ExpectOption
WithStreamingFallback consumes the first 32 KiB when 64 KiB are pending and no ordinary case matches. Result.CaseIndex is -1 and Match is the consumed data. Continue and ContinueWithoutReset both preserve all existing timers.
func WithTimeout ¶
func WithTimeout(d time.Duration) ExpectOption
WithTimeout sets the relative timer, including elapsed callback time. Zero disables it. Continue can reset it; context deadlines cannot be reset.
type Handler ¶
Handler runs after consumption, outside internal locks. It may send or close, but may not call Expect recursively on the same Session.
type Observer ¶
type Observer func(Event)
Observer is invoked once per completed public Expect, Send or SendAll operation. Observers run synchronously outside locks and must not block indefinitely.
type Pattern ¶
type Pattern struct {
// contains filtered or unexported fields
}
Pattern is an immutable literal, regular expression, EOF or All pattern. Its zero value is invalid. It never contains per-operation match state.
func All ¶
All matches all supplied text patterns, in any order, consuming through the last match. Repeated patterns may refer to the same bytes. Captures are omitted.
func EOF ¶
func EOF() Pattern
EOF matches a clean end of input, after buffered text has been matched.
func FromRegexp ¶ added in v0.1.1
FromRegexp snapshots a compiled expression, including POSIX/Longest semantics. Later changes to the caller's expression do not affect the Pattern.
type Redactor ¶ added in v0.1.1
type Redactor struct {
// contains filtered or unexported fields
}
Redactor filters one diagnostic stream independently of any Session. Rules, retained prefixes and replacement runs are scoped to this instance. Methods are concurrency safe. Formatting never exposes secrets or retained data.
func NewRedactor ¶ added in v0.1.1
NewRedactor copies literal secrets and the nonempty custom replacement.
func (*Redactor) Append ¶ added in v0.1.1
Append returns only bytes that cannot begin a future secret match. It replaces each contiguous union of overlapping or adjacent matches once, across chunks.
func (*Redactor) Finish ¶ added in v0.1.1
Finish ends a stream and conservatively masks any retained secret prefix. Repeated calls are empty; the instance may then filter a fresh stream.
func (*Redactor) SetSecrets ¶ added in v0.1.1
SetSecrets ends the old rule scope and returns its safe final bytes. Suspected old secret prefixes are masked before new rules take effect. Invalid rules leave the existing scope untouched. Callers must deliver the returned bytes.
type Responder ¶
type Responder struct {
// contains filtered or unexported fields
}
Responder is an immutable rule set, safe to reuse across different sessions. Rule counts are local to each call; callback closures remain caller-owned.
func NewResponder ¶
NewResponder validates and snapshots rules without accessing a session.
func (*Responder) Expect ¶
func (r *Responder) Expect(ctx context.Context, s *Session, completion []Pattern, opts ...ExpectOption) (Result, error)
Expect responds to registered prompts while waiting for a completion pattern. Completion wins only same-position ties. Responses preserve the original relative timer. The returned CaseIndex indexes completion, or is -1 on failure.
type Response ¶
Response sends a reply or performs a caller-defined action for a matched rule. It must return write errors; actions are never automatically retried.
type ResponseError ¶
type ResponseError struct{ RuleIndex int }
ResponseError identifies a response rule that exceeded its per-call limit.
func (*ResponseError) Error ¶
func (e *ResponseError) Error() string
type Result ¶
Result is a detached snapshot of the final match, not the whole conversation. Before contains pending input on failure; CaseIndex is -1 without a match. Explicit fields contain unredacted bytes; formatting emits only metadata.
type Rule ¶
Rule describes a reusable automatic response. Limit zero means one response per Expect, negative is invalid, positive sets an explicit finite limit.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session owns one duplex transport and one matching buffer. The transport must support concurrent Read/Write and guarantee Close interrupts both. After a successful NewSession, callers must not perform I/O on that transport. Expect and Poll are exclusive. Sends are serialized; Close and Redact are concurrency safe. SendAll may queue bounded input for the next Expect. Do not copy a Session. Callback and output execution is cooperative.
func NewSession ¶
func NewSession(transport io.ReadWriteCloser, opts ...SessionOption) (*Session, error)
NewSession transfers transport ownership only on success. Options are validated before any reads, writes or closes take place.
func (*Session) Close ¶
Close interrupts I/O and joins owned workers. It never waits for application callbacks or closes borrowed output writers. Repeated calls return the same error.
func (*Session) Expect ¶
Expect consumes input through the earliest currently visible match. Ties use declaration order. Continuations consume their match and rescan the remaining buffer, without rereading or replaying bytes. Context cancellation and timeout leave unmatched input available to a subsequent call.
func (*Session) Poll ¶ added in v0.1.1
Poll matches buffered bytes and performs one OS readiness pass without waiting for future input. No match returns ErrTimeout. A zero Expect timeout instead disables that timer and continues waiting. Requires WithOSPolling.
func (*Session) Redact ¶
Redact adds nonempty literal secrets before sending or receiving them. Registration cannot retract bytes already delivered to output writers.
func (*Session) Send ¶
Send writes text once. No partial write is retried. A failure after entering transport.Write closes the Session and returns its progress in WriteError. An invalid transport count is rejected and reported as zero.
func (*Session) SendAll ¶ added in v0.1.1
SendAll writes only the unsent suffix after positive partial writes. Its context owns the complete deadline, including serialization; WithWriteTimeout applies only to Send. Receive data is queued up to WithBufferLimit while the peer writes before reading. Exceeding that bound fails instead of deadlocking. Every error after transport entry closes the Session and reports total progress.
func (*Session) SendAllPoll ¶ added in v0.1.1
SendAllPoll uses immediate OS write readiness for every suffix, permitting an initial write without waiting. A blocked suffix returns ErrTimeout with total progress and closes the Session. Requires WithOSPolling.
type SessionOption ¶
type SessionOption func(*sessionOptions) error
SessionOption configures a Session before it takes ownership of the transport.
func WithBufferLimit ¶
func WithBufferLimit(n int) SessionOption
WithBufferLimit bounds unconsumed matching input; overflow never discards data.
func WithDefaultTimeout ¶
func WithDefaultTimeout(d time.Duration) SessionOption
WithDefaultTimeout sets the relative Expect timeout; zero disables it.
func WithLineEnding ¶
func WithLineEnding(s string) SessionOption
WithLineEnding selects LF, CR or CRLF for SendLine. Send and Reply are verbatim.
func WithLogger ¶
func WithLogger(l *log.Logger) SessionOption
WithLogger enables metadata-only diagnostics; payloads and causes are omitted.
func WithOSPolling ¶ added in v0.1.1
func WithOSPolling() SessionOption
WithOSPolling enables sole-reader OS readiness coordination for Poll and SendAllPoll. The transport must expose syscall.Conn and a nonblocking OS fd. Unsupported transports fail construction before ownership transfers. A working SetReadDeadline(time.Time) error capability selects the runtime poller; otherwise construction selects the bounded native-poll fallback. Wrappers may forward NormalizeReadError(error) error for transport-specific read errors, such as PTY EIO at EOF. Control errors are never normalized.
func WithObserver ¶
func WithObserver(observers ...Observer) SessionOption
WithObserver adds metadata observers in declaration order.
func WithOutput ¶
func WithOutput(writers ...io.Writer) SessionOption
WithOutput copies received input through the streaming secret filter. Writers are borrowed, synchronous and must not reenter Session methods. Failure closes the Session; delivery to earlier writers is not replayed.
func WithTranscript ¶
func WithTranscript(w io.Writer) SessionOption
WithTranscript records the same filtered receive stream as WithOutput.
func WithWriteTimeout ¶
func WithWriteTimeout(d time.Duration) SessionOption
WithWriteTimeout bounds each Send, including serialization wait; zero disables it.
type WriteError ¶
WriteError reports a failed, non-retryable write. Error never prints payloads or the underlying error message; Unwrap exposes the original cause explicitly.
func (*WriteError) Error ¶
func (e *WriteError) Error() string
func (*WriteError) GoString ¶
func (e *WriteError) GoString() string
func (*WriteError) Unwrap ¶
func (e *WriteError) Unwrap() error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
dialogue
command
Command dialogue runs a local simulated device; no network connection is made.
|
Command dialogue runs a local simulated device; no network connection is made. |
|
Package expecttest provides test-owned PTY consoles without logging goroutines.
|
Package expecttest provides test-owned PTY consoles without logging goroutines. |