Documentation
¶
Overview ¶
Package client speaks Rex's control protocol, rex.control.v1, over one WebSocket connection to the Rex server.
The protocol is specified by the server itself; rexuikit keeps a snapshot in docs/rex-api/llms-r7.md (the "## The Control Connection" section and its subsections are the normative source for everything in this file). Section names are cited in the doc comments below so a reader can check each rule against the spec instead of trusting this code.
A Client is safe for concurrent use. Every request gets a unique id and is multiplexed over the single connection; one reader goroutine routes each response back to its caller by id and every event onto the Events channel in seq order.
Reconnecting is deliberately not implemented: the welcome's reconnect token is recorded (ReconnectToken) so a later version can resume a client, but a dropped connection here simply fails every pending and future call.
This package never shells out to the rex CLI: the CLI costs ~76ms per call against 0.1-3ms over this connection, which is the reason rexuikit exists.
Index ¶
- Constants
- Variables
- func ServerAddr(getenv func(string) string) (string, error)
- func SocketPath(addr string) (string, error)
- type Attachment
- type BlockEvent
- type BlockInfo
- type BlockSpec
- type Bounds
- type CarrierInfo
- type Client
- func (c *Client) APIRevision() int
- func (c *Client) Attach(ctx context.Context, sessionID string) (Attachment, error)
- func (c *Client) BlockMethod(ctx context.Context, sessionID, blockID, method string, args, out any) error
- func (c *Client) Call(ctx context.Context, method string, payload, out any) error
- func (c *Client) CallSeq(ctx context.Context, method string, payload, out any) (int64, error)
- func (c *Client) ClientID() string
- func (c *Client) Close() error
- func (c *Client) CloseBlock(ctx context.Context, sessionID, blockID string) (int64, error)
- func (c *Client) CloseLayer(ctx context.Context, sessionID, layerID string) (int64, error)
- func (c *Client) CloseWindow(ctx context.Context, sessionID, windowID string) (int64, error)
- func (c *Client) Detach(ctx context.Context, sessionID string) error
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Err() error
- func (c *Client) Events() <-chan Event
- func (c *Client) FocusBlock(ctx context.Context, sessionID, blockID string) (int64, error)
- func (c *Client) ListBlocks(ctx context.Context, sessionID string) ([]BlockInfo, error)
- func (c *Client) ListSessions(ctx context.Context) ([]SessionInfo, error)
- func (c *Client) MoveBlock(ctx context.Context, a MoveBlockArgs) (MoveBlockResult, error)
- func (c *Client) NewBlock(ctx context.Context, a NewBlockArgs) (string, error)
- func (c *Client) NewLayer(ctx context.Context, a NewLayerArgs) (NewLayerResult, error)
- func (c *Client) NewSplit(ctx context.Context, a NewSplitArgs) (NewSplitResult, error)
- func (c *Client) NewWindow(ctx context.Context, a NewWindowArgs) (NewWindowResult, error)
- func (c *Client) RaiseLayer(ctx context.Context, sessionID, layerID, relativeLayerID string) (int64, error)
- func (c *Client) ReconnectToken() string
- func (c *Client) ResizeLayer(ctx context.Context, sessionID, layerID string, b Bounds) (int64, error)
- func (c *Client) ServerVersion(ctx context.Context) (Version, error)
- func (c *Client) SetBlockLabel(ctx context.Context, sessionID, blockID, label string) (int64, error)
- func (c *Client) TerminalSize(ctx context.Context, sessionID, blockID string) (TerminalSize, error)
- func (c *Client) View(ctx context.Context, sessionID string) (View, error)
- func (c *Client) Welcome() Welcome
- type DesiredSize
- type Error
- type Event
- type Layer
- type Layout
- type LayoutNode
- type Limits
- type MoveBlockArgs
- type MoveBlockResult
- type NewBlockArgs
- type NewLayerArgs
- type NewLayerResult
- type NewSplitArgs
- type NewSplitResult
- type NewWindowArgs
- type NewWindowResult
- type Options
- type SessionEvent
- type SessionInfo
- type Size
- type SplitSpec
- type TerminalOptions
- type TerminalSize
- type Version
- type View
- type ViewBlock
- type ViewSplit
- type Welcome
- type WelcomeInfo
- type Window
Constants ¶
const ( // Subprotocol is the WebSocket subprotocol the control endpoint requires // ("## The Control Connection"). Subprotocol = "rex.control.v1" ControlPath = "/api/control" // APIRevision is the control API revision this package was written // against: every typed shape in methods.go is revision 7's // ("### API Revisions"). The hello sends it as api_revision. APIRevision = 7 // MinAPIRevision is the oldest revision this package can decode. It // equals APIRevision because older revisions use different shapes for // the same methods; asking for less would let the server translate // messages into shapes methods.go cannot read. A server that cannot // speak revision 7 closes the connection with status 1008. MinAPIRevision = 7 // DefaultHandshakeTimeout bounds the wait for the welcome. The server // itself drops a connection whose hello is not in within 5 seconds // ("### Opening the Connection"), so waiting longer for its reply would // only hide a dead server. DefaultHandshakeTimeout = 5 * time.Second // DefaultEventBuffer is how many undelivered events the client holds // before it gives up on the connection (see ErrEventOverflow). DefaultEventBuffer = 1024 // DefaultWriteTimeout bounds one request write. Writes are not tied to // the caller's context: coder/websocket closes the whole connection when // a write's context ends mid-write, so a caller's cancellation would // otherwise kill every other caller's requests too. DefaultWriteTimeout = 5 * time.Second // DefaultPingInterval and pingTimeout follow the server's own keepalive // schedule ("### Staying Connected"): ping every 30s, wait 15s for each // pong, give up after two misses in a row. DefaultPingInterval = 30 * time.Second )
const ( Horizontal = "horizontal" Vertical = "vertical" Before = "before" After = "after" )
Directions and sides for splits ("### `session.new_split`").
const ( LayerTiled = "tiled" LayerFloating = "floating" )
Layer kinds. The spec says to treat an unknown kind as floating.
const ( Placed = "placed" Detached = "detached" )
Block placements in BlockInfo. The spec says to treat an unknown value as detached.
const DefaultSocketPath = "Library/Application Support/rex/server.sock"
DefaultSocketPath is where the macOS Rex app's server listens when REX_SERVER is not set, relative to $HOME.
const TerminalFlavor = "com.superlogical.terminal.shell"
TerminalFlavor is the terminal block flavor, the only one rexuikit creates.
Variables ¶
var ( // ErrClosed is returned by calls made after, or pending during, Close. ErrClosed = errors.New("rexuikit/client: connection closed") // ErrEventOverflow is the connection's terminal error when the event // buffer fills because nobody is reading Events. The client closes the // connection rather than drop an event: an event stream with a hole // silently desynchronises every view built from it, while a closed // connection is a visible failure the caller can recover from by // reconnecting and re-reading state ("### Combining Results With // Events"). ErrEventOverflow = errors.New("rexuikit/client: event buffer full (Events not drained); connection closed") // ErrEventGap is the terminal error when an event's seq is not exactly // one more than the last. The server promises a gapless sequence on a // live connection ("### Combining Results With Events"), so a gap means // an event was lost and any state built from the stream is wrong. ErrEventGap = errors.New("rexuikit/client: event seq out of order") // ErrKeepalive is the terminal error after two unanswered pings. ErrKeepalive = errors.New("rexuikit/client: server stopped answering pings") )
var ( ErrBadRequest error = &codeSentinel{"bad_request"} ErrNotFound error = &codeSentinel{"not_found"} ErrMethodNotFound error = &codeSentinel{"method_not_found"} ErrSessionNotFound error = &codeSentinel{"session_not_found"} ErrConflict error = &codeSentinel{"conflict"} ErrNotSupported error = &codeSentinel{"not_supported"} ErrRefused error = &codeSentinel{"refused"} ErrTooLarge error = &codeSentinel{"too_large"} ErrRevisionTooLow error = &codeSentinel{"revision_too_low"} ErrTimeout error = &codeSentinel{"timeout"} ErrInternal error = &codeSentinel{"internal"} )
The sentinels for every code in the r7 error table. Servers released before method_not_found existed answer a missing method with not_found, so a caller probing for a method should accept both.
Functions ¶
func ServerAddr ¶
ServerAddr resolves the server address from the environment: REX_SERVER when set, else a unix:// URL for $HOME's default socket. It does no I/O.
func SocketPath ¶
SocketPath returns the filesystem path a unix:// address names. Rex percent-encodes the path in REX_SERVER (a space in "Application Support" arrives as %20), so the path is unescaped exactly once; the snapshot script rexuikit/scripts/rex-api-snapshot.sh decodes it the same way.
Types ¶
type Attachment ¶
type Attachment struct {
ClientID string `json:"client_id"`
View View `json:"view"`
Seq int64 `json:"-"`
}
Attachment is session.attach's result plus the response seq. Apply View first, then only events with a seq above Seq ("### Combining Results With Events").
type BlockEvent ¶
type BlockEvent struct {
SessionID string
BlockID string
CreatorName string
Name string
Payload json.RawMessage
}
BlockEvent is a block's own event, which arrives as a block_event inside a session_event ("### Events"; fields per "### `block_event`").
type BlockInfo ¶
type BlockInfo struct {
BlockID string `json:"block_id"`
Label string `json:"label"`
CreatorName string `json:"creator_name,omitempty"`
Flavor string `json:"flavor,omitempty"`
HostID string `json:"host_id,omitempty"`
Placement string `json:"placement"`
WindowID string `json:"window_id,omitempty"`
Owner string `json:"owner,omitempty"`
}
type BlockSpec ¶
type BlockSpec struct {
Flavor string `json:"flavor"`
Options any `json:"options,omitempty"`
Label string `json:"label,omitempty"`
}
BlockSpec starts one new block. Options is passed to the flavor's creator unchanged; for TerminalFlavor use TerminalOptions.
type Bounds ¶
type Bounds [4]float64
Bounds is [x, y, w, h] as fractions of the window's width and height.
type CarrierInfo ¶
type CarrierInfo struct {
Carrier string `json:"carrier"`
Port int `json:"port"`
ALPN []string `json:"alpn"`
}
CarrierInfo is another transport to the same server. rexuikit ignores carriers; the field is kept so Welcome round-trips what the server sent.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func Dial ¶
Dial opens a control connection, sends the hello and waits for the welcome. ctx bounds the whole handshake; the returned Client outlives it.
func (*Client) APIRevision ¶
func (*Client) Attach ¶
Attach calls session.attach ("### `session.attach`"). Most methods naming a session fail with conflict until the connection is attached to it.
func (*Client) BlockMethod ¶
func (c *Client) BlockMethod(ctx context.Context, sessionID, blockID, method string, args, out any) error
BlockMethod calls a block's own method, such as com.superlogical.terminal.size, with its arguments under args ("## Calling Block Methods"). Nil args sends an empty object, which every block method's object schema accepts.
func (*Client) Call ¶
Call sends one request and decodes its result into out (which may be nil to discard it). payload is the method's arguments; nil omits the field, as the spec allows for methods that take none ("### Calling a Method").
A failed call returns *Error; compare it with errors.Is against the Err* code sentinels. Cancelling ctx abandons the wait, not the request: the server may still run it, and its late response is discarded.
func (*Client) CallSeq ¶
CallSeq is Call that also returns the response's seq: the last event the server had queued before it started the request. Events with a higher seq may not be reflected in the result ("### Combining Results With Events").
func (*Client) ClientID ¶
ClientID is this connection's client id, or "" from a server that cannot resume clients.
func (*Client) Close ¶
Close ends the connection with a close frame, which also ends the client at once on the server ("### Reconnecting"). Pending calls return ErrClosed. It is safe to call more than once.
func (*Client) CloseBlock ¶
CloseBlock calls block.close ("### `block.close`") on one block, placed or detached, ending its program.
func (*Client) CloseLayer ¶
CloseLayer calls session.close_layer ("### `session.close_layer`"). If the layer had focus, focus returns to the layer that had it before.
func (*Client) CloseWindow ¶
CloseWindow calls session.close_window ("### `session.close_window`"), which closes every block in the window. Empty windowID closes the active window.
func (*Client) Events ¶
Events returns the event stream. It is closed when the connection ends; Err then says why. It is nil when Options.DisableEvents was set.
func (*Client) FocusBlock ¶
FocusBlock calls session.focus_block ("### `session.focus_block`"). A detached block cannot be focused (not_found).
func (*Client) ListBlocks ¶
ListBlocks calls session.list_blocks ("### `session.list_blocks`"): every block including detached ones, sorted by block id.
func (*Client) ListSessions ¶
func (c *Client) ListSessions(ctx context.Context) ([]SessionInfo, error)
ListSessions calls session.list ("### `session.list`"), in creation order.
func (*Client) MoveBlock ¶
func (c *Client) MoveBlock(ctx context.Context, a MoveBlockArgs) (MoveBlockResult, error)
MoveBlock calls session.move_block ("### `session.move_block`"). It places a detached block beside an anchor; a move that empties a floating layer removes the layer.
func (*Client) NewBlock ¶
NewBlock calls session.new_block ("### `session.new_block`"): the block starts detached and owned by this client. It returns the block id.
func (*Client) NewLayer ¶
func (c *Client) NewLayer(ctx context.Context, a NewLayerArgs) (NewLayerResult, error)
NewLayer calls session.new_layer ("### `session.new_layer`").
func (*Client) NewSplit ¶
func (c *Client) NewSplit(ctx context.Context, a NewSplitArgs) (NewSplitResult, error)
NewSplit calls session.new_split ("### `session.new_split`").
func (*Client) NewWindow ¶
func (c *Client) NewWindow(ctx context.Context, a NewWindowArgs) (NewWindowResult, error)
NewWindow calls session.new_window ("### `session.new_window`").
func (*Client) RaiseLayer ¶
func (c *Client) RaiseLayer(ctx context.Context, sessionID, layerID, relativeLayerID string) (int64, error)
RaiseLayer calls session.raise_layer ("### `session.raise_layer`"). Empty relativeLayerID moves the layer to the front.
func (*Client) ReconnectToken ¶
ReconnectToken is the token a later hello would send to resume this client ("### Reconnecting"). Resuming is not implemented yet; the token is kept for it. Never log it: it is a credential for this client.
func (*Client) ResizeLayer ¶
func (c *Client) ResizeLayer(ctx context.Context, sessionID, layerID string, b Bounds) (int64, error)
ResizeLayer calls session.resize_layer ("### `session.resize_layer`"). It is not an ordered method, so successive animation frames sent without waiting may apply out of order.
func (*Client) SetBlockLabel ¶
func (c *Client) SetBlockLabel(ctx context.Context, sessionID, blockID, label string) (int64, error)
SetBlockLabel calls session.set_block_label ("### `session.set_block_label`"). An empty label restores the default.
func (*Client) TerminalSize ¶
type DesiredSize ¶
type Error ¶
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
// Method is the method that failed, filled in by the client.
Method string `json:"-"`
}
Error is a failed call's error object ("### Errors"). Branch on it with errors.Is and the Err* sentinels, never on Message: the server rewords messages between releases.
type Event ¶
type Event struct {
Seq int64
Type string
Payload json.RawMessage
}
Event is one event message from the server ("### Events"): its place in the connection's sequence and the inner event's name and fields. Unknown types are delivered unchanged; the spec requires clients to skip them, and that choice belongs to the consumer, not the transport.
type Layer ¶
type Layer struct {
LayerID string `json:"layer_id"`
Kind string `json:"kind"`
Bounds Bounds `json:"bounds"`
Layout *LayoutNode `json:"layout"`
Blocks []ViewBlock `json:"blocks"`
}
Layer is a window's layer; the first is the tiled layout.
type Layout ¶
type Layout struct {
Block *BlockSpec `json:"block,omitempty"`
Split *SplitSpec `json:"split,omitempty"`
}
Layout is a node of a layout to create: exactly one of Block or Split.
func BlockLayout ¶
type LayoutNode ¶
type LayoutNode struct {
Rect Bounds `json:"rect"`
BlockID string `json:"block_id,omitempty"`
Split *ViewSplit `json:"split,omitempty"`
}
LayoutNode is a node of an existing layout: a block or a split.
type MoveBlockArgs ¶
type MoveBlockArgs struct {
SessionID string `json:"session_id"`
BlockID string `json:"block_id"`
AnchorBlockID string `json:"anchor_block_id"`
Direction string `json:"direction,omitempty"`
Side string `json:"side,omitempty"`
Ratio float64 `json:"ratio,omitempty"`
}
MoveBlockArgs are session.move_block's arguments. Empty Direction and Side mean the server's horizontal and after.
type MoveBlockResult ¶
type NewBlockArgs ¶
type NewLayerArgs ¶
type NewLayerArgs struct {
SessionID string `json:"session_id"`
WindowID string `json:"window_id,omitempty"`
Bounds Bounds `json:"bounds"`
Layout Layout `json:"layout"`
Focus bool `json:"focus,omitempty"`
}
NewLayerArgs are session.new_layer's arguments. Empty WindowID means the active window.
type NewLayerResult ¶
type NewSplitArgs ¶
type NewSplitArgs struct {
SessionID string `json:"session_id"`
AnchorID string `json:"anchor_id,omitempty"`
WindowID string `json:"window_id,omitempty"`
Direction string `json:"direction"`
Side string `json:"side"`
Ratio float64 `json:"ratio,omitempty"`
Layout Layout `json:"layout"`
Focus bool `json:"focus,omitempty"`
}
NewSplitArgs are session.new_split's arguments. Send AnchorID or WindowID, not both; with neither, the active window's focused block is split.
type NewSplitResult ¶
type NewWindowArgs ¶
type NewWindowArgs struct {
SessionID string `json:"session_id"`
Label string `json:"window_label,omitempty"`
Layout Layout `json:"layout"`
Focus *bool `json:"focus,omitempty"`
}
NewWindowArgs are session.new_window's arguments. Nil Focus means the server default, which is true.
type NewWindowResult ¶
type Options ¶
type Options struct {
// Addr is the server address: a unix:// URL whose path is
// percent-encoded (REX_SERVER's format, e.g.
// unix:///Users/me/Library/Application%20Support/rex/server.sock), or
// an http://, https://, ws:// or wss:// base URL. Empty resolves it
// from Getenv with ServerAddr.
Addr string
// HTTPClient carries the WebSocket handshake. Nil builds one that dials
// Addr's unix socket (or uses http.DefaultClient for a network URL).
// Tests pass an httptest server's client to run hermetically over TCP
// loopback, because the sandbox denies unix-socket bind().
HTTPClient *http.Client
// Getenv resolves an empty Addr. Nil means os.Getenv.
Getenv func(string) string
// Name and Version describe this program in the hello's client object.
// Empty Name means "rexuikit".
Name string
Version string
// HandshakeTimeout bounds the wait for the welcome; zero means
// DefaultHandshakeTimeout.
HandshakeTimeout time.Duration
// EventBuffer is how many events may queue before the connection is
// failed with ErrEventOverflow; zero means DefaultEventBuffer.
EventBuffer int
// DisableEvents discards every event instead of queueing it, and makes
// Events return a nil channel. Use it for a connection that only makes
// calls: an attached session emits events continuously, and an
// undrained buffer would otherwise end the connection.
DisableEvents bool
// PingInterval is how often the client pings the server; zero means
// DefaultPingInterval, negative disables client pings (the client still
// answers the server's pings).
PingInterval time.Duration
}
Options configures Dial. The zero value dials the server named by the environment (REX_SERVER, else the default macOS socket).
type SessionEvent ¶
type SessionEvent struct {
SessionID string
Type string
Payload json.RawMessage
}
SessionEvent is the inside of a session_event: the session it happened in and the event itself.
type SessionInfo ¶
type SplitSpec ¶
type SplitSpec struct {
Direction string `json:"direction"`
Before Layout `json:"before"`
After Layout `json:"after"`
Ratio float64 `json:"ratio,omitempty"`
}
SplitSpec divides a node in two. Zero Ratio means the server's 0.5.
type TerminalOptions ¶
type TerminalOptions struct {
Shell string `json:"shell,omitempty"`
Command []string `json:"command,omitempty"`
Cwd string `json:"cwd,omitempty"`
Size *Size `json:"size,omitempty"`
}
TerminalOptions are a terminal block's creation options. The r7 snapshot does not spell this schema out (block_creator.list serves it live); these fields are the ones observed working during planning probes: Shell "none" with Command runs Command as the block's own program (Shell "none" without Command tries to exec "none"), and Size sets the starting size, without which a block starts at 80x24.
type TerminalSize ¶
type TerminalSize struct {
Columns int `json:"columns"`
Rows int `json:"rows"`
CellWidthPx int `json:"cell_width_px"`
CellHeightPx int `json:"cell_height_px"`
Owner string `json:"owner,omitempty"`
Desired []DesiredSize `json:"desired"`
}
TerminalSize is com.superlogical.terminal.size's result.
type Version ¶
type Version struct {
RexVersion string `json:"rex_version"`
Platform string `json:"platform"`
Commit string `json:"commit,omitempty"`
BuiltAt string `json:"built_at,omitempty"`
Dirty bool `json:"dirty"`
APIRevision int `json:"api_revision,omitempty"`
APIMinRevision int `json:"api_min_revision,omitempty"`
}
Version is server.version's result ("### `server.version`").
type View ¶
type View struct {
Revision int64 `json:"revision"`
SessionID string `json:"session_id"`
Label string `json:"label,omitempty"`
ActiveWindowID string `json:"active_window_id,omitempty"`
Windows []Window `json:"windows"`
}
View is a session's structure ("### `session.view`"). It holds only placed blocks; ListBlocks also lists detached ones.
type ViewSplit ¶
type ViewSplit struct {
SplitID string `json:"split_id"`
Direction string `json:"direction"`
Ratio float64 `json:"ratio"`
Before LayoutNode `json:"before"`
After LayoutNode `json:"after"`
}
type Welcome ¶
type Welcome struct {
Protocol string `json:"protocol"`
Limits Limits `json:"limits"`
Client *WelcomeInfo `json:"client,omitempty"`
Features []string `json:"features,omitempty"`
APIRevision int `json:"api_revision"`
APIServerRevision int `json:"api_server_revision"`
APIMinRevision int `json:"api_min_revision"`
Carriers []CarrierInfo `json:"carriers,omitempty"`
}
Welcome is what the server said when it accepted the connection ("### Opening the Connection", the welcome's fields).
type WelcomeInfo ¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clienttest is an in-process fake of Rex's control endpoint for hermetic tests of rexuikit/client and the packages built on it.
|
Package clienttest is an in-process fake of Rex's control endpoint for hermetic tests of rexuikit/client and the packages built on it. |