tmux_server (libtmux for Erlang v0.0.1)
View SourceOpen tmux endpoints and execute explicit command values.
open/1 validates an absolute socket path and the
executable/server versions. It never creates a tmux server or attaches a
control client. Each command rechecks the observed Linux process incarnation
before dispatch. Replacement between that observation and a later client
connection remains possible; same_connection requests are rejected until
persistent dispatch qualifies.
start_owned/1 creates a separate private daemon and returns an ownership
token for stop_owned/1. The ownership guide explains caller
death, application shutdown and namespace cleanup.
Use with_server/2 or with_owned/2 for a callback scope. They attempt cleanup
after its return or exception and preserve both outcomes if cleanup fails.
The calling process owns the endpoint. close/1 cancels queued
work, retires its one-shot clients and preserves the borrowed server. Cleanup
failure remains explicit and keeps the supervised owner alive. Successful close is
idempotent during the 60-second handle retention period. Separate
tmux_control attachments receive an invalidation notice and begin their
own retirement. Close those attachments explicitly to prove their native
cleanup. Command results preserve stdout, stderr and status; cancellation
after dispatch cannot undo
remote effects. Clients explicitly select tmux's UTF-8 mode so Unicode and the
identity probe's tab do not depend on the caller's locale. Command-specific
escaping still applies to raw command output.
Use snapshot/1 to capture a graph for tmux_snapshot and
tmux_select. Use tmux_operation for non-blocking submission and
explicit waits; the job guide explains ownership and cleanup.
Summary
Types
Capture bounds, hydration strategy and consistency request. Atomic capture is unsupported.
Command options: deadline_ms defaults to 2500, max_stdout to 1 MiB, max_stderr to 64 KiB, stdin to an empty binary and identity to observed. The deadline includes admission, preflight and execution. stdin is limited to 256 KiB; stdin plus the rendered argument reservation must also fit 256 KiB. Each endpoint admits at most 64 operations and 256 KiB of command payload; exhaustion returns busy. same_connection is recognized but unsupported.
Capture text/bytes with one framed scan per entity (batched, the default), or
one field per physical row (isolated). Both retain complete graph coverage and
interval semantics. Each command has the same 1 MiB stdout bound; isolated
can distribute large entity output across commands at greater source cost.
See snapshot/2 and tmux_query:explain/1.
An explicit absolute socket endpoint and optional absolute tmux executable path.
Owned startup options. The finite startup budget defaults to 2500 milliseconds.
Opaque ownership token for stop_owned/1. An ordinary endpoint or row origin
does not convey this token. Trusted code can pass it to another process.
Both callback and cleanup evidence when a scope cannot prove retirement.
primary is the callback value or its exception class, reason and original
stack. cleanup preserves the operational error or a separate cleanup
exception. server permits close/1 reconciliation; owned scopes also include
ownership for stop_owned/1. Retain these handles until cleanup is resolved.
Endpoint resource summary. owner is the supervised endpoint process, not its initiating caller. operations and command_bytes count active admission leases; active_bytes reserves output capacity. Retired results are bounded separately by retained_results and result_bytes. These are accounting limits, not VM heap measurements. generation identifies this endpoint handle's lifetime.
A supervised borrowed-endpoint handle bound to an owner generation and admission state.
Functions
Explicitly read current fields from this server and register the new value.
For sessions, physical windows and panes, the read uses the stable ID and
discards the supplied field observations. This explicit call accepts an edited
target; ordinary actions require its captured target association to match
and reject mismatches before dispatch. The returned row carries a new private
observation association; see tmux_model. It provides no atomic identity
check. Window-link binding checks its session/index and expected physical
window. A replaced or missing membership returns stale_link. This observed
preflight does not make a later action atomic.
Retire this endpoint's operations and one-shot clients, preserving the borrowed
tmux server. Returns ok only after their cleanup completes; incomplete cleanup
remains an explicit error. Closing an already closed retained handle is
idempotent. The initiator controls endpoint lifetime. Separate control
attachments are invalidated and asked to retire; use tmux_control:close/1
before this call to verify those clients' cleanup too.
Execute one validated command and await its result. Performs I/O. The result
preserves stdout, stderr, exit status and cleanup certainty. Use
tmux_operation:start/3 to submit without blocking this caller. A timeout or
cancellation cannot reverse effects that may already have reached tmux.
Values from domain command builders keep their captured endpoint origin.
Another endpoint returns different_owner with submitted = false before any
native preflight or execution. Raw commands do not carry that origin.
Open a borrowed socket endpoint and start its supervised library owner. The caller owns that handle. This probes the executable, daemon version and observed Linux process incarnation; it never starts a tmux server or attaches a control client. Pass an absolute socket_path and optionally an executable.
Return the registered opaque origin for this open endpoint. The token provides library provenance and generation checks, not authorization against trusted Erlang code. It is not a portable identifier.
Capture a complete immutable graph with default capture limits. Performs I/O.
See snapshot/2 for bounds, consistency and conflict errors.
Capture the server's sessions, physical windows, window links and panes.
Start an empty owned daemon in a fresh private Linux socket directory. Performs
I/O and waits for bounded startup; no session or attached observer is created.
Returns an ordinary endpoint and a separate ownership/0 token. The caller
owns the daemon lifetime: caller death or stop_owned/1 retires its helper tree.
close/1 only closes the endpoint and preserves the daemon.
Read the endpoint owner's lifecycle and resource summary. This contacts the library owner, not tmux, and does not refresh captured rows.
Stop the daemon and endpoint associated with a ownership/0 token. Performs
I/O and returns ok only after endpoint/client/helper retirement and namespace
cleanup are proved. It never sends kill-server to a socket path.
Return the daemon version observed when the endpoint opened. This reads owner state and does not execute a fresh version command or qualify another tmux release.
Start an owned daemon, run a callback in the calling process, then stop it.
Performs start_owned/1 and token-based stop_owned/1 around the callback.
With successful cleanup, returns {ok, Value} or re-raises the original callback
exception. A returned error tuple is an ordinary callback value. Startup
failure passes through without invoking the callback.
Types
-type capture_options() :: #{deadline_ms => 1..600000, max_rows => 1..65536, max_bytes => 1..67108864, hydration => hydration(), consistency => observed | atomic}.
Capture bounds, hydration strategy and consistency request. Atomic capture is unsupported.
-type command_options() :: #{deadline_ms => 1..600000, max_stdout => 0..1048576, max_stderr => 0..65536, stdin => binary(), identity => observed | same_connection}.
Command options: deadline_ms defaults to 2500, max_stdout to 1 MiB, max_stderr to 64 KiB, stdin to an empty binary and identity to observed. The deadline includes admission, preflight and execution. stdin is limited to 256 KiB; stdin plus the rendered argument reservation must also fit 256 KiB. Each endpoint admits at most 64 operations and 256 KiB of command payload; exhaustion returns busy. same_connection is recognized but unsupported.
-type hydration() :: batched | isolated.
Capture text/bytes with one framed scan per entity (batched, the default), or
one field per physical row (isolated). Both retain complete graph coverage and
interval semantics. Each command has the same 1 MiB stdout bound; isolated
can distribute large entity output across commands at greater source cost.
See snapshot/2 and tmux_query:explain/1.
An explicit absolute socket endpoint and optional absolute tmux executable path.
-type owned_options() :: #{executable => binary(), startup_timeout_ms => 1..600000}.
Owned startup options. The finite startup budget defaults to 2500 milliseconds.
-opaque ownership()
Opaque ownership token for stop_owned/1. An ordinary endpoint or row origin
does not convey this token. Trusted code can pass it to another process.
-type scope_failure() :: #{code := scope_cleanup_failed, primary := {ok, term()} | {exception, error | exit | throw, term(), erlang:stacktrace()}, cleanup := {error, map()} | {exception, error | exit | throw, term(), erlang:stacktrace()}, server := t(), ownership => ownership()}.
Both callback and cleanup evidence when a scope cannot prove retirement.
primary is the callback value or its exception class, reason and original
stack. cleanup preserves the operational error or a separate cleanup
exception. server permits close/1 reconciliation; owned scopes also include
ownership for stop_owned/1. Retain these handles until cleanup is resolved.
-type state() :: #{phase := open | closing | closed, generation := reference(), owner := pid(), operations := non_neg_integer(), command_bytes := non_neg_integer(), active_bytes := non_neg_integer(), retained_results := non_neg_integer(), result_bytes := non_neg_integer()}.
Endpoint resource summary. owner is the supervised endpoint process, not its initiating caller. operations and command_bytes count active admission leases; active_bytes reserves output capacity. Retired results are bounded separately by retained_results and result_bytes. These are accounting limits, not VM heap measurements. generation identifies this endpoint handle's lifetime.
-opaque t()
A supervised borrowed-endpoint handle bound to an owner generation and admission state.
Functions
-spec bind(t(), tmux_model:row()) -> {ok, tmux_model:row()} | {error, map()}.
Explicitly read current fields from this server and register the new value.
For sessions, physical windows and panes, the read uses the stable ID and
discards the supplied field observations. This explicit call accepts an edited
target; ordinary actions require its captured target association to match
and reject mismatches before dispatch. The returned row carries a new private
observation association; see tmux_model. It provides no atomic identity
check. Window-link binding checks its session/index and expected physical
window. A replaced or missing membership returns stale_link. This observed
preflight does not make a later action atomic.
Invalid rows are rejected before I/O:
1> tmux_server:bind(invalid_server, invalid_row).
{error,#{code => invalid_row,path => []}}
Retire this endpoint's operations and one-shot clients, preserving the borrowed
tmux server. Returns ok only after their cleanup completes; incomplete cleanup
remains an explicit error. Closing an already closed retained handle is
idempotent. The initiator controls endpoint lifetime. Separate control
attachments are invalidated and asked to retire; use tmux_control:close/1
before this call to verify those clients' cleanup too.
-spec command(t(), tmux_command:t(), command_options()) -> {ok, tmux_operation:completed()} | {error, tmux_operation:failure()}.
Execute one validated command and await its result. Performs I/O. The result
preserves stdout, stderr, exit status and cleanup certainty. Use
tmux_operation:start/3 to submit without blocking this caller. A timeout or
cancellation cannot reverse effects that may already have reached tmux.
Values from domain command builders keep their captured endpoint origin.
Another endpoint returns different_owner with submitted = false before any
native preflight or execution. Raw commands do not carry that origin.
-spec open(open_options()) -> {ok, t()} | {error, map()}.
Open a borrowed socket endpoint and start its supervised library owner. The caller owns that handle. This probes the executable, daemon version and observed Linux process incarnation; it never starts a tmux server or attaches a control client. Pass an absolute socket_path and optionally an executable.
Return the registered opaque origin for this open endpoint. The token provides library provenance and generation checks, not authorization against trusted Erlang code. It is not a portable identifier.
-spec snapshot(t()) -> {ok, tmux_snapshot:t()} | {error, map()}.
Capture a complete immutable graph with default capture limits. Performs I/O.
See snapshot/2 for bounds, consistency and conflict errors.
-spec snapshot(t(), capture_options()) -> {ok, tmux_snapshot:t()} | {error, map()}.
Capture the server's sessions, physical windows, window links and panes.
This performs explicit I/O and records each command's observation interval. Identity scans bracket field reads; detected topology or value disagreements return inconsistent_capture. Changes between reads can remain undetected, including changes followed by a reversal. Atomic capture is unsupported.
Options are consistency (observed only), deadline_ms (default 2500, maximum
600000), max_rows (4096, maximum 65536 raw observations per scan and aggregate
spine) and max_bytes (8 MiB, maximum 64 MiB total stdout across capture
commands). Repeated memberships count before deduplication. The
hydration/0 strategy defaults to batched. Each command is limited to 1 MiB;
isolated hydration distributes larger entity output across individual fields.
These are data limits, not a VM heap limit. Capturing performs no retry. Local
reads of the resulting value do no I/O. tmux_snapshot:metadata/1 records the
strategy and actual source calls.
Unsupported consistency is rejected before contacting a server:
1> tmux_server:snapshot(invalid_server, #{consistency => atomic}).
{error,#{code => unsupported_consistency}}
-spec start_owned(owned_options()) -> {ok, t(), ownership()} | {error, map()}.
Start an empty owned daemon in a fresh private Linux socket directory. Performs
I/O and waits for bounded startup; no session or attached observer is created.
Returns an ordinary endpoint and a separate ownership/0 token. The caller
owns the daemon lifetime: caller death or stop_owned/1 retires its helper tree.
close/1 only closes the endpoint and preserves the daemon.
The daemon starts without a user config, with exit-empty disabled. One idle,
unattached bootstrap client keeps the owned helper tree alive. Startup includes
readiness and endpoint incarnation binding, not just executable launch.
Incomplete cleanup remains explicit; it is never permission to kill by path.
An incomplete startup error includes an ownership token and captured resources
for stop_owned/1 recovery. The token does not serialize across VM lifetimes.
-spec status(t()) -> {ok, state()} | {error, tmux_operation:failure()}.
Read the endpoint owner's lifecycle and resource summary. This contacts the library owner, not tmux, and does not refresh captured rows.
Stop the daemon and endpoint associated with a ownership/0 token. Performs
I/O and returns ok only after endpoint/client/helper retirement and namespace
cleanup are proved. It never sends kill-server to a socket path.
A replaced socket/directory or unexpected directory contents are preserved and
return cleanup_incomplete with process and namespace details. A supervised
tombstone retains uncertain cleanup; call again to inspect/retry after external
repair. Filesystem identity checks are observations, not atomic reservations
against another trusted process replacing a path during unlink.
Successful stop is idempotent during the 60-second token retention period.
After token expiry or application shutdown, returns ownership_expired.
Stop explicitly before application shutdown when the caller needs a verified
cleanup result. OTP application shutdown itself does not prove native cleanup.
Incomplete shutdown writes a private recovery report outside the owned socket
directory and logs its location or write failure; no automatic recovery runs.
-spec version(t()) -> {ok, tmux_version:t()} | {error, map()}.
Return the daemon version observed when the endpoint opened. This reads owner state and does not execute a fresh version command or qualify another tmux release.
-spec with_owned(owned_options(), fun((t()) -> Value)) -> {ok, Value} | {error, scope_failure() | map()}.
Start an owned daemon, run a callback in the calling process, then stop it.
Performs start_owned/1 and token-based stop_owned/1 around the callback.
With successful cleanup, returns {ok, Value} or re-raises the original callback
exception. A returned error tuple is an ordinary callback value. Startup
failure passes through without invoking the callback.
Cleanup failure returns scope_failure/0, including both server and ownership
handles for inspection and an explicit stop retry. It preserves the callback
outcome and cleanup evidence separately; it never claims timeout is retirement.
See with_server/2 for callback and separately allocated resource obligations.
-spec with_server(open_options(), fun((t()) -> Value)) -> {ok, Value} | {error, scope_failure() | map()}.
Open a borrowed endpoint, run a callback in the calling process, then close it.
Performs the same I/O as open/1 and close/1; the borrowed daemon survives.
Startup failure passes through without invoking the callback.
With successful cleanup, returns {ok, Value} for any callback return value,
including a returned error tuple. Callback error, throw and exit exceptions
are re-raised with their original reason and stack. If cleanup fails, returns
{error, Failure} with scope_failure/0, preserving both outcomes and the
endpoint for explicit recovery. It attempts cleanup once; a timeout does not
prove retirement. Existing supervised cleanup ownership remains in force.
The callback must retire separately created resources such as tmux_control
attachments. This scope closes its endpoint, not every resource the callback
may allocate. Use with_owned/2 when the scope should own the daemon too.