session

package
v0.0.0-...-264c7d8 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package session provides distributed terminal session lifecycle, CRDT-based state synchronization, and cross-node migration.

Index

Constants

View Source
const CRDTCheckpointVersion uint32 = 2

CRDTCheckpointVersion distinguishes CRDT-payload checkpoints from session-payload (migratableState) checkpoints so that Restore and RestoreCRDT fail fast when handed the wrong kind.

View Source
const CheckpointVersion uint32 = 1

CheckpointVersion is the on-the-wire format version for a session Checkpoint. Bump it whenever the serialized layout changes in a way that older Restore implementations cannot interpret. Restore rejects any snapshot whose Version it does not recognize.

Variables

View Source
var (
	// ErrCheckpointMagic is returned when the snapshot does not carry the
	// checkpoint magic prefix (not a Checkpoint, or truncated header).
	ErrCheckpointMagic = errors.New("session: not a checkpoint snapshot (bad magic)")
	// ErrCheckpointVersion is returned when the snapshot version is not
	// understood by this build.
	ErrCheckpointVersion = errors.New("session: unsupported checkpoint version")
	// ErrCheckpointChecksum is returned when the payload checksum does not
	// match the recorded checksum (tampered / corrupted snapshot).
	ErrCheckpointChecksum = errors.New("session: checkpoint checksum mismatch")
	// ErrCheckpointDecode is returned when the payload cannot be decoded.
	ErrCheckpointDecode = errors.New("session: checkpoint payload decode failed")
)

Sentinel errors for Restore failures so callers can branch on cause.

Functions

This section is empty.

Types

type BackendAdapter

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

BackendAdapter adapts a pkg/session/backends.Backend (the low-level tmux / native-PTY interface) to the pkg/session.TmuxBackend interface consumed by Manager. This is the bridge that eliminates the nil-backend StatusRunning bluff: when a real backends.Backend is wired in, Manager.Create actually starts a process and SessionExists can verify it.

Only operations that backends.Backend exposes are forwarded to the real implementation; operations with no direct equivalent (window management, state save/restore) are fulfilled via direct tmux shell-out so the Manager still has a complete interface implementation.

func NewBackendAdapter

func NewBackendAdapter(be backends.Backend) *BackendAdapter

NewBackendAdapter wraps be in a BackendAdapter.

func (*BackendAdapter) AttachSession

func (a *BackendAdapter) AttachSession(name string) error

AttachSession delegates to the backend's Attach (we open and immediately close the stream — Manager.Attach is a side-effectful marker, not a long-running read/write loop at this level).

func (*BackendAdapter) CapturePane

func (a *BackendAdapter) CapturePane(sessionName, pane string) (string, error)

CapturePane returns visible content of a pane.

func (*BackendAdapter) CreateSession

func (a *BackendAdapter) CreateSession(name string, env map[string]string) (string, error)

CreateSession creates a detached tmux session via the wrapped backend. env is applied as KEY=VALUE pairs passed to the shell command.

func (*BackendAdapter) CreateWindow

func (a *BackendAdapter) CreateWindow(sessionName, windowName string) (string, error)

CreateWindow creates a new window inside the named session. Delegated via direct tmux call because backends.Backend has no window API.

func (*BackendAdapter) DetachSession

func (a *BackendAdapter) DetachSession(name string) error

DetachSession delegates to the backend.

func (*BackendAdapter) GetSessionState

func (a *BackendAdapter) GetSessionState(sessionName string) ([]byte, error)

GetSessionState serializes session state via tmux show-environment.

func (*BackendAdapter) KillSession

func (a *BackendAdapter) KillSession(name string) error

KillSession delegates to the backend.

func (*BackendAdapter) ListSessions

func (a *BackendAdapter) ListSessions() ([]string, error)

ListSessions returns the names of all active sessions from the backend.

func (*BackendAdapter) ResizePane

func (a *BackendAdapter) ResizePane(sessionName, pane string, rows, cols int) error

ResizePane resizes a pane.

func (*BackendAdapter) RestoreSessionState

func (a *BackendAdapter) RestoreSessionState(sessionName string, state []byte) error

RestoreSessionState restores session state via tmux set-environment.

func (*BackendAdapter) SendKeys

func (a *BackendAdapter) SendKeys(sessionName, pane string, keys string) error

SendKeys sends keystrokes to the session/pane.

func (*BackendAdapter) SessionExists

func (a *BackendAdapter) SessionExists(name string) (bool, error)

SessionExists reports whether a session with the given name is alive in the underlying backend. This is the sink-side probe used by unit tests and health checks to prove a real process was launched.

