LibTmux.Control (libtmux v0.1.3)

Copy Markdown View Source

A qualified control connection for scoped and managed execution.

Start with with_connection/2 to own startup and cleanup around a callback. Use execute/3 to obtain a command outcome after wire retirement and record reclamation. Canonical :failed, :skipped and :unknown outcomes remain values, including from bang functions; acknowledgement does not prove external program completion. See the managed control guide.

A successful scope returns {:ok, callback_value} after proven cleanup. LibTmux.Control.ScopeFailure preserves the callback outcome when cleanup fails. LibTmux.Control.ExecutionError carries the operation handle and recovery context for errors after admission.

Starting a connection explicitly attaches to an existing session. The host must qualify effective hooks, aliases and stream writers for its lifetime; lane: :host_qualified declares that work without performing it. Each handle stays pinned to one epoch. Pinning does not authenticate unqualified output or defend against arbitrary writes to internal tables. Local selections never attach, and commands never replay, refresh or change transport.

For independently retained results, use submit/3 and LibTmux.Operation. Awaiting a retained result does not reclaim its record. See the advanced execution guide for explicit ownership. request_close/1 closes write authority for the entire epoch through reserved capacity; it neither proves retirement nor rolls back effects.

Summary

Types

A positive millisecond budget shared by all stages of one lifecycle or submission call.

A pinned epoch's current phase, identity and terminal evidence; retirement and unknown cleanup are distinct.

Startup options plus a separate cleanup allowance of 1..950ms, default 950ms; callback duration has no library timer.

Explicit attachment policy and bounded startup settings; capacities count slots and timeouts use milliseconds.

t()

A handle pinned to one owner and connection epoch; it never follows a replacement.

An observed close reason, its error phase and at most 8192 captured stderr bytes; not proof of effects or complete stderr.

Functions

Builds a permanent supervisor child spec without attaching.

Requests closure and waits for proven retirement of the pinned epoch.

Waits for retirement or raises the same structured error.

Executes one qualified request, returning its result after wire retirement and record reclamation. Repeated successful calls need no manual forget.

Executes and reclaims as in execute/3; raises API/context errors, preserving canonical failures as values.

Explicitly obtains the ready epoch, starting a replacement only after retirement.

Obtains the ready epoch or raises the same structured error.

Requests whole-epoch closure without claiming an operation or metadata slot.

Requests epoch closure or raises the same structured error.

Starts a linked connection and returns {:ok, root, control}.

Reads the pinned epoch's phase, identity and terminal diagnostics without I/O.

Reads pinned connection status or raises the same structured error.

Admits one request and returns its retained operation handle.

Admits a request or raises the same structured error.

Runs a callback with one connection and owns its native and supervisor cleanup.

Types

call_option()

@type call_option() :: {:timeout, pos_integer()}

A positive millisecond budget shared by all stages of one lifecycle or submission call.

connection_status()

@type connection_status() :: %{
  epoch: reference() | nil,
  generation: non_neg_integer(),
  phase: :starting | :ready | :closing | :retired | :unknown,
  instance: String.t() | nil,
  terminal: terminal_diagnostic() | nil | :unavailable
}

A pinned epoch's current phase, identity and terminal evidence; retirement and unknown cleanup are distinct.

scope_option()

@type scope_option() :: start_option() | {:cleanup_timeout, 1..950}

Startup options plus a separate cleanup allowance of 1..950ms, default 950ms; callback duration has no library timer.

start_option()

@type start_option() ::
  {:server, LibTmux.Server.t()}
  | {:session, {:existing, String.t()}}
  | {:lane, :host_qualified}
  | {:timeout, 1..600_000}
  | {:capacity | :metadata_capacity | :waiter_capacity, 1..256}
  | {:retention_ms, 1..600_000}

Explicit attachment policy and bounded startup settings; capacities count slots and timeouts use milliseconds.

t()

@opaque t()

A handle pinned to one owner and connection epoch; it never follows a replacement.

terminal_diagnostic()

@type terminal_diagnostic() :: %{reason: atom(), phase: atom(), stderr: binary()}

