Current section
Files
Jump to
Current section
Files
docs/advanced-execution.md
# Advanced: inspect both transports and own a retained operation
This example inspects a retained operation before and after closing its connection. For
routine work, start with [capture and filter](first-task.md), then choose
[one-shot actions](one-shot-actions.md) or [managed control](managed-control.md).
It starts a private server with [`Server.with_owned/2`](owned-server.md). From
a checkout, with tmux on `PATH`:
```console
$ mix run examples/capture_and_read.exs
```
The connect, submit, await, close and forget calls each get 5000 ms by
default. Set `LIBTMUX_EXAMPLE_TIMEOUT_MS` to a value from 1 to 600000 to
change their budgets. Scope cleanup has its own budget of at most 950 ms.
A failure prints the stage and elapsed milliseconds. Cleanup reports elapsed
time since entering the connection scope.
To run the whole packed-example check against an isolated tmux server, from a
source checkout:
```console
$ MIX_ENV=test mix run scripts/check_package.exs --examples
```
- It needs the toolchain from [Contributing](../.github/CONTRIBUTING.md#setup),
plus tmux 3.3 or newer on `PATH`.
- Set `LIBTMUX_TEST_TMUX` to an absolute executable to check a particular tmux
build.
- Hex must already be installed; the check downloads nothing.
- It builds and extracts a real package, compiles its core in a fresh
directory and runs the packaged example outside the checkout.
- An owned fixture supplies a unique socket, an empty configuration and an
existing session. It clears inherited `TMUX`, `TMUX_PANE`, `LIBTMUX_SOCKET`
and `LIBTMUX_SOCKET_PATH`, verifies that its server, pane, clients and helper
exited, and never uses the default server.
## The complete program
The [program](../examples/capture_and_read.exs) starts its own server, creates
a session and uses the captured pane ID in both transports.
<!-- example: examples/capture_and_read.exs -->
```elixir
defmodule CaptureRead do
alias LibTmux.Control.ScopeFailure
def timeout!(value) do
case Integer.parse(value) do
{ms, ""} when ms in 1..600_000 -> ms
_ -> raise ArgumentError, "LIBTMUX_EXAMPLE_TIMEOUT_MS must be 1..600000"
end
end
def step!(stage, run) do
started = System.monotonic_time(:millisecond)
case run.() do
{:ok, value} ->
value
:ok ->
:ok
{:error, %ScopeFailure{primary: {:raise, kind, reason, stack}} = error} ->
report(:cleanup, started, error.cleanup)
:erlang.raise(kind, reason, stack)
{:error, %ScopeFailure{cleanup: error}} ->
report(:cleanup, started, error)
raise error
{:error, error} ->
report(stage, started, error)
raise error
end
end
defp report(stage, started, error) do
elapsed = System.monotonic_time(:millisecond) - started
message = Exception.message(error)
IO.puts(:stderr, "#{stage} after #{elapsed} ms: #{message}")
end
end
alias LibTmux.{Codec, Command, Control, Format, Operation}
alias LibTmux.{Ref, Selection, Server, Snapshot}
alias LibTmux.Control.Request
tmux = System.find_executable("tmux") || raise "tmux is not on PATH"
timeout = System.get_env("LIBTMUX_EXAMPLE_TIMEOUT_MS", "5000")
timeout = CaptureRead.timeout!(timeout)
Server.with_owned([executable: tmux], fn server ->
{:ok, %{value: %{id: session_id}}} =
Server.new_session(server, "demo", command: {:argv, ["/bin/cat"]})
{:ok, snapshot} = Server.snapshot(server)
session = snapshot |> Snapshot.sessions() |> Selection.one!(id: session_id)
window = Snapshot.related(snapshot, :session, session.id, :active_window)
pane =
snapshot
|> Snapshot.panes()
|> Selection.where(window_id: window.id)
|> Selection.filter(& &1.active)
|> Selection.one!()
{:ok, target} = Ref.new(:pane, pane.id, snapshot.server_instance)
escaped = [encoding: :escaped_v1]
args = ["-p", "-t", pane.id, Format.field("pane_id")]
command = Command.new("display-message", args)
{:ok, %{stdout: stdout, cleanup: :retired}} = Server.run(server, command)
{:ok, one_shot_id} = Codec.decode_field(stdout, :string, escaped)
true = one_shot_id == pane.id
options = [
server: server,
session: {:existing, session.id},
lane: :host_qualified,
timeout: timeout,
cleanup_timeout: min(timeout, 950)
]
read = fn control ->
request = Request.field("pane_id", target)
operation =
CaptureRead.step!(:submit, fn ->
Control.submit(control, request, timeout: timeout)
end)
result =
CaptureRead.step!(:await, fn ->
Operation.await(operation, timeout: timeout)
end)
%{outcome: :completed, certainty: :acknowledged} = result
%{evidence: :command_reply, lines: [line]} = result
{:ok, %{phase: :ready}} = Control.status(control)
{:ok, %{result: %{outcome: :completed}}} = Operation.status(operation)
{:ok, id} = Codec.decode_field(line <> "\n", :string, escaped)
true = id == pane.id
CaptureRead.step!(:close, fn ->
Control.close(control, timeout: timeout)
end)
{:ok, %{phase: :retired, terminal: terminal}} = Control.status(control)
%{reason: :closure_requested} = terminal
{:ok, ^result} = Operation.result(operation)
CaptureRead.step!(:forget, fn ->
Operation.forget(operation, timeout: timeout)
end)
id
end
control_id =
CaptureRead.step!(:connect, fn ->
Control.with_connection(options, read)
end)
IO.puts(
JSON.encode!(%{
"session" => session.id,
"window" => window.id,
"pane" => pane.id,
"oneShot" => one_shot_id,
"control" => control_id,
"connectionRetired" => true
})
)
end)
```
<!-- /example -->
- The result holds the observed session, window and pane IDs. Both replies
must identify the selected pane.
- `connectionRetired` is true only after the connection closes and its
supervisor exits.
- `Server.with_owned/2` stops the private server after the callback; the
packed check then confirms that no directory, socket or process remains.
- After closure, `LibTmux.Control.status/1` keeps the observed close reason and
bounded captured stderr until epoch replacement or context loss. Inspect
that report before reconnecting or shutting its owner down.
- The example checks requested closure and the unchanged completed operation.
An unexpected close can have a different reason or no evidence.
- Captured stderr can contain application data.
## What each step establishes
- `LibTmux.Server.snapshot/2` observes a capture interval. `LibTmux.Selection`
then runs `where`, a native predicate and checked cardinality locally, with
no further tmux command, and relationships resolve against the same graph.
- The one-shot read uses an exact pane ID and the escaped field codec. Its
check/use race remains: a captured pane is not reserved.
- The control request also carries a `LibTmux.Ref` bound to the observed server
incarnation.
- Control startup attaches a client and can change session state and
attachment counts. The fixture's empty, controlled configuration is why this
example can declare `lane: :host_qualified`. On another server, qualify its
effective hooks, aliases and stream writers first.
- `LibTmux.Control.submit/3` returns an admitted operation. The example checks
that `LibTmux.Operation.await/2` reports `:completed` and `:acknowledged`. A
reply acknowledges this tmux command; it does not prove that a program
started by another command has exited.
## Failure behavior and cleanup
- The program uses assertions, so an unexpected result fails the example.
- Capture and transport errors return `{:error, %LibTmux.Error{}}`, with
`kind`, `phase` and `certainty` describing the failure.
- A control field read whose target disappeared returns an acknowledged
`:failed` operation. A present empty field stays `:completed`.
- Raw one-shot commands keep tmux's native semantics, so the example also
checks the returned pane ID. Neither path retries with a positional target.
- `LibTmux.Selection.one!/2` raises `:no_match` or `:multiple_matches` instead
of selecting arbitrarily.
- An await timeout ends only that waiter. Failed, skipped and unknown outcomes
are values, including from bang functions. Inspect the retained operation
instead of replaying an uncertain command. This example accepts only an
acknowledged completed read.
- `Control.with_connection/2` retires the connection supervisor. If scope
cleanup also fails, the example reports that error and raises the original
failure with its stacktrace. The packed check audits the owned processes.
See [the mental model](mental-model.md) and [ownership](ownership.md) for the
different lifetimes and remaining limits.