func (*BackendAdapter) SplitWindow

func (a *BackendAdapter) SplitWindow(sessionName, windowName string) (string, error)

SplitWindow splits a window in the named session.

type CRDTPane

type CRDTPane struct {
	ID         string
	Command    string
	WorkingDir string
	Status     PaneStatus
	Version    uint64
}

CRDTPane represents a pane in CRDT form.

type CRDTSessionState

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

CRDTSessionState is a CRDT-based session state container. Uses a simple LWW (Last-Write-Wins) register for now.

func FromBytes

func FromBytes(data []byte) (*CRDTSessionState, error)

FromBytes deserializes CRDT state.

func NewCRDTSessionState

func NewCRDTSessionState() *CRDTSessionState

NewCRDTSessionState creates an empty CRDT state.

func (*CRDTSessionState) Clone

func (c *CRDTSessionState) Clone() *CRDTSessionState

Clone returns a deep, independent copy of the CRDT state.

func (*CRDTSessionState) Fingerprint

func (c *CRDTSessionState) Fingerprint() string

Fingerprint returns a deterministic, content-only canonical string of the observable replica state. Two replicas with the same fingerprint hold the same shared state; the internal `version` counter is intentionally excluded.

func (*CRDTSessionState) GetPane

func (c *CRDTSessionState) GetPane(windowID, paneID string) (*CRDTPane, bool)

GetPane returns a pane by window and pane ID.

func (*CRDTSessionState) GetWindow

func (c *CRDTSessionState) GetWindow(id string) (*CRDTWindow, bool)

GetWindow returns a window by ID.

func (*CRDTSessionState) Merge

func (c *CRDTSessionState) Merge(other *CRDTSessionState) error

Merge merges another CRDT state (LWW semantics).

func (*CRDTSessionState) ToBytes

func (c *CRDTSessionState) ToBytes() ([]byte, error)

ToBytes serializes the CRDT state.

func (*CRDTSessionState) UpdatePane

func (c *CRDTSessionState) UpdatePane(windowID string, p *CRDTPane)

UpdatePane updates or creates a pane within a window.

func (*CRDTSessionState) UpdateWindow

func (c *CRDTSessionState) UpdateWindow(w *CRDTWindow)

UpdateWindow updates or creates a window.

type CRDTWindow

type CRDTWindow struct {
	ID      string
	Name    string
	Layout  string
	Panes   map[string]*CRDTPane
	Version uint64
}

CRDTWindow represents a window in CRDT form.

type Checkpoint

type Checkpoint struct {
	Magic    [4]byte  // format guard, must equal checkpointMagic
	Version  uint32   // CheckpointVersion at write time
	Checksum [32]byte // sha256(Version-bytes || Data)
	Data     []byte   // gob-encoded migratableState payload (opaque)
}

Checkpoint is an opaque, versioned, self-validating snapshot of a session's migratable state. It is the pure-Go state-only migration unit: serialize on the source with NewCheckpoint, ship the bytes, Restore on the target.

The snapshot is "opaque" to callers: they should treat Data as bytes and not reach inside. Integrity is protected by a SHA-256 checksum over (Version || Data); Restore recomputes and compares it before decoding, so a single flipped bit anywhere in the body is rejected rather than silently restored.

func NewCRDTCheckpoint

func NewCRDTCheckpoint(state *CRDTSessionState) (*Checkpoint, error)

NewCRDTCheckpoint serializes a CRDTSessionState into a versioned, checksummed Checkpoint. The payload is the gob encoding produced by CRDTSessionState.ToBytes(). The CRDTCheckpointVersion (2) in the header distinguishes this from a session-state Checkpoint (version 1), so Checkpoint.Restore will reject it and RestoreCRDT will accept it.

func NewCheckpoint

func NewCheckpoint(session *Session) (*Checkpoint, error)

NewCheckpoint serializes a session's migratable state into a versioned, checksummed Checkpoint. The session is not mutated. Binary-ish payloads inside windows/panes (e.g. CRDTState, PTYPath) survive the round-trip byte-for-byte.

func UnmarshalCheckpoint

func UnmarshalCheckpoint(data []byte) (*Checkpoint, error)

UnmarshalCheckpoint parses bytes produced by Checkpoint.MarshalBinary back into a Checkpoint without yet validating or decoding the payload. Use Restore to validate integrity and obtain a Session.

func (*Checkpoint) MarshalBinary

func (c *Checkpoint) MarshalBinary() ([]byte, error)