An observed close reason, its error phase and at most 8192 captured stderr bytes; not proof of effects or complete stderr.

Functions

child_spec(options)

@spec child_spec([start_option()]) :: Supervisor.child_spec()

Builds a permanent supervisor child spec without attaching.

Prepares bounded detached inputs and one lifetime shared by all factory invocations. Each invocation starts its own configured startup budget. A restarted nonfresh lifetime returns an inert handle and never attaches automatically. Proven retirement permits explicit reconnect/2; unknown cleanup refuses it. Old handles never follow a replacement Root or Manager.

Supervisor.start_child/2 and Supervisor.restart_child/2 return the new handle as their third info element. After an automatic restart, use Supervisor.terminate_child/2 followed by Supervisor.restart_child/2 for fresh info. This does not clear unknown cleanup or authorize replay.

See the worked example.

close(control, options \\ [])

@spec close(t(), [call_option()]) :: :ok | {:error, LibTmux.Error.t()}

Requests closure and waits for proven retirement of the pinned epoch.

timeout defaults to 5000ms. The original budget includes validation and retirement waiting. Closure still happens if the bounded metadata wait cannot be admitted. Timeout, overload or lost ownership reports unknown certainty; it never proves cleanup. :ok requires known native and actor retirement.

The connection supervisor and retained records remain available for explicit reconnect and inspection. This does not stop the supervisor or roll back sibling effects.

See the worked example.

close!(control, options \\ [])

@spec close!(t(), [call_option()]) :: :ok

Waits for retirement or raises the same structured error.

See the worked example.

execute(control, request, options \\ [])

Executes one qualified request, returning its result after wire retirement and record reclamation. Repeated successful calls need no manual forget.

The default 5000ms budget covers preparation, admission, execution and collection. Failed, skipped and unknown canonical outcomes remain values; acknowledgement does not establish external program completion.

Pre-admission errors have no-write certainty. An error after admission is a LibTmux.Control.ExecutionError with the exact Operation and retained or lost context. Inspect that handle when available; never replay on timeout. The original caller owns recovery: its death permits reclamation after wire retirement, even if it passed the handle to another process. A live caller's timeout leaves the record subject to normal retention and explicit forget. Operation.status/1 and Operation.result/1 inspect it without a waiter. A new await needs its own slot; the expired collector releases its slot asynchronously when the owner processes closure. Use submit/3 when a retained handle is required after successful waiting.

alias LibTmux.Control

Control.execute(control, LibTmux.Control.Request.field("pid"))

execute!(control, request, options \\ [])

Executes and reclaims as in execute/3; raises API/context errors, preserving canonical failures as values.

See the worked example.

reconnect(control, options \\ [])

@spec reconnect(t(), [call_option()]) :: {:ok, t()} | {:error, LibTmux.Error.t()}

Explicitly obtains the ready epoch, starting a replacement only after retirement.

A ready epoch returns itself. Call close/2 first to require replacement. The default 5000ms budget covers metadata admission, retirement and startup. A successful reply pins the acknowledged endpoint even if it becomes stale before this caller resumes. It never follows a later view or replays work. Errors report unknown certainty about existing effects. Attachment counts include the control client; reconnect can attach one replacement client.

See the worked example.

reconnect!(control, options \\ [])

@spec reconnect!(t(), [call_option()]) :: t()

Obtains the ready epoch or raises the same structured error.

See the worked example.

request_close(control)

@spec request_close(t()) :: :ok | {:error, LibTmux.Error.t()}

Requests whole-epoch closure without claiming an operation or metadata slot.

Repeated requests for the same closing or proven-retired generation return :ok. Success is a request or previously known retirement, not a cleanup acknowledgement. A replacement Manager or epoch is never followed.

See the worked example.

request_close!(control)

@spec request_close!(t()) :: :ok

Requests epoch closure or raises the same structured error.

See the worked example.

start_link(options)

@spec start_link([start_option()]) :: {:ok, pid(), t()} | {:error, LibTmux.Error.t()}

Starts a linked connection and returns {:ok, root, control}.

