Documentation
¶
Overview ¶
Package ptyrelay is the serve-side per-session pty relay (WEB-03 design §6, K2/K6): it consumes a PtySource (the raw byte stream from a worker's pty over the dedicated pty ws, or a serve-local ptmx) and drives TWO independent backpressure layers:
- recorder MAIN path (bounded, must not lose bytes): every chunk read from the source is appended to a bounded ring buffer (pre-attach scrollback) and an optional cast sink. This path is synchronous and never gated on any viewer.
- viewer FAN-OUT (each viewer its own bounded queue): a slow viewer drops screen refreshes (or is disconnected) and NEVER blocks the recorder or a fast viewer.
It also holds the single input WRITE lease (K3): the first attaching writer owns exclusive stdin; a second writer is refused; read-only followers never take the lease.
This package is a leaf (stdlib only): the transport (ws) and the source impls live above it; it depends on neither job nor runner (G022).
Index ¶
- Constants
- Variables
- type CastSink
- type NonceBinding
- type NonceStore
- type Option
- type OutputObserver
- type PtySource
- type Registry
- func (r *Registry) Close(jobID, reason string)
- func (r *Registry) Done(jobID string) <-chan struct{}
- func (r *Registry) Lookup(jobID string) (*RelayEntry, bool)
- func (r *Registry) LookupSession(ptySessionID string) (*RelayEntry, bool)
- func (r *Registry) MarkAttached(jobID string) (*RelayEntry, error)
- func (r *Registry) Open(nonce string, source PtySource, opts ...Option) (*RelayEntry, error)
- func (r *Registry) Prepare(b RelayBinding) *RelayEntry
- type Relay
- func (r *Relay) AddViewer(write bool) (*Viewer, error)
- func (r *Relay) AddViewerWithQueue(write bool, queue int) (*Viewer, error)
- func (r *Relay) CastClosedCleanly() bool
- func (r *Relay) Close() error
- func (r *Relay) Done() <-chan struct{}
- func (r *Relay) InputLen() int64
- func (r *Relay) RecordedLen() int
- func (r *Relay) Resize(cols, rows int) error
- func (r *Relay) Size() (cols, rows int)
- func (r *Relay) Start()
- type RelayBinding
- type RelayEntry
- type RelayState
- type Stripper
- type Transcript
- type Viewer
Constants ¶
const DefaultTranscriptMaxBytes = 4 << 20
DefaultTranscriptMaxBytes is the transcript tail cap when pty.transcript_max_bytes is unset (PTY-01 decision 3).
Variables ¶
var ( ErrRelayNotFound = errors.New("ptyrelay: relay entry not found") ErrRelayBadNonce = errors.New("ptyrelay: relay nonce not found") ErrRelayAlreadyOpen = errors.New("ptyrelay: relay already open") ErrRelayFinalized = errors.New("ptyrelay: relay finalized") ErrRelayBindingMatch = errors.New("ptyrelay: relay binding mismatch") )
var ( // ErrLeaseTaken is returned when a second writer tries to attach while the // input write lease is already held (K3 exclusive write). ErrLeaseTaken = errors.New("ptyrelay: input write lease already held") // ErrReadOnly is returned when a read-only viewer tries to send input. ErrReadOnly = errors.New("ptyrelay: viewer is read-only (no write lease)") // ErrClosed is returned by operations on a closed relay. ErrClosed = errors.New("ptyrelay: relay is closed") )
Errors returned by the relay's admission paths.
Functions ¶
This section is empty.
Types ¶
type CastSink ¶
CastSink is the recorder main path's optional second consumer (asciinema-style cast recording). ptyrelay only Writes chunks and Closes the sink on finish; it is deliberately narrow (io.Writer + Close, no Err) so ptyrelay stays a leaf — the concrete sink (castrec) lives above and satisfies this; the httpapi finalize path consults the concrete sink's richer state (Err) directly (H5).
type NonceBinding ¶
type NonceBinding struct {
WorkerID string
InstanceID string
JobID string
PtySessionID string
Expiry int64
}
NonceBinding is the serve-side binding encoded by an issued relay nonce. The nonce itself is opaque; callers validate these fields after Consume.
type NonceStore ¶
type NonceStore struct {
// contains filtered or unexported fields
}
NonceStore holds one-time relay nonces in memory. It is live-only: process restart drops all entries, matching the relay registry lifecycle.
func NewNonceStore ¶
func NewNonceStore() *NonceStore
NewNonceStore returns an empty in-memory nonce store.
func (*NonceStore) Consume ¶
func (s *NonceStore) Consume(nonce string, nowUnix int64) (NonceBinding, bool)
Consume atomically removes nonce and returns its binding. Expired nonces are deleted and reported as missing. nowUnix is injected by the caller for deterministic tests.
func (*NonceStore) Issue ¶
func (s *NonceStore) Issue(b NonceBinding) string
Issue stores b and returns a cryptographically-random one-time token.
type Option ¶
type Option func(*Relay)
Option configures a Relay.
func WithCloseHook ¶
func WithCloseHook(fn func()) Option
WithCloseHook registers fn to run once the recorder has stopped and its output tail is complete (right before the cast sink is sealed and Done fires). It is the seam for a consumer that must look at the FINAL output — the session-id capture re-scans the tail here, because a TUI prints its session id on exit.
func WithOutputObserver ¶
func WithOutputObserver(fn OutputObserver) Option
WithOutputObserver wires a non-owning observer for pty output chunks.
func WithRingSize ¶
WithRingSize sets the pre-attach scrollback ring size in bytes.
func WithTranscript ¶
func WithTranscript(t *Transcript) Option
WithTranscript wires the recorder's de-ANSI'd text transcript (PTY-01 §四). The relay writes every chunk to it on the main path and closes it in finish().
func WithViewerQueue ¶
WithViewerQueue sets the per-viewer bounded output-queue depth (chunks).
type OutputObserver ¶
type OutputObserver func([]byte)
OutputObserver receives every output chunk after the recorder's ring/cast write. It is for tiny metadata extraction, e.g. detecting an agent session id; implementations must not block the relay.
type PtySource ¶
type PtySource interface {
Read([]byte) (int, error)
Write([]byte) (int, error)
Resize(cols, rows int) error
Close() error
}
PtySource is the raw byte stream a Relay consumes. remotePtySource (worker pty ws, V1) and localPtySource (serve ptmx, drop-in) both satisfy it; the relay is transport-agnostic.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages live-only pty relay sessions for serve.
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry returns an empty live-only relay registry.
func (*Registry) Close ¶
Close moves a relay to finalized and closes its terminal source. It is idempotent; repeated closes for the same job are safe. The relay is detached under the lock but closed AFTER unlocking (D-P2-8: no global HOL on a slow source.Close).
func (*Registry) Done ¶
Done returns the serve-drain completion signal for jobID (D-P2-2 semantics):
open/attached (live Relay) → relay.Done() (closed when recordLoop hits EOF =
the pty output tail has been recorded/drained)
pending_worker / finalized / missing → a pre-closed chan (no bytes can be
pending, so the host must not block waiting on a drain that will never come)
A RelayClosing entry is treated as still having a live Relay whose Done() the host can wait on; detachLocked (which finalizes) is the terminal transition, so there is no separate closing wait state to special-case here.
func (*Registry) Lookup ¶
func (r *Registry) Lookup(jobID string) (*RelayEntry, bool)
Lookup returns the relay entry for jobID.
func (*Registry) LookupSession ¶
func (r *Registry) LookupSession(ptySessionID string) (*RelayEntry, bool)
LookupSession returns the relay entry for ptySessionID.
func (*Registry) MarkAttached ¶
func (r *Registry) MarkAttached(jobID string) (*RelayEntry, error)
MarkAttached records that a browser attach path has claimed the relay. It is safe to call repeatedly after the relay is open.
func (*Registry) Open ¶
Open consumes a prepared nonce and binds the relay source. The returned entry is in open state and owns a started Relay. opts configure the Relay (e.g. WithCast wires the cast sink — the recorder wiring lands in the handler, T5).
func (*Registry) Prepare ¶
func (r *Registry) Prepare(b RelayBinding) *RelayEntry
Prepare creates or replaces a pending_worker relay entry for b. If an older entry exists for the same job, its relay is detached under the lock and closed AFTER unlocking (D-P2-8: a slow source.Close must not hold off concurrent Open/Lookup/MarkAttached).
type Relay ¶
type Relay struct {
// contains filtered or unexported fields
}
Relay is one pty session's serve-side relay + state.
func (*Relay) AddViewer ¶
AddViewer registers a viewer with the relay's default per-viewer queue depth. write=true tries to take the exclusive input lease (K3): the first writer wins; a second writer is refused with ErrLeaseTaken. Read-only viewers never touch the lease.
func (*Relay) AddViewerWithQueue ¶
AddViewerWithQueue is AddViewer with an explicit per-viewer output-queue depth (chunks). The queue is what bounds a viewer independently of others: a viewer with a shallow queue that stops draining laggs and drops, without affecting a deeper/faster viewer or the recorder (K2 layer 2).
func (*Relay) CastClosedCleanly ¶
CastClosedCleanly reports whether the cast recording was sealed cleanly. It is true when there was no cast at all or the sink's Close returned within castCloseGrace; it is false only when boundedCastClose timed out (a wedged Close, tail not封尾). Only meaningful after Done() has fired (H1).
func (*Relay) Close ¶
Close tears down the relay: closes the source, drops all viewers. Idempotent — all five close sources (source EOF, worker disconnect, browser close, cancel, explicit) funnel here (design §5 unified CAS close).
Close is NOT the close owner of done/cast (B1): when the relay was Start()ed, closing the source unblocks the recordLoop's src.Read, and the recordLoop's deferred finish() closes the cast sink (bounded) then done — so cast.Close never races the recordLoop's cast.Write. Only a relay that was NEVER Start()ed (no recordLoop to run finish) closes them here.
func (*Relay) Done ¶
func (r *Relay) Done() <-chan struct{}
Done is closed by finish() — after the recordLoop has exited (the pty output tail is recorded) and the cast sink is封尾 (or its Close timed out). For a relay that was never Start()ed, Close() closes it. Either way it always fires.
func (*Relay) InputLen ¶
InputLen reports the total stdin bytes forwarded to the source across all write-lease viewers (D-P3-8, for the pty_sessions bytes_in column).
func (*Relay) RecordedLen ¶
RecordedLen reports how many bytes the recorder has taken from the source (for tests to observe main-path progress deterministically).
func (*Relay) Resize ¶
Resize forwards a window-size change to the source (a writer-lease viewer's resize; the transport gates WHO may resize — see attach handler — the relay gates nothing beyond the source's own validation).
On success it records the new size and notifies every viewer's size listener (tools-3xy): the pty size is a single shared truth, and a viewer that misses a change has no way to recover (its terminal stays laid out for a size the TUI no longer draws for). Listeners are invoked on their own goroutines so a slow viewer connection can never stall the resizing client's read loop.
type RelayBinding ¶
type RelayBinding struct {
WorkerID string
InstanceID string
JobID string
PtySessionID string
Nonce string
Expiry int64
Cols int // initial pty window cols (D-P3-2, for the cast header); 0 = sink default
Rows int // initial pty window rows (D-P3-2, for the cast header); 0 = sink default
}
RelayBinding identifies a prepared pty relay session.
type RelayEntry ¶
type RelayEntry struct {
Binding RelayBinding
State RelayState
Relay *Relay
CreatedAt time.Time
OpenedAt time.Time
ClosedAt time.Time
CloseReason string
}
RelayEntry is one serve-side pty relay record. Callers must treat it as read-only and mutate it through Registry methods.
type RelayState ¶
type RelayState string
RelayState is the serve-side lifecycle state for one pty relay session.
const ( RelayPendingWorker RelayState = "pending_worker" RelayOpen RelayState = "open" RelayAttached RelayState = "attached" RelayClosing RelayState = "closing" RelayFinalized RelayState = "finalized" )
type Stripper ¶
type Stripper struct {
// contains filtered or unexported fields
}
Stripper removes ANSI escape sequences (PTY-01 §四): CSI, OSC, the two-byte sequences and the charset/intermediate introducers, and folds CR into LF. It is a LEAF-level text filter with no screen model: the cursor motion a TUI uses to PLACE text is turned back into whitespace (see csiFinal) so the words it drew stay apart, and every other decoration is simply dropped.
State is carried ACROSS Write calls: a read chunk may split an escape sequence (a 4KB pty read routinely cuts an OSC title or a colour run in half), and a stateless filter would leak the tail of the sequence into the text. A CR is also held back until the next byte, so CRLF folds to ONE newline and a final lone CR is emitted by Flush.
func (*Stripper) Flush ¶
Flush returns the newline a held lone CR owes and clears the pending state. It is what makes a transcript that ended with "\r" still close its last line.
type Transcript ¶
type Transcript struct {
// contains filtered or unexported fields
}
Transcript is the de-ANSI'd text record of one pty session, written to <result_dir>/pty.txt (PTY-01 §四): an interactive job's pty output never reaches stdout.log, so this file is the only durable text an operator (or `job logs`) can read after the TUI is gone.
The retained text is bounded by maxBytes (pty.transcript_max_bytes, default 4MB): the ring keeps the TAIL and the file is compacted down to it, so a long-running TUI transcript stays readable rather than growing without bound. Writes append only what is new (recording must stay cheap); a compaction — the one operation that rewrites the file — happens at most once per maxBytes/4 written bytes, so the file is bounded at maxBytes*1.25 while over the cap.
It is safe for concurrent use, but the relay only ever writes it from the recorder goroutine and closes it from finish().
func NewTranscript ¶
func NewTranscript(path string, maxBytes int) *Transcript
NewTranscript opens no file: the sink is created lazily on the first flush, so a pty session that never produces output leaves no empty pty.txt behind. maxBytes <= 0 falls back to DefaultTranscriptMaxBytes.
func (*Transcript) Close ¶
func (t *Transcript) Close() error
Close flushes the tail and seals the file. Idempotent: the relay's finish and an explicit teardown may both call it.
func (*Transcript) Err ¶
func (t *Transcript) Err() error
Err reports the first write/close error, if any.
func (*Transcript) Path ¶
func (t *Transcript) Path() string
Path is the file the transcript is written to.
func (*Transcript) Tail ¶
func (t *Transcript) Tail() []byte
Tail returns the retained (de-ANSI'd) transcript tail — what the file holds after the cap, and what the session-id capture re-scans at close.
func (*Transcript) Write ¶
func (t *Transcript) Write(p []byte) (int, error)
Write strips p and records the result: the ring keeps the tail (the bounded transcript), the pending buffer feeds the next flush. The returned n is the number of RAW bytes consumed — the relay's recorder treats this like the cast sink, so a short write would be lost output.
type Viewer ¶
type Viewer struct {
// contains filtered or unexported fields
}
Viewer is one attached consumer of the session. Output arrives on Out(); SendInput forwards stdin bytes to the source ONLY if this viewer holds the write lease.
func (*Viewer) Close ¶
func (v *Viewer) Close()
Close detaches the viewer (releases the lease if held).
func (*Viewer) HoldsLease ¶
HoldsLease reports whether this viewer currently holds the exclusive input write lease. The transport uses it to gate resize the same way SendInput gates stdin (tools-3xy R3): only the writer may change the shared pty size.
func (*Viewer) Lagged ¶
Lagged reports whether this viewer has dropped at least one chunk because its queue was full (a slow-consumer signal the transport uses to disconnect it).
func (*Viewer) Out ¶
Out is the viewer's bounded output stream (LIVE output only — the pre-attach scrollback is a separate, non-droppable buffer: see Replay). It is closed when the viewer is removed or the relay closes.
func (*Viewer) Replay ¶
Replay returns the pre-attach scrollback this viewer must render before its Out() stream (K6): the ring's tail as of the moment the viewer was registered. The transport writes it once, then pumps Out(); because the snapshot and the registration share one lock, no byte can be both replayed and streamed — the duplication that made an attached TUI redraw the lines it was already showing (h-aii-rx9a).
func (*Viewer) SendInput ¶
SendInput forwards raw stdin bytes to the source. Only the write-lease holder may write; a read-only follower is refused (K3).
func (*Viewer) SetSizeListener ¶
SetSizeListener registers fn to be called (on its own goroutine) after every successful Resize, with the new pty size. One listener per viewer; nil clears.