MarshalBinary renders the Checkpoint as a single opaque byte slice suitable for shipping over the wire or persisting. The encoding is gob over the Checkpoint header + payload, so MarshalBinary/UnmarshalCheckpoint is a byte-exact round-trip of the underlying Data.

func (*Checkpoint) Restore

func (c *Checkpoint) Restore(targetNode string) (*Session, error)

Restore validates a Checkpoint (magic, version, checksum) and reconstructs the migratable Session state on the target. The returned Session carries the source's identity and migratable state; targetNode is stamped as the new NodeID and Status is set to migrating so callers can resume it locally.

Restore is the integrity gate: a wrong magic, an unknown version, or any corruption of the payload (checksum mismatch) is rejected with a specific sentinel error instead of producing a partial or zero state.

func (*Checkpoint) RestoreCRDT

func (c *Checkpoint) RestoreCRDT() (*CRDTSessionState, error)

RestoreCRDT validates a CRDT Checkpoint (magic, version, checksum) and decodes the payload into a CRDTSessionState. It is the counterpart to NewCRDTCheckpoint and rejects checkpoints created by NewCheckpoint (session version 1) or any checkpoint with a tampered header/payload.

type CreateRequest

type CreateRequest struct {
	Name          string
	Owner         string
	Backend       SessionBackend
	CPURequest    int64
	MemoryRequest int64
	GPURequest    []string
	Environment   map[string]string
	Labels        map[string]string
}

CreateRequest holds parameters for session creation.

type InvalidTransitionError

type InvalidTransitionError struct {
	From   SessionStatus
	Action lifecycleAction
}

InvalidTransitionError is returned when a lifecycle action is attempted from a state the FSM does not permit. It carries the offending from-state and action so callers (and tests) can assert precisely which guard fired, rather than pattern-matching error strings.

func (*InvalidTransitionError) Error

func (e *InvalidTransitionError) Error() string

type Manager

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

Manager handles session lifecycle operations.

func NewManager

func NewManager(tmux TmuxBackend) *Manager

NewManager creates a session manager.

func (*Manager) Attach

func (m *Manager) Attach(ctx context.Context, id SessionID, user string) error

Attach attaches to a running session.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, req *CreateRequest) (*Session, error)

Create creates a new session.

func (*Manager) Detach

func (m *Manager) Detach(ctx context.Context, id SessionID, user string) error

Detach detaches from a session.

func (*Manager) Get

func (m *Manager) Get(id SessionID) (*Session, error)

Get returns a session by ID.

func (*Manager) GetResourceUsage

func (m *Manager) GetResourceUsage(id SessionID) (*ResourceUsage, error)

GetResourceUsage returns current resource usage for a session.

func (*Manager) List

func (m *Manager) List() []*Session

List returns all sessions.

func (*Manager) ListByNode

func (m *Manager) ListByNode(nodeID string) []*Session

ListByNode returns sessions on a specific node.

func (*Manager) ListByOwner

func (m *Manager) ListByOwner(owner string) []*Session

ListByOwner returns sessions for a specific owner.

func (*Manager) Migrate

func (m *Manager) Migrate(ctx context.Context, id SessionID, targetNode string) error

Migrate initiates session migration to another node.

func (*Manager) ResizePTY

func (m *Manager) ResizePTY(ctx context.Context, id SessionID, paneID string, rows, cols int) error

ResizePTY resizes the PTY for a pane.

func (*Manager) SendInput

func (m *Manager) SendInput(ctx context.Context, id SessionID, paneID string, input string) error

SendInput sends input to a pane.

func (*Manager) Terminate

func (m *Manager) Terminate(ctx context.Context, id SessionID) error

Terminate gracefully terminates a session.

func (*Manager) Update

func (m *Manager) Update(id SessionID, fn func(*Session)) (*Session, error)

Update modifies an existing session's mutable fields.

type MigrationPlanner

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

MigrationPlanner plans and executes session migrations.

func NewMigrationPlanner

func NewMigrationPlanner() *MigrationPlanner

NewMigrationPlanner creates a planner with all strategies.

func (*MigrationPlanner) Execute

func (mp *MigrationPlanner) Execute(ctx context.Context, session *Session, targetNode string) (*MigrationResult, error)

Execute performs the full migration.

func (*MigrationPlanner) Plan

func (mp *MigrationPlanner) Plan(session *Session, targetNode string) (MigrationStrategy, error)

Plan selects the best migration strategy for a session.

type MigrationResult