Require server: %LibTmux.Server{}, session: {:existing, "$id"} and lane: :host_qualified. No session is created. The attachment is visible in tmux's client counts and can update session state. no-output,ignore-size suppresses pane output and excludes this client from window sizing.

timeout defaults to 5000ms and accepts 1..600000ms. One budget covers input preparation, Root startup, bootstrap, ready waiting and handoff. A fresh factory returns a ready handle. Runtime failures return a structured error; invalid trusted options raise ArgumentError. Ordinary OTP links remain: an asynchronous fatal Root exit can terminate a non-trapping caller.

Failed startup fences its lifetime and requests exact-Root cleanup. Error details distinguish observed Root exit from a kill request; unknown native cleanup is never success. OTP can await Root exit after its initialization timer expires, so a strict wall-clock caller-return bound remains unqualified.

Optional capacity, metadata_capacity and waiter_capacity default to 32 and accept 1..256. retention_ms defaults to 60000 and accepts 1..600000.

Ready connections buffer at most 64 KiB or 128 stdout chunks behind the reader. Overflow closes the whole epoch with resource_limit; it never replays commands. These receive limits do not cap borrowed-server memory.

See the worked example.

status(control)

@spec status(t()) :: {:ok, connection_status()} | {:error, LibTmux.Error.t()}

Reads the pinned epoch's phase, identity and terminal diagnostics without I/O.

terminal is nil before a terminal report, or :unavailable when the report is missing or an ended epoch has no report. A report contains reason, its error phase and at most 8192 raw stderr bytes. Empty stderr means no bytes were captured; the buffer may be incomplete and need not be UTF-8. It can contain application data and is never logged automatically.

A terminal report can coexist with :closing or unknown cleanup. Its reason is an observed cause, not necessarily the original cause, and does not alter operation outcomes. Status fields are separate observations, not an atomic snapshot. A replacement epoch starts without the old report; old handles remain stale. Losing the status owner returns the existing context error.

See the worked example.

status!(control)

@spec status!(t()) :: connection_status()

Reads pinned connection status or raises the same structured error.

See the worked example.

submit(control, request, options \\ [])

@spec submit(t(), LibTmux.Control.Request.t(), [call_option()]) ::
  {:ok, LibTmux.Operation.t()} | {:error, LibTmux.Error.t()}

Admits one request and returns its retained operation handle.

timeout defaults to 5000ms and covers validation, admission, queueing, writes and replies under one monotonic deadline. Request binaries are detached before publication. Invalid input, overload or stale context before admission returns a no-write error. Every successful admission returns its Operation, even if its context disappears before publication. Inspect that handle for the eventual canonical result or an explicit lost-context error.

Closing the connection can affect sibling operations. Command replies do not prove external program exit. Caller timeout does not authorize replay.

See the worked example.

submit!(control, request, options \\ [])

Admits a request or raises the same structured error.

See the worked example.

with_connection(options, callback)

@spec with_connection([scope_option()], (t() -> value)) ::
  {:ok, value}
  | {:error, LibTmux.Error.t() | LibTmux.Control.ScopeFailure.t(value)}
when value: var

Runs a callback with one connection and owns its native and supervisor cleanup.

Takes the explicit server, existing session and host qualification options from start_link/1. The callback runs in the calling process. Its duration is separate from startup and cleanup_timeout (default 950ms). A dedicated connection owner also requests cleanup when that caller dies.

Returns {:ok, value} after proven connection retirement and Root exit. Cleaned-up exceptions, throws and exits are re-raised with their original stacktrace. If cleanup fails, returns {:error, ScopeFailure} containing the callback's original value or exception and separate cleanup evidence. Startup failures return {:error, Error}; invalid options raise.

The control handle is scoped to the callback. Explicit reconnect is allowed inside it; cleanup permanently fences new epochs and retires the current one. Escaped handles cannot reconnect after the scope. Startup retains start_link/1's OTP initialization limitation; a timeout can report unknown cleanup while its owner is still unwinding startup. It does not promise a hard native process-exit deadline.

alias LibTmux.Control

Control.with_connection(options, fn control ->
  Control.execute(control, LibTmux.Control.Request.field("pid"))
end)