type MigrationResult struct {
	Success    bool
	Duration   time.Duration
	DataSize   int64
	Method     MigrationStrategy
	SourceNode string
	TargetNode string
	Error      error
}

MigrationResult captures migration outcome.

type MigrationStrategy

type MigrationStrategy string

MigrationStrategy identifies the migration approach.

const (
	StrategyCRIU       MigrationStrategy = "criu"
	StrategyDMTCP      MigrationStrategy = "dmtcp"
	StrategyCRDT       MigrationStrategy = "crdt"       // state-only, no process
	StrategyContainer  MigrationStrategy = "container"  // container checkpoint/restore
	StrategyCheckpoint MigrationStrategy = "checkpoint" // versioned state snapshot/restore (pure-Go)
)

type MigrationStrategyImpl

type MigrationStrategyImpl interface {
	CanMigrate(session *Session) (bool, string)
	PreMigrate(ctx context.Context, session *Session, targetNode string) error
	Migrate(ctx context.Context, session *Session, targetNode string) (*MigrationResult, error)
	PostMigrate(ctx context.Context, session *Session, targetNode string) error
}

MigrationStrategyImpl is the interface for migration strategies.

type Pane

type Pane struct {
	ID          string
	Command     string
	WorkingDir  string
	Environment map[string]string
	PTYPath     string
	CPULimit    int64 // millicores
	MemoryLimit int64 // bytes
	GPUDevice   string
	Status      PaneStatus
	CRDTState   []byte
}

Pane represents a tmux pane within a window.

type PaneStatus

type PaneStatus int

PaneStatus represents the lifecycle state of a pane.

const (
	PaneRunning PaneStatus = iota
	PaneExited
	PaneFrozen
)

type ResourceUsage

type ResourceUsage struct {
	CPUMillis      int64
	MemoryBytes    int64
	GPUMemoryBytes map[string]int64 // per GPU
	NetworkRx      int64
	NetworkTx      int64
}

ResourceUsage tracks real-time resource consumption.

type Session

type Session struct {
	ID        SessionID
	Name      string
	Owner     string
	Status    SessionStatus
	Backend   SessionBackend
	NodeID    string
	CreatedAt time.Time
	UpdatedAt time.Time

	// Resources
	CPURequest    int64    // millicores
	MemoryRequest int64    // bytes
	GPURequest    []string // GPU device IDs

	// State
	Windows     []Window
	Environment map[string]string
	Labels      map[string]string
}

Session represents a distributed terminal session.

type SessionBackend

type SessionBackend string

SessionBackend identifies the terminal backend.

const (
	BackendTmux   SessionBackend = "tmux"
	BackendZellij SessionBackend = "zellij"
	BackendScreen SessionBackend = "screen"
)

type SessionID

type SessionID string

SessionID is a unique session identifier.

type SessionStatus

type SessionStatus int

SessionStatus represents the lifecycle state.

const (
	StatusPending SessionStatus = iota
	StatusCreating
	StatusRunning
	StatusMigrating
	StatusPaused
	StatusTerminated
	StatusFailed
)

func StatusFromString

func StatusFromString(s string) SessionStatus

StatusFromString parses a SessionStatus from its string representation.

func (SessionStatus) String

func (s SessionStatus) String() string

String returns the human-readable name of the status.

type TmuxBackend

type TmuxBackend interface {
	CreateSession(name string, env map[string]string) (string, error)
	AttachSession(name string) error
	DetachSession(name string) error
	KillSession(name string) error
	ListSessions() ([]string, error)
	// SessionExists reports whether a session with the given name is alive in
	// the backend. It is the sink-side probe used by tests and health checks to
	// prove a real process was launched (not merely StatusRunning in memory).
	SessionExists(name string) (bool, error)
	CreateWindow(session, name string) (string, error)
	SplitWindow(session, window string) (string, error)
	ResizePane(session, pane string, rows, cols int) error
	SendKeys(session, pane string, keys string) error
	CapturePane(session, pane string) (string, error)
	GetSessionState(session string) ([]byte, error)
	RestoreSessionState(session string, state []byte) error
}

TmuxBackend abstracts tmux operations.

type Window

type Window struct {
	ID        string
	Name      string
	Layout    string // tmux layout string
	Active    bool
	Panes     []Pane
	CRDTState []byte // serialized CRDT state
}

Window represents a tmux window within a session.

Directories

Path Synopsis
Package backends provides terminal multiplexer backend implementations for the Helix Cluster session manager.
Package backends provides terminal multiplexer backend implementations for the Helix Cluster session manager.

Jump to

Keyboard shortcuts

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