diff --git a/CHANGELOG.md b/CHANGELOG.md index 225ee9f..6eb30a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ at one version, so a release has a section in each changelog. ## 0.1.4 (unreleased) +- Own tmux servers, sessions, windows and panes in Ruby blocks. The + lifecycle APIs distinguish created and borrowed resources, bound + discovery and retain an owner for retry when cleanup fails. (#27) + ## 0.1.3 (2026-12-05) Core and Async can wait for visible pane text with a deadline. On tmux 3.7 diff --git a/README.md b/README.md index aaec5a7..54591ee 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,29 @@ logs: %1, %2 Pane commands take argument arrays. +## Own a session on a running server + +`Server.open` borrows the running tmux daemon. `with_session` creates a +session for its block and removes that session when the block exits. + + +```ruby +# frozen_string_literal: true + +require "libtmux" +require "securerandom" + +LibTmux::Server.open do |server| + server.with_session(name: "ruby-example-#{SecureRandom.hex(4)}", command: ["/bin/cat"]) do |session| + puts "session windows: #{session.list_windows.length}" + end +end +``` + + +See [lifecycle operations](docs/lifecycle.md) for explicit adoption, bounded +discovery and created or reused resources. + ## Drive a pane ### [`Pane#split`][pane-split]: split a pane, type into it, resize it diff --git a/docs/lifecycle.md b/docs/lifecycle.md new file mode 100644 index 0000000..8208dad --- /dev/null +++ b/docs/lifecycle.md @@ -0,0 +1,95 @@ +# Ownership, discovery and find or create + +## Own a session, window or pane + +An ordinary program uses your running default tmux daemon. It creates one session, reuses it by exact name, creates and cleans up a window and pane, then adopts a window created through the borrowed API. Each example includes its imports. The repository harness supplies a private endpoint through the child environment when testing the same source. + + +```ruby +# frozen_string_literal: true + +require "libtmux" +require "securerandom" + +LibTmux::Server.open do |server| + name = "ruby-lifecycle-#{SecureRandom.hex(4)}" + server.owned_session(name: name, command: ["/bin/cat"]) do |session| + reused = server.find_or_create_session(name: name, command: ["/bin/cat"]) + puts "session reused: #{!reused.created?}" + window = session.find_or_create_window(name: "worker", command: ["/bin/cat"]) + window.use do |resource| + pane = resource.find_or_create_pane(identity: "worker", direction: :horizontal, command: ["/bin/cat"]) + pane.use { puts "pane created: #{pane.created?}" } + end + session.new_window(name: "adopt", command: ["/bin/cat"]).adopt do |window| + puts "adopted panes: #{window.list_panes.length}" + end + end +end +``` + + +## Find running servers + +This example scans direct entries in the directory containing the selected endpoint. Omit `roots:` to scan the captured endpoint directory, the configured `TMUX_TMPDIR/tmux-UID` directory and `/tmp/tmux-UID`. Discovery returns successful endpoints, per-path diagnostics and a truncation flag. Symlinks are skipped; hard links to one socket are deduplicated. The entry limit includes roots. Probe and total time limits bound client waits. Discovery uses `-N` and cannot launch a daemon. It does not inventory arbitrary sockets elsewhere on the machine. + + +```ruby +# frozen_string_literal: true + +require "libtmux" + +endpoint = LibTmux::Endpoint.new +result = LibTmux::Server.discover(roots: [File.dirname(endpoint.socket_path)]) +puts "servers: #{result.servers.length}" +raise "discovery was truncated" if result.truncated? +``` + + +## Adopt a daemon + +This cleanup demonstration starts a private foreground daemon because the example destroys the entire server. `Server.start` retains its own child-process observer. `adopt` also captures a daemon generation receipt. Exiting the inner block kills the accepted daemon; the outer block retires its client and startup files. + + +```ruby +# frozen_string_literal: true + +require "libtmux" + +LibTmux::Server.start do |server| + server.new_session(name: "ownership", command: ["/bin/cat"]) + server.adopt do |daemon| + pane = daemon.list_panes.first + pane.adopt { puts "server adopted: true" } + end +end +``` + + +## Ownership and failure rules + +`server.adopt`, `session.adopt`, `window.adopt` and `pane.adopt` return an `OwnedResource`, or run a block and clean up at block exit. `owned_session`, `owned_window` and `owned_pane` create a resource and return an owner with the same block option. `with_session` yields the session in a receipt-backed block scope. A window owner kills the window, its panes and every linked copy. A moved pane or window retains its ID and cleanup follows that ID. Plain lookup, `new_session`, `new_window`, `split`, and client `Server.open` do not adopt remote resources. + +An owner retains its borrowed server binding, a hard-link route to the accepted Unix socket, PID, start time, object ID and a random 32-character generation token. The library initializes the reserved server option `@libtmux_owner_generation` only when it is absent. Empty or malformed existing values fail acquisition. Callers must not change or shadow this reserved option while owners remain open. Destructive commands check the receipt inside tmux. A replacement daemon cannot become the target of a retained route; the generation guard also rejects a simulated numeric identity collision. Keep the borrowed server client open until its owners close. + +`OwnedResource#close` succeeds once and then does nothing. A failed close leaves `closed?` false and retains the exception in `cleanup_error`, so callers can retry. A block failure survives a successful cleanup as the original exception object. If both fail, `CleanupError#body_error` and `cleanup_error` retain both original exception objects; `recovery` exposes the owner for retry. Ruby `ensure` handles return, break, throw and exceptions. Ruby asynchronous exceptions are deferred during receipt handoff and cleanup. A cancellation token observed after creation triggers receipt-based rollback. + +Adoption checks `cancel:` before acquisition and after accepting a complete, valid receipt. Cancellation before acquisition leaves the borrowed target intact. Cancellation after ownership acceptance destroys the adopted server, session, window or pane through that receipt and raises `Cancelled` without returning an owner or entering the block. If destruction fails, `CleanupError` retains the cancellation, cleanup failure and recovery owner for retry. Late cancellation of `server.adopt` therefore destroys the accepted daemon, just as leaving its owned block does. + +Creation prints the object ID and daemon identity in the creating command. Extra data after a complete receipt triggers rollback; a later pane-identity verification failure does too. If rollback fails, `CleanupError#recovery` retains the owner. Without a complete receipt, `OutcomeUnknown` reports uncertainty and the retained endpoint is the inspection boundary. It does not guess which object to delete. Timeouts and killed runner processes can still lose a receipt; an external fixture must own whole-server teardown for those cases. + +The Async facade uses its existing bound core server for ownership commands and cleanup. It defers Async task cancellation during receipt handoff and allows cleanup after body cancellation. These ownership calls use the blocking core executor; ordinary Async commands keep their scheduler transport. Async permits a second cancellation to interrupt a deferred task. Repeated forced cancellation and whole-runner crash recovery require an outer owner; they are not a promise of this block API. + +## Matching and concurrency + +`Server.find_or_create` returns `Acquisition[Server]`. A fresh endpoint receives a foreground daemon through atomic no-overwrite socket publication; a reused endpoint remains borrowed. Stale sockets and ordinary files are errors and stay in place. Close the returned server client after a reused acquisition. A created result has an owner; `Acquisition#use` cleans up only a created resource. + +`find_or_create_session` matches one exact session name. Names containing dot, colon, backslash or control characters fail before creation because tmux rewrites those characters. Existing borrowed creation methods keep their previous input behavior. `find_or_create_window` matches a window name within one session and rejects multiple matches. It rejects backslash and control characters that tmux rewrites in window names. `find_or_create_pane` matches the literal local `@libtmux_pane_identity` option within one window and rejects duplicates. The library writes and verifies that identity for a created pane; it rolls back if that step fails. + +Find-or-create calls share one bounded gate within a Ruby process, across server handles and threads. Calls for different endpoints also share that gate. A caller waiting for it uses the operation deadline. Raw tmux commands and other processes do not join this serialization. They can rename, link, move or create objects during a lookup. This API makes no cross-process atomicity claim. tmux still rejects duplicate session names, and socket publication still refuses an occupied pathname. + +Session, window and pane find-or-create calls check `cancel:` before gate admission, during lookup and before returning the acquisition. A waiting call checks the token at intervals of at most 0.05 seconds while another call holds the gate, subject to thread scheduling. Cancelled reuse leaves the existing resource borrowed and intact. Cancellation after creation rolls back only the newly owned resource, including a pane whose identity was written before cancellation arrived. The same operation deadline covers the gate, lookup and creation. + +## Example checks + +The example manifest binds each displayed code block to its complete Ruby source. The existing Markdown/YARD renderer and installed-gem recipes check those source excerpts and execute them. The external harness passes `LIBTMUX_SOCKET_PATH`, validates output and remaining sessions, then observes its foreground daemon exit before removing its fixture. A bounded worker executor retires timed-out example processes; a crashed example worker still reaches outer fixture cleanup. Killing the harness process itself requires a separate supervisor and is not covered by that in-process ensure. Host `ENV` stays unchanged. Astro, Sphinx and Python doctest adapters remain shared project scope; this Ruby repository does not claim executed native integrations for those formats. diff --git a/docs/ownership-errors.md b/docs/ownership-errors.md index fd3c6c6..76ba119 100644 --- a/docs/ownership-errors.md +++ b/docs/ownership-errors.md @@ -12,6 +12,16 @@ - Handles, Async tasks and subscriptions stay with the process and scheduler that made them. +`Server#with_session` owns a newly created session. Call +`server.with_session(name:, command:)` with a block. +It captures the session ID and attempts removal after normal return or an +exception. A lookup or `new_session` without that block scope returns a +borrowed handle. If the block and teardown both fail, inspect `CleanupError`'s +`body_error` and `cleanup_error`; both retain the original exception objects. +The [ordinary example](../examples/default_session.rb) uses this scope with +the default endpoint. The [behavior contract](reference/behavior.md#session-scopes) +describes retries and deadlines. + | Failure or empty value | Meaning | | --- | --- | | Empty `Selection` / `one_or_nil` returns `nil` | A valid complete local selection has no matching record | diff --git a/docs/reference/api.md b/docs/reference/api.md index 0d879c0..5330f18 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -23,6 +23,15 @@ type checking. See [signature proof](behavior.md#signature-proof). | [.run_program](../../gems/libtmux/lib/libtmux/program.rb#L16) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | | [.start_program](../../gems/libtmux/lib/libtmux/program.rb#L11) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +## LibTmux::Acquisition + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#created?](../../gems/libtmux/lib/libtmux/lifecycle.rb#L99) | `bool` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#owner](../../gems/libtmux/lib/libtmux/lifecycle.rb#L91) | `::LibTmux::OwnedResource[A]?` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#resource](../../gems/libtmux/lib/libtmux/lifecycle.rb#L91) | `A` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#use](../../gems/libtmux/lib/libtmux/lifecycle.rb#L103) | `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | + ## LibTmux::Async | Method | Declared return | Contract | @@ -76,46 +85,52 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L273) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#attach](../../gems/libtmux-async/lib/libtmux/async/server.rb#L53) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | -| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L242) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L240) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | | [#close](../../gems/libtmux-async/lib/libtmux/async/server.rb#L19) | `nil` | [Async scope](behavior.md#async-scope) | | [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L69) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [#diagnostics](../../gems/libtmux-async/lib/libtmux/async/server.rb#L24) | `::LibTmux::Async::scope_diagnostics` | [Diagnostics](behavior.md#diagnostics) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L18) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#endpoint](../../gems/libtmux/lib/libtmux/server.rb#L149) | `::LibTmux::Endpoint` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L92) | `::String?` | [Environment](behavior.md#environment) | -| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L414) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#find_or_create_session](../../gems/libtmux/lib/libtmux/lifecycle.rb#L283) | `::LibTmux::Acquisition[::LibTmux::Session]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L11) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L302) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L300) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | | [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L73) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | | [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L100) | `::Array[{ name: ::String, pid: ::Integer, created: ::Integer, tty: ::String?, session_id: ::String?, control: bool }]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L336) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L328) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L341) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L333) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | | [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L80) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | -| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L313) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L337) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L311) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | | [#open_control](../../gems/libtmux-async/lib/libtmux/async/server.rb#L28) | `T` / `::LibTmux::Async::ControlConnection` | [Control connections](behavior.md#control-connections) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L7) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | | [#owned?](../../gems/libtmux/lib/libtmux/owned.rb#L16) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | -| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L348) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#owned_session](../../gems/libtmux/lib/libtmux/lifecycle.rb#L277) | `::LibTmux::OwnedResource[::LibTmux::Session]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L353) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | | [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L458) | `{ binding_key: ::String, pid: ::Integer, start_time: ::Integer, version: ::String, since: ::String, supported: bool }` | [Owned terminal programs](behavior.md#owned-terminal-programs) | | [#read_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L65) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [#run](../../gems/libtmux-async/lib/libtmux/async/server.rb#L15) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | | [#run_group](../../gems/libtmux/lib/libtmux/group.rb#L32) | `::LibTmux::GroupResult` | [Command groups](behavior.md#command-groups) | -| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L405) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | -| [#session](../../gems/libtmux/lib/libtmux/server.rb#L340) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L410) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L345) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | | [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L88) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | -| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L399) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L404) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | | [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L42) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | | [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L464) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | -| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L234) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L232) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L39) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | -| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L229) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L227) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L96) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | | [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L47) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | -| [#window](../../gems/libtmux/lib/libtmux/server.rb#L344) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L349) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | | [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L84) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | +| [#with_session](../../gems/libtmux/lib/libtmux/server.rb#L326) | `T` | [Session scopes](behavior.md#session-scopes) | | [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L57) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [.discover](../../gems/libtmux-async/lib/libtmux/async/server.rb#L69) | `::LibTmux::DiscoveryResult` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [.find_or_create](../../gems/libtmux-async/lib/libtmux/async/server.rb#L65) | `bot` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [.open](../../gems/libtmux-async/lib/libtmux/async/server.rb#L61) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | | [.start](../../gems/libtmux-async/lib/libtmux/async/server.rb#L57) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | | [.valid_terminal_type?](../../gems/libtmux/lib/libtmux/terminal.rb#L34) | `bool` | [Terminal attachment](behavior.md#terminal-attachment) | @@ -231,6 +246,23 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | | [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +## LibTmux::CleanupError + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#body_error](../../gems/libtmux/lib/libtmux/errors.rb#L32) | `::Exception` | [Errors](behavior.md#errors) | +| [#cleanup_error](../../gems/libtmux/lib/libtmux/errors.rb#L32) | `::Exception` | [Errors](behavior.md#errors) | +| [#cleanup_errors](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Array[::String]` | [Errors](behavior.md#errors) | +| [#delivery](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol` | [Errors](behavior.md#errors) | +| [#entity](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | +| [#expected](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [#path](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [#phase](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | +| [#pid](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Integer?` | [Errors](behavior.md#errors) | +| [#recovery](../../gems/libtmux/lib/libtmux/errors.rb#L32) | `untyped` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L34) | `::LibTmux::CleanupError` | [Errors](behavior.md#errors) | + ## LibTmux::ClientSnapshot | Method | Declared return | Contract | @@ -288,9 +320,9 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#path](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | | [#phase](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | | [#pid](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Integer?` | [Errors](behavior.md#errors) | -| [#result](../../gems/libtmux/lib/libtmux/errors.rb#L66) | `::LibTmux::CommandResult?` | [Errors](behavior.md#errors) | +| [#result](../../gems/libtmux/lib/libtmux/errors.rb#L77) | `::LibTmux::CommandResult?` | [Errors](behavior.md#errors) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | -| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L68) | `::LibTmux::CommandError` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L79) | `::LibTmux::CommandError` | [Errors](behavior.md#errors) | ## LibTmux::CommandResult @@ -381,24 +413,44 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | | [.new](../../gems/libtmux/lib/libtmux/errors.rb#L7) | `::LibTmux::DeadlineExceeded` | [Errors](behavior.md#errors) | +## LibTmux::DiscoveredServer + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#endpoint](../../gems/libtmux/lib/libtmux/lifecycle.rb#L111) | `::LibTmux::Endpoint` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#pid](../../gems/libtmux/lib/libtmux/lifecycle.rb#L111) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#started_at](../../gems/libtmux/lib/libtmux/lifecycle.rb#L111) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | + +## LibTmux::DiscoveryResult + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#diagnostics](../../gems/libtmux/lib/libtmux/lifecycle.rb#L121) | `::Array[::Hash[::Symbol, ::String \| ::Symbol]]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#entries](../../gems/libtmux/lib/libtmux/lifecycle.rb#L121) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#probes](../../gems/libtmux/lib/libtmux/lifecycle.rb#L121) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#servers](../../gems/libtmux/lib/libtmux/lifecycle.rb#L121) | `::Array[::LibTmux::DiscoveredServer]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#truncated?](../../gems/libtmux/lib/libtmux/lifecycle.rb#L131) | `bool` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | + ## LibTmux::Endpoint | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/endpoint.rb#L56) | `bool` | [Endpoints](behavior.md#endpoints) | -| [#eql?](../../gems/libtmux/lib/libtmux/endpoint.rb#L56) | `bool` | [Endpoints](behavior.md#endpoints) | -| [#executable](../../gems/libtmux/lib/libtmux/endpoint.rb#L18) | `::String` | [Endpoints](behavior.md#endpoints) | -| [#hash](../../gems/libtmux/lib/libtmux/endpoint.rb#L61) | `::Integer` | [Endpoints](behavior.md#endpoints) | -| [#inspect](../../gems/libtmux/lib/libtmux/endpoint.rb#L65) | `::String` | [Endpoints](behavior.md#endpoints) | -| [#socket_path](../../gems/libtmux/lib/libtmux/endpoint.rb#L18) | `::String` | [Endpoints](behavior.md#endpoints) | -| [.from_env](../../gems/libtmux/lib/libtmux/endpoint.rb#L51) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | -| [.new](../../gems/libtmux/lib/libtmux/endpoint.rb#L20) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | +| [#==](../../gems/libtmux/lib/libtmux/endpoint.rb#L63) | `bool` | [Endpoints](behavior.md#endpoints) | +| [#environment](../../gems/libtmux/lib/libtmux/endpoint.rb#L20) | `::Hash[::String, ::String]` | [Endpoints](behavior.md#endpoints) | +| [#eql?](../../gems/libtmux/lib/libtmux/endpoint.rb#L63) | `bool` | [Endpoints](behavior.md#endpoints) | +| [#executable](../../gems/libtmux/lib/libtmux/endpoint.rb#L20) | `::String` | [Endpoints](behavior.md#endpoints) | +| [#hash](../../gems/libtmux/lib/libtmux/endpoint.rb#L68) | `::Integer` | [Endpoints](behavior.md#endpoints) | +| [#inspect](../../gems/libtmux/lib/libtmux/endpoint.rb#L72) | `::String` | [Endpoints](behavior.md#endpoints) | +| [#socket_path](../../gems/libtmux/lib/libtmux/endpoint.rb#L20) | `::String` | [Endpoints](behavior.md#endpoints) | +| [.from_env](../../gems/libtmux/lib/libtmux/endpoint.rb#L58) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | +| [.new](../../gems/libtmux/lib/libtmux/endpoint.rb#L22) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | ## LibTmux::Entity | Method | Declared return | Contract | | --- | --- | --- | | [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L139) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | | [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | @@ -556,7 +608,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#phase](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | | [#pid](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Integer?` | [Errors](behavior.md#errors) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | -| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L31) | `::LibTmux::InvalidFilterError` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L42) | `::LibTmux::InvalidFilterError` | [Errors](behavior.md#errors) | ## LibTmux::MCP::Application @@ -679,11 +731,33 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | | [.new](../../gems/libtmux/lib/libtmux/errors.rb#L7) | `::LibTmux::OutcomeUnknown` | [Errors](behavior.md#errors) | +## LibTmux::OwnedResource + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#cleanup_error](../../gems/libtmux/lib/libtmux/lifecycle.rb#L22) | `::Exception?` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#close](../../gems/libtmux/lib/libtmux/lifecycle.rb#L37) | `nil` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#closed?](../../gems/libtmux/lib/libtmux/lifecycle.rb#L33) | `bool` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#receipt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L22) | `::LibTmux::OwnershipReceipt` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#resource](../../gems/libtmux/lib/libtmux/lifecycle.rb#L22) | `A` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#use](../../gems/libtmux/lib/libtmux/lifecycle.rb#L66) | `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | + +## LibTmux::OwnershipReceipt + +| Method | Declared return | Contract | +| --- | --- | --- | +| [#generation](../../gems/libtmux/lib/libtmux/lifecycle.rb#L9) | `::String` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#id](../../gems/libtmux/lib/libtmux/lifecycle.rb#L9) | `::String?` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#kind](../../gems/libtmux/lib/libtmux/lifecycle.rb#L9) | `::Symbol` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#pid](../../gems/libtmux/lib/libtmux/lifecycle.rb#L9) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#started_at](../../gems/libtmux/lib/libtmux/lifecycle.rb#L9) | `::Integer` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | + ## LibTmux::Pane | Method | Declared return | Contract | | --- | --- | --- | | [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L139) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#break_out](../../gems/libtmux/lib/libtmux/operations.rb#L358) | `::LibTmux::Window` | [Entity mutation](behavior.md#entity-mutation) | | [#capture](../../gems/libtmux/lib/libtmux/entity.rb#L351) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | | [#copy_command](../../gems/libtmux/lib/libtmux/operations.rb#L426) | `::LibTmux::CommandResult` | [Copy mode](behavior.md#copy-mode) | @@ -698,6 +772,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L87) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | | [#move](../../gems/libtmux/lib/libtmux/operations.rb#L351) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#owned_pane](../../gems/libtmux/lib/libtmux/lifecycle.rb#L169) | `::LibTmux::OwnedResource[::LibTmux::Pane]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#paste](../../gems/libtmux/lib/libtmux/operations.rb#L388) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | | [#pipe](../../gems/libtmux/lib/libtmux/operations.rb#L398) | `::LibTmux::CommandResult` | [Pane pipes](behavior.md#pane-pipes) | | [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | @@ -723,7 +798,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#path](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | | [#phase](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Symbol?` | [Errors](behavior.md#errors) | | [#pid](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::Integer?` | [Errors](behavior.md#errors) | -| [#reason](../../gems/libtmux/lib/libtmux/errors.rb#L53) | `:pane_exited \| :pane_gone \| :server_gone` | [Pane text waits](behavior.md#pane-text-waits) | +| [#reason](../../gems/libtmux/lib/libtmux/errors.rb#L64) | `:pane_exited \| :pane_gone \| :server_gone` | [Pane text waits](behavior.md#pane-text-waits) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String` | [Errors](behavior.md#errors) | ## LibTmux::PaneSnapshot @@ -841,47 +916,53 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L273) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#attach](../../gems/libtmux/lib/libtmux/terminal.rb#L52) | `::LibTmux::TerminalResult` | [Terminal attachment](behavior.md#terminal-attachment) | -| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L242) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#close](../../gems/libtmux/lib/libtmux/server.rb#L253) | `nil` | [Closing bindings](behavior.md#closing-bindings) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L240) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#close](../../gems/libtmux/lib/libtmux/server.rb#L251) | `nil` | [Closing bindings](behavior.md#closing-bindings) | | [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L69) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/server.rb#L292) | `{ admitted_requests: ::Integer, reserved_process_slots: ::Integer, control_connections: ::Integer, closed: bool, limits: { max_requests: ::Integer, max_controls: ::Integer, close_timeout: ::Numeric } }` | [Diagnostics](behavior.md#diagnostics) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/server.rb#L290) | `{ admitted_requests: ::Integer, reserved_process_slots: ::Integer, control_connections: ::Integer, closed: bool, limits: { max_requests: ::Integer, max_controls: ::Integer, close_timeout: ::Numeric } }` | [Diagnostics](behavior.md#diagnostics) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L18) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#endpoint](../../gems/libtmux/lib/libtmux/server.rb#L149) | `::LibTmux::Endpoint` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L92) | `::String?` | [Environment](behavior.md#environment) | -| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L414) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#find_or_create_session](../../gems/libtmux/lib/libtmux/lifecycle.rb#L283) | `::LibTmux::Acquisition[::LibTmux::Session]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L11) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L302) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L300) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | | [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L73) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | | [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L100) | `::Array[{ name: ::String, pid: ::Integer, created: ::Integer, tty: ::String?, session_id: ::String?, control: bool }]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L336) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L328) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_panes](../../gems/libtmux/lib/libtmux/server.rb#L341) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L333) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | | [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L80) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | -| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L313) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | -| [#open_control](../../gems/libtmux/lib/libtmux/server.rb#L352) | `T` / `::LibTmux::ControlConnection` | [Control connections](behavior.md#control-connections) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L337) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L311) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#open_control](../../gems/libtmux/lib/libtmux/server.rb#L357) | `T` / `::LibTmux::ControlConnection` | [Control connections](behavior.md#control-connections) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L7) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | | [#owned?](../../gems/libtmux/lib/libtmux/owned.rb#L16) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | -| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L348) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#owned_session](../../gems/libtmux/lib/libtmux/lifecycle.rb#L277) | `::LibTmux::OwnedResource[::LibTmux::Session]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L353) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | | [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L458) | `{ binding_key: ::String, pid: ::Integer, start_time: ::Integer, version: ::String, since: ::String, supported: bool }` | [Owned terminal programs](behavior.md#owned-terminal-programs) | | [#read_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L65) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | -| [#run](../../gems/libtmux/lib/libtmux/server.rb#L249) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | +| [#run](../../gems/libtmux/lib/libtmux/server.rb#L247) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | | [#run_group](../../gems/libtmux/lib/libtmux/group.rb#L32) | `::LibTmux::GroupResult` | [Command groups](behavior.md#command-groups) | -| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L405) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | -| [#session](../../gems/libtmux/lib/libtmux/server.rb#L340) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L410) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L345) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | | [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L88) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | -| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L399) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L404) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | | [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L42) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | | [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L464) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | -| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L234) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L232) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L39) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | -| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L229) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L227) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L96) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | | [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L47) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | -| [#window](../../gems/libtmux/lib/libtmux/server.rb#L344) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L349) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | | [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L84) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | +| [#with_session](../../gems/libtmux/lib/libtmux/server.rb#L326) | `T` | [Session scopes](behavior.md#session-scopes) | | [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L57) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | -| [.new](../../gems/libtmux/lib/libtmux/server.rb#L183) | `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [.discover](../../gems/libtmux/lib/libtmux/lifecycle.rb#L178) | `::LibTmux::DiscoveryResult` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [.find_or_create](../../gems/libtmux/lib/libtmux/lifecycle.rb#L289) | `::LibTmux::Acquisition[::LibTmux::Server]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | +| [.new](../../gems/libtmux/lib/libtmux/server.rb#L180) | `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [.open](../../gems/libtmux/lib/libtmux/server.rb#L151) | `T` / `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [.start](../../gems/libtmux/lib/libtmux/owned.rb#L12) | `::LibTmux::Server` / `T` | [Owned daemons](behavior.md#owned-daemons) | | [.valid_terminal_type?](../../gems/libtmux/lib/libtmux/terminal.rb#L34) | `bool` | [Terminal attachment](behavior.md#terminal-attachment) | @@ -891,9 +972,11 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | | [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L139) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L286) | `::String?` | [Environment](behavior.md#environment) | | [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#find_or_create_window](../../gems/libtmux/lib/libtmux/lifecycle.rb#L150) | `::LibTmux::Acquisition[::LibTmux::Window]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | | [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | @@ -905,6 +988,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#list_windows](../../gems/libtmux/lib/libtmux/entity.rb#L165) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | | [#new_window](../../gems/libtmux/lib/libtmux/entity.rb#L160) | `::LibTmux::CreationReceipt` / `::LibTmux::Window` | [Creation](behavior.md#creation) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#owned_window](../../gems/libtmux/lib/libtmux/lifecycle.rb#L145) | `::LibTmux::OwnedResource[::LibTmux::Window]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | | [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L267) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | | [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | @@ -1054,8 +1138,10 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | | [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L139) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#find_or_create_pane](../../gems/libtmux/lib/libtmux/lifecycle.rb#L162) | `::LibTmux::Acquisition[::LibTmux::Pane]` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | | [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | | [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | @@ -1063,6 +1149,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L87) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | | [#list_panes](../../gems/libtmux/lib/libtmux/entity.rb#L230) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | | [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#owned_pane](../../gems/libtmux/lib/libtmux/lifecycle.rb#L156) | `::LibTmux::OwnedResource[::LibTmux::Pane]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | | [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L296) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | | [#resize](../../gems/libtmux/lib/libtmux/operations.rb#L307) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | @@ -1077,6 +1164,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | | [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | +| [#adopt](../../gems/libtmux/lib/libtmux/lifecycle.rb#L139) | `::LibTmux::OwnedResource[self]` / `T` | [Lifecycle ownership and discovery](behavior.md#lifecycle-ownership-and-discovery) | | [#display](../../gems/libtmux/lib/libtmux/entity.rb#L426) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | | [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | | [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | diff --git a/docs/reference/behavior.md b/docs/reference/behavior.md index f9e7d17..4b87b6e 100644 --- a/docs/reference/behavior.md +++ b/docs/reference/behavior.md @@ -18,8 +18,8 @@ caller data even when diagnostic inspection omits it. ## Endpoints `Endpoint.new` takes a socket path or a socket name, and raises -`ArgumentError` when given both. It expands the path and resolves -`executable: "tmux"` through PATH without starting a client. Socket names use +`ArgumentError` when given both. It resolves relative and home paths while +preserving filesystem traversal. Socket names use `socket_directory`, then `TMUX_TMPDIR`, then `/tmp`, with tmux's per-user directory. Invalid paths/names or an unavailable executable raise `ArgumentError`. @@ -39,6 +39,20 @@ and `TMUX_PANE` removed and reaches the daemon through a private route to the socket (see [Borrowed bindings](#borrowed-bindings)). Choosing a socket never starts a server: a socket that does not exist raises a typed binding error. +`environment:` selects the socket. By default the endpoint captures the +process environment for child clients. Pass `env:` to `Endpoint.new`, +`Server.new`, `Server.open` or `Server.start` to supply a complete child map. +`Endpoint.new` and the borrowing factories also use that map to select the +socket when it is unspecified. + +`Endpoint#environment` returns the frozen child map. The endpoint copies its +keys and values, drops nil entries and omits `TMUX` and `TMUX_PANE`. It looks +up the executable in the captured PATH, or the process PATH if the map has +none. Core, Async and control clients use the captured map, and terminal +attachment supplies its own TERM. Changes to the original map or process +environment do not affect the binding. The `environment:` creation option +for sessions, windows and panes sets the environment of the new pane. + `Endpoint.from_env` follows `TMUX` alone: it uses the socket from `TMUX`, or tmux's `default` socket name when absent, and ignores `LIBTMUX_SOCKET_PATH` and `LIBTMUX_SOCKET`. Descriptor equality compares resolved executable and socket @@ -77,6 +91,22 @@ leaving the block retires those resources. Startup errors and cancellation clean up partially established ownership. `owned?` distinguishes this case from a borrowed binding; it does not grant ownership of another daemon. +An explicit `endpoint:` publishes that owned daemon at the selected path. The +library starts the daemon in a private subdirectory beside the endpoint and +uses an atomic hard link to publish its socket. An occupied path raises +`Errno::EEXIST`, including a competing library startup, without replacing the +existing endpoint. tmux reports its private startup path in `socket_path`. +Callers must control the selected directory; same-user tampering with that +private directory remains outside the ownership contract. + +For named endpoints, startup creates only the `tmux-UID` directory with mode +0700. Its parent must exist. An existing UID directory must be a real +directory owned by the current UID with no other-user permission bits; group +permissions are allowed. Explicit paths never create parents. A missing or +removed root fails without choosing `/tmp`. Close checks socket identity +before removing a published path and reaps its owned child before removing +its private directory. It retains caller-provided parent directories. + ## Closing bindings `Server#close` stops admission, requests cancellation of owned clients and @@ -94,6 +124,20 @@ a command result. It can destroy a borrowed daemon and all of its sessions; this mutation is separate from closing the local binding. Successful client status is command evidence, not a substitute for closing local resources. +## Session scopes + +`Server#with_session` creates a session, yields it, then kills that captured +session ID on normal return or an exception. It returns the block result and +requires a block. Supply an explicit name and command. The scope accepts the session creation +options without a separate creation receipt. The cleanup uses a fresh default command deadline and no cancelled +body token. It leaves other sessions and the borrowed daemon running. + +If both the body and cleanup raise, `CleanupError` retains their exception +objects as `body_error` and `cleanup_error`. A cleanup failure alone propagates +as its original exception. `Server.open` also preserves both errors if its +block and binding close fail. For a lifecycle failure, `CleanupError#recovery` +exposes the owner so the caller can retry `close`. + ## Entity references An `EntityRef` is an immutable binding key, entity kind and tmux-assigned ID. @@ -1303,3 +1347,12 @@ end The program prints `Received: café`. + +## Lifecycle ownership and discovery + +[Ownership, discovery and find or create](../lifecycle.md) documents +receipt-backed resource ownership, created or reused results, and bounded +discovery. Keep the client binding open until ownership cleanup completes. +`OwnedResource#use` closes at block exit. A failed close keeps its error and +allows retry. The Async facade uses its bound Core transport for ownership +and defers task cancellation during receipt handoff. diff --git a/docs/reference/contracts.json b/docs/reference/contracts.json index 2a9d0c4..2b5c1ec 100644 --- a/docs/reference/contracts.json +++ b/docs/reference/contracts.json @@ -370,7 +370,8 @@ "LibTmux::Endpoint#inspect", "LibTmux::Endpoint#socket_path", "LibTmux::Endpoint.from_env", - "LibTmux::Endpoint.new" + "LibTmux::Endpoint.new", + "LibTmux::Endpoint#environment" ] }, { @@ -448,7 +449,10 @@ "LibTmux::Error.new", "LibTmux::InvalidFilterError.new", "LibTmux::SubscriptionOverflow#sequence", - "LibTmux::SubscriptionOverflow.new" + "LibTmux::SubscriptionOverflow.new", + "LibTmux::CleanupError.new", + "LibTmux::CleanupError#body_error", + "LibTmux::CleanupError#cleanup_error" ] }, { @@ -830,6 +834,56 @@ "LibTmux::Capabilities::Workaround.inspect", "LibTmux::Capabilities::Workaround.members" ] + }, + { + "id": "session-scopes", + "title": "Session scopes", + "methods": [ + "LibTmux::Server#with_session" + ] + }, + { + "id": "lifecycle-ownership-and-discovery", + "title": "Lifecycle ownership and discovery", + "methods": [ + "LibTmux::Acquisition#created?", + "LibTmux::Acquisition#owner", + "LibTmux::Acquisition#resource", + "LibTmux::Acquisition#use", + "LibTmux::Async::Server.discover", + "LibTmux::Async::Server.find_or_create", + "LibTmux::CleanupError#recovery", + "LibTmux::DiscoveredServer#endpoint", + "LibTmux::DiscoveredServer#pid", + "LibTmux::DiscoveredServer#started_at", + "LibTmux::DiscoveryResult#diagnostics", + "LibTmux::DiscoveryResult#entries", + "LibTmux::DiscoveryResult#probes", + "LibTmux::DiscoveryResult#servers", + "LibTmux::DiscoveryResult#truncated?", + "LibTmux::Entity#adopt", + "LibTmux::OwnedResource#cleanup_error", + "LibTmux::OwnedResource#close", + "LibTmux::OwnedResource#closed?", + "LibTmux::OwnedResource#receipt", + "LibTmux::OwnedResource#resource", + "LibTmux::OwnedResource#use", + "LibTmux::OwnershipReceipt#generation", + "LibTmux::OwnershipReceipt#id", + "LibTmux::OwnershipReceipt#kind", + "LibTmux::OwnershipReceipt#pid", + "LibTmux::OwnershipReceipt#started_at", + "LibTmux::Pane#owned_pane", + "LibTmux::Server#adopt", + "LibTmux::Server#find_or_create_session", + "LibTmux::Server#owned_session", + "LibTmux::Server.discover", + "LibTmux::Server.find_or_create", + "LibTmux::Session#find_or_create_window", + "LibTmux::Session#owned_window", + "LibTmux::Window#find_or_create_pane", + "LibTmux::Window#owned_pane" + ] } ] } diff --git a/examples/default_session.rb b/examples/default_session.rb new file mode 100644 index 0000000..6e8012b --- /dev/null +++ b/examples/default_session.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +require "libtmux" +require "securerandom" + +LibTmux::Server.open do |server| + server.with_session(name: "ruby-example-#{SecureRandom.hex(4)}", command: ["/bin/cat"]) do |session| + puts "session windows: #{session.list_windows.length}" + end +end diff --git a/examples/lifecycle.rb b/examples/lifecycle.rb new file mode 100644 index 0000000..9a05711 --- /dev/null +++ b/examples/lifecycle.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require "libtmux" +require "securerandom" + +LibTmux::Server.open do |server| + name = "ruby-lifecycle-#{SecureRandom.hex(4)}" + server.owned_session(name: name, command: ["/bin/cat"]) do |session| + reused = server.find_or_create_session(name: name, command: ["/bin/cat"]) + puts "session reused: #{!reused.created?}" + window = session.find_or_create_window(name: "worker", command: ["/bin/cat"]) + window.use do |resource| + pane = resource.find_or_create_pane(identity: "worker", direction: :horizontal, command: ["/bin/cat"]) + pane.use { puts "pane created: #{pane.created?}" } + end + session.new_window(name: "adopt", command: ["/bin/cat"]).adopt do |window| + puts "adopted panes: #{window.list_panes.length}" + end + end +end diff --git a/examples/lifecycle_discovery.rb b/examples/lifecycle_discovery.rb new file mode 100644 index 0000000..05f5e73 --- /dev/null +++ b/examples/lifecycle_discovery.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +require "libtmux" + +endpoint = LibTmux::Endpoint.new +result = LibTmux::Server.discover(roots: [File.dirname(endpoint.socket_path)]) +puts "servers: #{result.servers.length}" +raise "discovery was truncated" if result.truncated? diff --git a/examples/lifecycle_server.rb b/examples/lifecycle_server.rb new file mode 100644 index 0000000..4d93faa --- /dev/null +++ b/examples/lifecycle_server.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +require "libtmux" + +LibTmux::Server.start do |server| + server.new_session(name: "ownership", command: ["/bin/cat"]) + server.adopt do |daemon| + pane = daemon.list_panes.first + pane.adopt { puts "server adopted: true" } + end +end diff --git a/examples/manifest.json b/examples/manifest.json index 2de6d58..2263cba 100644 --- a/examples/manifest.json +++ b/examples/manifest.json @@ -460,6 +460,33 @@ "description": "Read the same feature report through the Async dispatcher within an owned scope.", "output": "Control mode requires tmux 3.7\n" } + }, + { + "id": "default_session", + "path": "examples/default_session.rb", + "gem": "libtmux", + "endpoint": "borrowed", + "output": "session windows: 1\n" + }, + { + "id": "lifecycle", + "path": "examples/lifecycle.rb", + "gem": "libtmux", + "endpoint": "borrowed", + "output": "session reused: true\npane created: true\nadopted panes: 1\n" + }, + { + "id": "lifecycle_discovery", + "path": "examples/lifecycle_discovery.rb", + "gem": "libtmux", + "endpoint": "borrowed", + "output": "servers: 1\n" + }, + { + "id": "lifecycle_server", + "path": "examples/lifecycle_server.rb", + "gem": "libtmux", + "output": "server adopted: true\n" } ], "support": [ @@ -487,7 +514,8 @@ "gems/libtmux-workspace/CHANGELOG.md", "gems/libtmux-workspace/README.md", "gems/libtmux/CHANGELOG.md", - "gems/libtmux/README.md" + "gems/libtmux/README.md", + "docs/lifecycle.md" ], "snippets": [ { @@ -703,6 +731,26 @@ "source": "examples/api/async_capabilities.rb", "region": "main", "language": "ruby" + }, + { + "id": "default_session", + "source": "examples/default_session.rb", + "language": "ruby" + }, + { + "id": "lifecycle", + "source": "examples/lifecycle.rb", + "language": "ruby" + }, + { + "id": "lifecycle_discovery", + "source": "examples/lifecycle_discovery.rb", + "language": "ruby" + }, + { + "id": "lifecycle_server", + "source": "examples/lifecycle_server.rb", + "language": "ruby" } ] } diff --git a/gems/libtmux-async/lib/libtmux/async/control.rb b/gems/libtmux-async/lib/libtmux/async/control.rb index c4df187..16ee922 100644 --- a/gems/libtmux-async/lib/libtmux/async/control.rb +++ b/gems/libtmux-async/lib/libtmux/async/control.rb @@ -77,7 +77,7 @@ def initialize(scope:, binding:, session_id:, reconnect: nil, **limits) @startup_changed = ::Async::Notification.new @exchanges, @exchange_changed = {}, ::Async::Notification.new initialize_state(binding_key: binding.key, session_id: session_id, reconnect: reconnect, **limits) - @driver = ControlDriver.new(self, scope, binding.command_prefix + ["-C", "attach-session", "-t", session_id]) + @driver = ControlDriver.new(self, scope, binding.command_prefix + ["-C", "attach-session", "-t", session_id], binding.environment) @worker = ::Async::Task.new(scope.__send__(:parent)) { @driver.call } end @@ -259,9 +259,9 @@ def finish_transport(failure, errors = nil) end class ControlDriver < ProcessDriver - def initialize(connection, scope, argv) + def initialize(connection, scope, argv, environment) super(scope, nil, argv.freeze, "".b, Float::INFINITY, nil, - {cleanup_timeout: 0.4, drain_timeout: 0.1}) + {cleanup_timeout: 0.4, drain_timeout: 0.1}, environment: environment) @connection = connection end diff --git a/gems/libtmux-async/lib/libtmux/async/process.rb b/gems/libtmux-async/lib/libtmux/async/process.rb index 7f56399..7eb8fc7 100644 --- a/gems/libtmux-async/lib/libtmux/async/process.rb +++ b/gems/libtmux-async/lib/libtmux/async/process.rb @@ -11,9 +11,10 @@ class ProcessDriver attr_reader :pid, :result - def initialize(scope, ticket, argv, input, deadline, cancel, limits, stdout_tail: nil) + def initialize(scope, ticket, argv, input, deadline, cancel, limits, environment:, stdout_tail: nil) @scope, @ticket, @argv, @input = scope, ticket, argv, input @deadline, @cancel, @limits = deadline, cancel, limits + @environment = environment @started = clock @changed = ::Async::Notification.new @tasks, @streams = [], [] @@ -175,8 +176,8 @@ def spawn @stderr, error = pipe @child = Internal::OwnedChild.new begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, [@argv.first, @argv.first], *@argv.drop(1), - in: input, out: output, err: error, close_others: true) + @pid = Process.spawn(@environment, [@argv.first, @argv.first], *@argv.drop(1), + in: input, out: output, err: error, close_others: true, unsetenv_others: true) ensure @child.spawned(@pid) end diff --git a/gems/libtmux-async/lib/libtmux/async/scope.rb b/gems/libtmux-async/lib/libtmux/async/scope.rb index 2210551..d5cfb75 100644 --- a/gems/libtmux-async/lib/libtmux/async/scope.rb +++ b/gems/libtmux-async/lib/libtmux/async/scope.rb @@ -304,7 +304,7 @@ def execute(argv, input: "".b, timeout: 5.0, cancel: nil, stdout_tail: nil) @waiting << ticket @queued_bytes += bytes ticket.execution = ProcessDriver.new(self, ticket, argv.map { |arg| arg.dup.freeze }.freeze, - input.b.freeze, deadline, cancel, @limits, stdout_tail: stdout_tail) + input.b.freeze, deadline, cancel, @limits, environment: @server.endpoint.environment, stdout_tail: stdout_tail) ticket.task = ::Async::Task.new(@parent) do begin ticket.result = ticket.execution.call diff --git a/gems/libtmux-async/lib/libtmux/async/server.rb b/gems/libtmux-async/lib/libtmux/async/server.rb index 82d822c..f814f96 100644 --- a/gems/libtmux-async/lib/libtmux/async/server.rb +++ b/gems/libtmux-async/lib/libtmux/async/server.rb @@ -62,6 +62,14 @@ def self.open(**) raise UnsupportedFeatureError.new("open the core server, then call LibTmux::Async.open(server:) to get an Async facade", phase: :admission) end + def self.find_or_create(**) + raise UnsupportedFeatureError.new("find or create a core server before opening its Async scope", phase: :admission) + end + + def self.discover(**options) + LibTmux::Server.discover(**options) + end + private_class_method :new private @@ -79,6 +87,51 @@ def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false Internal::TmuxVersion.check_fence(result, marker, @release) end + # Core ownership retains the same pinned binding. Async cancellation waits + # for receipt handoff; cleanup can still run after this scope was cancelled. + def lifecycle_execute(program, names, budget) + @source.__send__(:lifecycle_execute, program, names, budget) + end + + def destroy_owned(receipt, timeout:) + ::Async::Task.current.defer_cancel do + @source.__send__(:destroy_owned, receipt, timeout: timeout) + end + end + + def acquire_owned(*arguments, **options, &block) + owner = nil + begin + ::Async::Task.current.defer_cancel { owner = super(*arguments, **options, &nil) } + rescue Exception => failure + rollback_owner(owner, failure) if owner + raise + end + block ? owner.use(&block) : owner + end + + def adopt_resource(*arguments, **options, &block) + owner = nil + begin + ::Async::Task.current.defer_cancel { owner = super(*arguments, **options, &nil) } + rescue Exception => failure + rollback_owner(owner, failure) if owner + raise + end + block ? owner.use(&block) : owner + end + + def find_or_create_entity(*arguments, **options) + acquisition = nil + begin + ::Async::Task.current.defer_cancel { acquisition = super } + rescue Exception => failure + rollback_owner(acquisition.owner, failure) if acquisition&.owner + raise + end + acquisition + end + def ensure_owner @scope.__send__(:ensure_owner) end diff --git a/gems/libtmux-async/sig/libtmux-async.rbs b/gems/libtmux-async/sig/libtmux-async.rbs index f9c1a94..bae1e2b 100644 --- a/gems/libtmux-async/sig/libtmux-async.rbs +++ b/gems/libtmux-async/sig/libtmux-async.rbs @@ -45,6 +45,8 @@ module LibTmux def attach: (**untyped) -> bot def self.start: (**untyped) -> bot def self.open: (**untyped) -> bot + def self.find_or_create: (**untyped) -> bot + def self.discover: (**untyped) -> LibTmux::DiscoveryResult end class ControlConnection < LibTmux::ControlConnection diff --git a/gems/libtmux/README.md b/gems/libtmux/README.md index 70b2e3e..6b39cea 100644 --- a/gems/libtmux/README.md +++ b/gems/libtmux/README.md @@ -512,6 +512,29 @@ sessions after client close: 1 See [ownership and errors](../../docs/ownership-errors.md). +### Own a session + +`with_session` removes the session it creates when the block exits. + + +```ruby +# frozen_string_literal: true + +require "libtmux" +require "securerandom" + +LibTmux::Server.open do |server| + server.with_session(name: "ruby-example-#{SecureRandom.hex(4)}", command: ["/bin/cat"]) do |session| + puts "session windows: #{session.list_windows.length}" + end +end +``` + + +Use `env: ENV.to_h.merge(...)` on `Server.open` to override the captured +child environment. See the [endpoint contract](../../docs/reference/behavior.md#endpoints) +and [lifecycle operations](../../docs/lifecycle.md). + ## Wait, time out, and cancel ### [`Cancellation.new`][cancellation-new]: wake a request that is waiting diff --git a/gems/libtmux/lib/libtmux.rb b/gems/libtmux/lib/libtmux.rb index 6e1569e..ada9eff 100644 --- a/gems/libtmux/lib/libtmux.rb +++ b/gems/libtmux/lib/libtmux.rb @@ -16,6 +16,7 @@ require "libtmux/control" require "libtmux/group" require "libtmux/owned" +require "libtmux/lifecycle" require "libtmux/terminal" require "libtmux/text_wait" require "libtmux/program" diff --git a/gems/libtmux/lib/libtmux/control.rb b/gems/libtmux/lib/libtmux/control.rb index 6a221f5..b48ece9 100644 --- a/gems/libtmux/lib/libtmux/control.rb +++ b/gems/libtmux/lib/libtmux/control.rb @@ -393,11 +393,11 @@ def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_comm process_wait = Internal::ProcessWait.new prefix = binding.command_prefix release = binding.release || Internal::TmuxVersion.connected(prefix) do |probe| - Internal::ProcessExecutor.new.run(probe, timeout: 5.0) + Internal::ProcessExecutor.new.run(probe, env: binding.environment, replace_env: true, timeout: 5.0) end Internal::TmuxVersion.require_control(release) @release = release - @pin = Internal::SocketIdentity.new(Endpoint.new(socket_path: prefix.last, executable: prefix.first)) + @pin = Internal::SocketIdentity.new(Endpoint.new(socket_path: prefix.last, executable: prefix.first, env: binding.environment)) @wake_reader, @wake_writer = pipe input_reader, @input = pipe @output, output_writer = pipe @@ -406,9 +406,9 @@ def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_comm @exit_reader = @child.reader @resources << @exit_reader begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, + @pid = Process.spawn(binding.environment, *@pin.command_prefix, "-C", "attach-session", "-t", session_id, - in: input_reader, out: output_writer, err: error_writer, close_others: true) + in: input_reader, out: output_writer, err: error_writer, close_others: true, unsetenv_others: true) ensure @child.spawned(@pid) end diff --git a/gems/libtmux/lib/libtmux/endpoint.rb b/gems/libtmux/lib/libtmux/endpoint.rb index 80fe6ff..449145f 100644 --- a/gems/libtmux/lib/libtmux/endpoint.rb +++ b/gems/libtmux/lib/libtmux/endpoint.rb @@ -5,7 +5,7 @@ require_relative "errors" module LibTmux - # Executable and socket selection. Construction starts no clients. + # Captured executable, child environment and socket. Construction starts no clients. # # {#initialize Endpoint.new} takes a `socket_path:` or a `socket_name:`. # With neither, it picks the socket as tmux does when it is given none, and @@ -14,17 +14,25 @@ module LibTmux # socket `TMUX` names when run inside tmux, else tmux's `default` socket. A # variable that is empty counts as unset, and a socket given as an argument # ignores the variables. {.from_env} skips the `LIBTMUX_*` variables. + # `env:` supplies both selection variables and the complete child environment. + # Without it, child processes receive the captured process environment. class Endpoint - attr_reader :executable, :socket_path + attr_reader :executable, :socket_path, :environment - def initialize(socket_path: nil, socket_name: nil, executable: "tmux", socket_directory: nil, environment: ENV) + def initialize(socket_path: nil, socket_name: nil, executable: "tmux", socket_directory: nil, environment: ENV, env: nil) unless socket_path.nil? || socket_name.nil? raise ArgumentError, "choose at most one socket_path or socket_name" end - origin = path_label = nil + unless env.nil? + raise ArgumentError, "env must provide a complete environment map" unless env.respond_to?(:to_h) + + env = env.to_h + end + selection = env || environment + origin = nil if socket_path.nil? && socket_name.nil? raise ArgumentError, "socket_directory applies only to socket_name" if socket_directory - socket_path, socket_name, origin = Internal::SocketChoice.call(environment) + socket_path, socket_name, origin = Internal::SocketChoice.call(selection) end if socket_name label = origin || "socket_name" @@ -32,16 +40,15 @@ def initialize(socket_path: nil, socket_name: nil, executable: "tmux", socket_di if socket_name.include?("/") || [".", ".."].include?(socket_name) raise ArgumentError, "#{label} must be a single filename" end - directory = socket_directory || Internal::SocketChoice.present(environment["TMUX_TMPDIR"]) || "/tmp" - validate_string(directory, "socket_directory") - path_label = socket_directory ? "socket_directory" : "TMUX_TMPDIR" - socket_path = File.join(directory, "tmux-#{Process.uid}", socket_name) + @named_directory = named_socket_directory(socket_directory, selection).freeze + socket_path = File.join(@named_directory, socket_name) elsif socket_directory raise ArgumentError, "socket_directory applies only to socket_name" end validate_string(socket_path, origin || "socket_path") validate_string(executable, "executable") - @socket_path = expand(socket_path, path_label || origin || "socket_path").freeze + @socket_path = socket_location(socket_path, origin || "socket_path").freeze + @environment = capture_environment(env || ENV.to_h) @executable = resolve_executable(executable).freeze freeze end @@ -68,6 +75,53 @@ def inspect private + def named_socket_directory(socket_directory, selection) + directory = socket_directory || Internal::SocketChoice.present(selection["TMUX_TMPDIR"]) || "/tmp" + label = socket_directory ? "socket_directory" : "TMUX_TMPDIR" + validate_string(directory, label) + File.join(socket_location(directory, label), "tmux-#{Process.uid}") + end + + # Resolve relative and home paths without collapsing filesystem traversal. + def socket_location(path, label) + return path.dup if path.start_with?("/") + return File.join(Dir.pwd, path) unless path.start_with?("~") + + home, suffix = path.split("/", 2) + directory = expand(home, label) + suffix ? File.join(directory, suffix) : directory + end + + def capture_environment(environment) + environment.each_with_object({}) do |(key, value), captured| + validate_string(key, "environment key") + raise ArgumentError, "environment keys cannot contain =" if key.include?("=") + next if value.nil? || key == "TMUX" || key == "TMUX_PANE" + unless value.is_a?(String) && !value.include?("\0") + raise ArgumentError, "environment values must be Strings without NUL, or nil" + end + captured[key.dup.freeze] = value.dup.freeze + end.freeze + end + + def prepare_directory + return unless @named_directory + + begin + Dir.mkdir(@named_directory, 0o700) + rescue Errno::EEXIST + nil + end + validate_directory + end + + def validate_directory + stat = File.lstat(@named_directory) + unless stat.directory? && stat.uid == Process.uid && (stat.mode & 0o007).zero? + raise ArgumentError, "named socket directory must be a real directory owned by the current UID without other-user permissions" + end + end + # File.expand_path puts the user it cannot find in its message, so the # message here names the argument or variable instead. def expand(path, label, base = nil) @@ -86,7 +140,7 @@ def resolve_executable(value) candidates = if value.include?(File::SEPARATOR) [expand(value, "executable")] else - ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map do |directory| + @environment.fetch("PATH") { ENV.fetch("PATH", "") }.split(File::PATH_SEPARATOR).map do |directory| expand(value, "executable", directory.empty? ? Dir.pwd : directory) end end @@ -129,10 +183,11 @@ def present(value) # Keep the socket inode alive and route through it; PID timestamps can repeat. class SocketIdentity - attr_reader :key, :release + attr_reader :key, :release, :environment def initialize(endpoint) @endpoint = endpoint + @environment = endpoint.environment @owner_pid = Process.pid @mutex = Mutex.new @closed = false diff --git a/gems/libtmux/lib/libtmux/errors.rb b/gems/libtmux/lib/libtmux/errors.rb index 7c58604..1c16f23 100644 --- a/gems/libtmux/lib/libtmux/errors.rb +++ b/gems/libtmux/lib/libtmux/errors.rb @@ -27,6 +27,17 @@ def attach_wait_text(text) end end + # Retains both exceptions when a resource block and its cleanup fail. + class CleanupError < Error + attr_reader :body_error, :cleanup_error, :recovery + + def initialize(body_error:, cleanup_error:, recovery: nil) + @body_error, @cleanup_error, @recovery = body_error, cleanup_error, recovery + super("resource body and cleanup failed", phase: :retire, delivery: :possibly_sent, + cleanup_errors: ["resource cleanup failed (#{cleanup_error.class})"]) + end + end + class InvalidFilterError < Error def initialize(message = "invalid filter", entity: nil, path: "$", expected: nil, **details) super("#{message} at #{path}#{expected ? "; expected #{expected}" : ""}", diff --git a/gems/libtmux/lib/libtmux/lifecycle.rb b/gems/libtmux/lib/libtmux/lifecycle.rb new file mode 100644 index 0000000..3c20fb6 --- /dev/null +++ b/gems/libtmux/lib/libtmux/lifecycle.rb @@ -0,0 +1,624 @@ +# frozen_string_literal: true + +require "libtmux/owned" + +module LibTmux + # Evidence accepted through one retained socket route. The reserved server + # option must not be changed or shadowed while an owner remains open. + class OwnershipReceipt + attr_reader :kind, :id, :pid, :started_at, :generation + + def initialize(kind:, id:, pid:, started_at:, generation:) + @kind, @id, @pid, @started_at = kind, id&.dup&.freeze, pid, started_at + @generation = generation.dup.freeze + freeze + end + private_class_method :new + end + + # Explicit responsibility for destroying a remote resource. The borrowed + # client must remain open until close succeeds. Failed close remains retryable. + class OwnedResource + attr_reader :resource, :receipt, :cleanup_error + + def initialize(resource, receipt) + @resource, @receipt = resource, receipt + @mutex = Mutex.new + @closed = false + @destroyed = false + @cleanup_error = nil + end + private_class_method :new + + def closed? + @mutex.synchronize { @closed } + end + + def close(timeout: 5.0) + previous = Thread.current[:libtmux_lifecycle_cleanup] + Thread.current[:libtmux_lifecycle_cleanup] = true + Thread.handle_interrupt(Exception => :never) do + @mutex.synchronize do + return nil if @closed + + begin + server = resource.is_a?(Server) ? resource : resource.server + unless @destroyed + server.__send__(:destroy_owned, receipt, timeout: timeout) + @destroyed = true + end + server.close if receipt.kind == :server && server.owned? + @closed = true + @cleanup_error = nil + rescue Exception => error + @cleanup_error = error + raise + end + end + end + nil + ensure + Thread.current[:libtmux_lifecycle_cleanup] = previous + end + + # Ruby block exit, including raise/throw/break, releases this resource. + # CleanupError preserves both failures and exposes this owner for retry. + def use + raise ArgumentError, "use requires a block" unless block_given? + + failure = nil + Thread.handle_interrupt(Exception => :never) do + begin + Thread.handle_interrupt(Exception => :immediate) { yield resource } + rescue Exception => error + failure = error + raise + ensure + begin + close + rescue Exception => cleanup + raise CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: self) if failure + + raise + end + end + end + end + end + + # A reused resource has no owner. Call resource.adopt to accept destruction. + class Acquisition + attr_reader :resource, :owner + + def initialize(resource:, owner: nil) + @resource, @owner = resource, owner + freeze + end + private_class_method :new + + def created? + !owner.nil? + end + + def use + raise ArgumentError, "use requires a block" unless block_given? + + owner ? owner.use { |resource| yield resource } : yield(resource) + end + end + + class DiscoveredServer + attr_reader :endpoint, :pid, :started_at + + def initialize(endpoint:, pid:, started_at:) + @endpoint, @pid, @started_at = endpoint, pid, started_at + freeze + end + private_class_method :new + end + + class DiscoveryResult + attr_reader :servers, :diagnostics, :entries, :probes + + def initialize(servers:, diagnostics:, entries:, probes:, truncated:) + @servers = servers.freeze + @diagnostics = diagnostics.map { |record| record.transform_values { |value| value.is_a?(String) ? value.dup.freeze : value }.freeze }.freeze + @entries, @probes, @truncated = entries, probes, truncated + freeze + end + private_class_method :new + + def truncated? + @truncated + end + end + + class Entity + # Killing a window removes every link and its panes, including linked copies. + # A lookup alone never adopts an object. WindowLink is not an ownership target. + def adopt(timeout: 5.0, cancel: nil, &block) + server.__send__(:adopt_resource, self, timeout: timeout, cancel: cancel, &block) + end + end + + class Session + def owned_window(name:, command:, **options, &block) + server.__send__(:acquire_owned, :window, self, name: name, command: command, **options, &block) + end + + # Exact window name in this session; two linked windows with that name fail. + def find_or_create_window(name:, command:, timeout: 5.0, **options) + server.__send__(:find_or_create_entity, :window, self, name: name, command: command, timeout: timeout, **options) + end + end + + class Window + def owned_pane(direction:, command:, **options, &block) + server.__send__(:acquire_owned, :pane, self, direction: direction, command: command, **options, &block) + end + + # Identity is stored in the local pane option @libtmux_pane_identity. + # Match within this window; identity is literal text, not a tmux format. + def find_or_create_pane(identity:, direction:, command:, timeout: 5.0, **options) + server.__send__(:find_or_create_entity, :pane, self, identity: identity, direction: direction, + command: command, timeout: timeout, **options) + end + end + + class Pane + def owned_pane(direction:, command:, **options, &block) + server.__send__(:acquire_owned, :pane, self, direction: direction, command: command, **options, &block) + end + end + + class Server + # Scans direct entries, without following symlinks, beneath explicit roots + # or the captured current-user roots. Probes use retained routes and -N. + # The entry bound counts roots too; errors and exhausted bounds are visible. + def self.discover(roots: nil, env: ENV, executable: "tmux", max_entries: 256, max_probes: 64, timeout: 1.0, probe_timeout: 0.1) + unless [max_entries, max_probes].all? { |value| value.is_a?(Integer) && value.positive? } && + [timeout, probe_timeout].all? { |value| value.is_a?(Numeric) && value.finite? && value.positive? } + raise ArgumentError, "discovery bounds must be positive and finite" + end + selected = Endpoint.new(env: env, executable: executable) + captured = selected.environment + servers, diagnostics, seen = [], [], {} + if roots.nil? + roots = [File.dirname(selected.socket_path)] + begin + roots << selected.__send__(:named_socket_directory, nil, captured) + rescue ArgumentError => error + diagnostics << {path: "TMUX_TMPDIR", reason: :root_failed, error: error.class.name} + end + roots << "/tmp/tmux-#{Process.uid}" + end + unless roots.is_a?(Array) && roots.all? { |root| root.is_a?(String) && root.start_with?("/") && !root.include?("\0") } + raise ArgumentError, "roots must be an Array of absolute directory paths" + end + entries = probes = 0 + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout + truncated = false + bounded = lambda do |path| + reason = if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + :time_bound + elsif entries >= max_entries + :entry_bound + end + if reason + truncated = true + diagnostics << {path: path, reason: reason} + true + else + entries += 1 + false + end + end + catch(:bounded) do + roots.uniq.each do |root| + throw :bounded if bounded.call(root) + begin + stat = File.lstat(root) + unless stat.directory? && !stat.symlink? + diagnostics << {path: root, reason: :not_directory} + next + end + Dir.open(root) do |directory| + directory.each_child do |name| + path = File.join(root, name) + throw :bounded if bounded.call(path) + begin + stat = File.lstat(path) + unless stat.socket? + diagnostics << {path: path, reason: stat.symlink? ? :symlink : :not_socket} + next + end + identity = [stat.dev, stat.ino] + if seen[identity] + diagnostics << {path: path, reason: :duplicate_socket} + next + end + seen[identity] = true + if probes >= max_probes + truncated = true + diagnostics << {path: path, reason: :probe_bound} + throw :bounded + end + probes += 1 + endpoint = Endpoint.new(socket_path: path, executable: selected.executable, env: captured) + probe_deadline = [deadline, Process.clock_gettime(Process::CLOCK_MONOTONIC) + probe_timeout].min + remaining = probe_deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + raise DeadlineExceeded.new("discovery time bound elapsed", phase: :admission) unless remaining.positive? + # Binding checks the version and fence in two native calls. + open(endpoint: endpoint, version_timeout: remaining / 2) do |server| + remaining = probe_deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + output = server.display("\#{pid}|\#{start_time}", timeout: remaining).stdout + match = /\A([1-9][0-9]*)\|([0-9]+)\n/n.match(output) + raise ProtocolError.new("probe did not return a daemon identity", phase: :decode, delivery: :observed) unless match + servers << DiscoveredServer.__send__(:new, endpoint: endpoint, pid: Integer(match[1], 10), started_at: Integer(match[2], 10)) + end + rescue StandardError => error + diagnostics << {path: path, reason: :probe_failed, error: error.class.name} + end + end + end + rescue SystemCallError => error + diagnostics << {path: root, reason: :root_failed, error: error.class.name} + end + end + end + DiscoveryResult.__send__(:new, servers: servers, diagnostics: diagnostics, entries: entries, probes: probes, truncated: truncated) + end + + # Adopts this daemon; client close still only retires client transports. + def adopt(timeout: 5.0, cancel: nil, &block) + adopt_resource(self, timeout: timeout, cancel: cancel, &block) + end + + def owned_session(name:, command:, **options, &block) + acquire_owned(:session, nil, name: name, command: command, **options, &block) + end + + # Calls through these APIs serialize within one Ruby process, across handles. + # Other processes and raw tmux commands do not participate in this boundary. + def find_or_create_session(name:, command:, timeout: 5.0, **options) + find_or_create_entity(:session, nil, name: name, command: command, timeout: timeout, **options) + end + + # Existing endpoints are borrowed. Atomic hard-link publication refuses an + # occupied pathname; stale sockets and ordinary files are not removed. + def self.find_or_create(endpoint: nil, timeout: 5.0, config: nil, **options) + raise ArgumentError, "endpoint cannot be combined with endpoint options" if endpoint && !options.empty? + endpoint ||= Endpoint.new(**options) + + Internal.const_get(:LifecycleGate, false).synchronize(timeout: timeout) do |remaining| + Thread.handle_interrupt(Exception => :never) do + server = owner = nil + begin + begin + server = new(endpoint: endpoint, version_timeout: remaining.call / 2) + # Binding an inode does not prove that a stale socket is alive. + server.display("\#{pid}", timeout: remaining.call) + result = Acquisition.__send__(:new, resource: server) + rescue TargetNotFoundError + raise if File.exist?(endpoint.socket_path) || File.symlink?(endpoint.socket_path) + + server = start(endpoint: endpoint, config: config, timeout: remaining.call) + owner = server.adopt(timeout: remaining.call) + result = Acquisition.__send__(:new, resource: server, owner: owner) + end + Thread.handle_interrupt(Exception => :immediate) { nil } + result + rescue Exception => failure + begin + server&.close + rescue Exception => cleanup + raise CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: owner) + end + raise + end + end + end + end + + private + + OWNER_OPTION = "@libtmux_owner_generation" + PANE_IDENTITY = "@libtmux_pane_identity" + private_constant :OWNER_OPTION, :PANE_IDENTITY + + def lifecycle_format(kind) + id = kind == :server ? "server" : "\#{#{kind}_id}" + "\#{pid}|\#{start_time}|\#{#{OWNER_OPTION}}|#{id}" + end + + def lifecycle_names(budget, *commands) + builtin_spellings("if-shell", "display-message", "set-option", *commands, budget: budget) + end + + def lifecycle_initialize(names) + tmux_command([names.fetch("set-option"), "-soq", OWNER_OPTION, SecureRandom.hex(16)]) + end + + def lifecycle_valid_generation + "\#{&&:\#{==:\#{n:#{OWNER_OPTION}},32},\#{m/r:^[0-9a-fA-F]+$,\#{#{OWNER_OPTION}}}}" + end + + # An owned mutation defers Ruby asynchronous exceptions until its receipt + # has been decoded. Deadline/transport failure still reports unknown outcome. + def lifecycle_execute(program, names, budget) + arguments = encode_arguments([names.fetch("if-shell"), "-F", "1", program]) + dispatch(arguments, timeout: budget.options.fetch(:timeout), interruptible: false) + end + + def lifecycle_receipt(text, kind) + prefix = {server: "server", session: "\\$[0-9]+", window: "@[0-9]+", pane: "%[0-9]+"}.fetch(kind) + match = /\A([1-9][0-9]*)\|([0-9]+)\|([0-9a-fA-F]{32})\|(#{prefix})\n/n.match(text) + unless match + raise OutcomeUnknown.new("owned #{kind} command returned no complete receipt; inspect the retained endpoint before recovery", + phase: :decode, delivery: :possibly_sent) + end + receipt = OwnershipReceipt.__send__(:new, kind: kind, id: kind == :server ? nil : match[4], + pid: Integer(match[1], 10), started_at: Integer(match[2], 10), generation: match[3]) + [receipt, match[0].bytesize] + end + + def owner_from_output(result, kind) + if result.stdout == "invalid-owner-generation\n" + raise ProtocolError.new("reserved owner generation is empty or malformed", phase: :admission, delivery: :observed) + end + receipt, consumed = lifecycle_receipt(result.stdout, kind) + resource = kind == :server ? self : build_entity(kind, receipt.id) + owner = OwnedResource.__send__(:new, resource, receipt) + if consumed != result.stdout.bytesize + begin + raise ProtocolError.new("owned command returned extra receipt data", phase: :decode, delivery: :observed) + rescue Exception => failure + rollback_owner(owner, failure) + end + end + owner + end + + def rollback_owner(owner, failure) + begin + owner.close + rescue Exception => cleanup + raise CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: owner) + end + raise failure + end + + def adopt_resource(resource, timeout:, cancel:, &block) + kind = resource.equal?(self) ? :server : resource.ref.kind + raise ArgumentError, "adopt requires a server, session, window or pane" unless %i[server session window pane].include?(kind) + id = kind == :server ? nil : target(resource.ref, kind) + owner = nil + Thread.handle_interrupt(Exception => :never) do + begin + budget = operation_budget(timeout, cancel) + names = lifecycle_names(budget) + show = [names.fetch("display-message"), "-p", *(["-t", id] if id), "--", lifecycle_format(kind)] + guard = kind == :server ? lifecycle_valid_generation : "\#{&&:#{lifecycle_valid_generation},\#{==:\#{#{kind}_id},#{id}}}" + command = tmux_command([names.fetch("if-shell"), "-F", *(["-t", id] if id), guard, + tmux_command(show), tmux_command([names.fetch("display-message"), "-p", "invalid-owner-target"])]) + result = lifecycle_execute([lifecycle_initialize(names), command].join(" ; "), names, budget) + raise CommandError.new(result: result, phase: :command) unless result.success? + if result.stdout == "invalid-owner-target\n" + raise TargetNotFoundError.new("adoption target or reserved generation is invalid", phase: :admission, delivery: :observed) + end + receipt, count = lifecycle_receipt(result.stdout, kind) + raise ProtocolError.new("adoption returned extra receipt data", phase: :decode, delivery: :observed) unless count == result.stdout.bytesize + + owner = OwnedResource.__send__(:new, resource, receipt) + raise Cancelled.new("adoption cancelled after ownership acceptance", phase: :handoff, delivery: :observed) if cancel&.cancelled? + Thread.handle_interrupt(Exception => :immediate) { nil } + rescue Exception => failure + rollback_owner(owner, failure) if owner + raise + end + block ? owner.use(&block) : owner + end + end + + def acquire_owned(kind, parent, timeout: 5.0, cancel: nil, **options, &block) + owner = nil + Thread.handle_interrupt(Exception => :never) do + begin + budget = operation_budget(timeout, cancel) + command = {session: "new-session", window: "new-window", pane: "split-window"}.fetch(kind) + names = lifecycle_names(budget, command) + arguments = owned_arguments(kind, parent, options) + body = tmux_command([names.fetch(command), *arguments]) + checked = tmux_command([names.fetch("if-shell"), "-F", lifecycle_valid_generation, body, + tmux_command([names.fetch("display-message"), "-p", "invalid-owner-generation"])]) + result = lifecycle_execute([lifecycle_initialize(names), checked].join(" ; "), names, budget) + if !result.success? && result.stdout.empty? + raise CommandError.new(result: result, phase: :command) + end + owner = owner_from_output(result, kind) + raise CommandError.new(result: result, phase: :command) unless result.success? + raise Cancelled.new("owned acquisition cancelled after creation", phase: :handoff, delivery: :observed) if cancel&.cancelled? + Thread.handle_interrupt(Exception => :immediate) { nil } + rescue Exception => failure + rollback_owner(owner, failure) if owner + raise + end + block ? owner.use(&block) : owner + end + end + + def owned_arguments(kind, parent, options) + options = options.dup + command = pane_command(options.delete(:command)) + arguments = ["-d", "-P", "-F", lifecycle_format(kind)] + if kind == :pane + direction = {horizontal: "-h", vertical: "-v"}.fetch(options.delete(:direction)) { raise ArgumentError, "direction must be :horizontal or :vertical" } + arguments << direction + arguments.concat(["-t", target(parent.ref, parent.ref.kind)]) + size = options.delete(:size) + if size + unless (size.is_a?(Integer) && size.between?(1, (1 << 31) - 1)) || + (size.is_a?(String) && size.match?(/\A(?:[1-9][0-9]?|100)%\z/)) + raise ArgumentError, "size must be positive cells or a percentage from 1% to 100%" + end + arguments.concat(["-l", size.to_s]) + end + else + name = literal_name(options.delete(:name)) + arguments.concat([kind == :session ? "-s" : "-n", name]) + if kind == :session + window_name = options.delete(:window_name) + arguments.concat(["-n", literal_name(window_name)]) if window_name + {width: "-x", height: "-y"}.each do |key, flag| + value = options.delete(key) + next unless value + raise ArgumentError, "dimensions must be positive integers" unless value.is_a?(Integer) && value.positive? + arguments.concat([flag, value.to_s]) + end + else + destination = target(parent.ref, :session) + index = options.delete(:index) + if index + raise ArgumentError, "index must be a nonnegative 32-bit Integer" unless index.is_a?(Integer) && index.between?(0, (1 << 31) - 1) + destination += ":#{index}" + end + arguments.concat(["-t", destination]) + end + end + focus = options.delete(:focus) + raise ArgumentError, "focus must be boolean" unless [nil, true, false].include?(focus) + arguments.delete("-d") if focus + arguments.concat(creation_options(cwd: options.delete(:cwd), environment: options.delete(:environment) || {})) + raise ArgumentError, "unknown owned creation options: #{options.keys.join(', ')}" unless options.empty? + + [*arguments, "--", *command] + end + + def destroy_owned(receipt, timeout:) + budget = operation_budget(timeout, nil) + command = "kill-#{receipt.kind}" + names = lifecycle_names(budget, command) + identity = "\#{&&:\#{==:\#{pid},#{receipt.pid}},\#{&&:\#{==:\#{start_time},#{receipt.started_at}},\#{==:\#{#{OWNER_OPTION}},#{receipt.generation}}}}" + marker = "owner-replaced-#{SecureRandom.hex(16)}" + missing = "owner-absent-#{SecureRandom.hex(16)}" + failure = tmux_command([names.fetch("display-message"), "-p", marker]) + kill = tmux_command([names.fetch(command), *(["-t", receipt.id] if receipt.id)]) + if receipt.id + present = "\#{==:\#{#{receipt.kind}_id},#{receipt.id}}" + kill = tmux_command([names.fetch("if-shell"), "-F", "-t", receipt.id, present, kill, + tmux_command([names.fetch("display-message"), "-p", missing])]) + end + program = tmux_command([names.fetch("if-shell"), "-F", identity, kill, failure]) + result = lifecycle_execute(program, names, budget) + raise CommandError.new(result: result, phase: :command) unless result.success? + if result.stdout == "#{marker}\n" + raise TargetNotFoundError.new("owned daemon generation changed; refusing destruction", phase: :command, delivery: :observed) + end + unless result.stdout.empty? || result.stdout == "#{missing}\n" + raise ProtocolError.new("owned destruction returned unexpected output", phase: :decode, delivery: :observed) + end + nil + end + + def find_or_create_entity(kind, parent, timeout:, cancel: nil, **options) + budget = operation_budget(timeout, cancel) + Internal.const_get(:LifecycleGate, false).synchronize(timeout: timeout, cancel: cancel) do + owner = nil + Thread.handle_interrupt(Exception => :never) do + begin + name = options[kind == :pane ? :identity : :name] + literal_name(name) + if (kind == :session && name.match?(/[.:]/)) || (kind != :pane && name.match?(/[\\\x00-\x1f\x7f]/)) + raise ArgumentError, "exact names cannot contain characters rewritten by tmux: backslash and controls, or dot and colon in session names" + end + entities = case kind + when :session then list_sessions(**budget.options) + when :window then parent.list_windows(**budget.options) + when :pane then parent.list_panes(**budget.options) + end + field = kind == :pane ? PANE_IDENTITY : "#{kind}_name" + matches = entities.select { |entity| lifecycle_value(entity, field, **budget.options) == name.b } + raise MultipleMatchesError.new("multiple #{kind}s match the exact #{kind == :pane ? 'pane identity' : 'name'}", phase: :admission) if matches.length > 1 + if matches.length == 1 + result = Acquisition.__send__(:new, resource: matches.first) + else + create_options = options.reject { |key, _| key == :identity } + owner = acquire_owned(kind, parent, **create_options, **budget.options) + if kind == :pane + owner.resource.options.set(PANE_IDENTITY, name, **budget.options) + actual = lifecycle_value(owner.resource, field, **budget.options) + raise ProtocolError.new("created pane did not retain its identity", phase: :decode, delivery: :observed) unless actual == name.b + end + result = Acquisition.__send__(:new, resource: owner.resource, owner: owner) + end + raise Cancelled.new("find or create cancelled before handoff", phase: :handoff, delivery: :observed) if cancel&.cancelled? + Thread.handle_interrupt(Exception => :immediate) { nil } + result + rescue Exception => failure + rollback_owner(owner, failure) if owner + raise + end + end + end + end + + def lifecycle_value(entity, field, timeout:, cancel: nil) + if field == PANE_IDENTITY + values = entity.options.list(inherited: false, timeout: timeout, cancel: cancel).select { |value| value.name == field } + return "".b if values.empty? + unless values.length == 1 && !values.first.array? + raise ProtocolError.new("pane identity must be a scalar local option", phase: :decode, delivery: :observed) + end + return values.first.raw + end + output = display(metadata_format([field]), target: entity.ref, timeout: timeout, cancel: cancel).stdout + rows = Internal::Metadata.decode(output, fields: 1, max_rows: 1, quoted: true) + raise ProtocolError.new("lookup did not return one value", phase: :decode, delivery: :observed) unless rows.length == 1 + rows.first.first + end + end + + module Internal + module LifecycleGate + @mutex = Mutex.new + @condition = ConditionVariable.new + @busy = false + class << self + def synchronize(timeout:, cancel: nil) + unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? + raise ArgumentError, "timeout must be positive and finite" + end + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout + remaining = -> do + raise Cancelled.new("find or create cancelled before gate admission", phase: :admission, delivery: :not_sent) if cancel&.cancelled? + seconds = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + raise DeadlineExceeded.new("find-or-create deadline elapsed", phase: :admission) unless seconds.positive? + seconds + end + Thread.handle_interrupt(Exception => :never) do + admitted = false + begin + @mutex.synchronize do + while @busy + seconds = remaining.call + @condition.wait(@mutex, cancel ? [seconds, 0.05].min : seconds) + end + remaining.call + @busy = admitted = true + end + yield remaining + ensure + if admitted + @mutex.synchronize do + @busy = false + @condition.broadcast + end + end + end + end + end + end + end + private_constant :LifecycleGate + end +end diff --git a/gems/libtmux/lib/libtmux/owned.rb b/gems/libtmux/lib/libtmux/owned.rb index 1561958..eedc6e9 100644 --- a/gems/libtmux/lib/libtmux/owned.rb +++ b/gems/libtmux/lib/libtmux/owned.rb @@ -22,7 +22,7 @@ module Internal class OwnedDaemon attr_reader :endpoint - def initialize(executable:, config:, timeout:, cancel:) + def initialize(executable:, config:, timeout:, cancel:, env:, endpoint: nil) unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? raise ArgumentError, "startup timeout must be positive and finite" end @@ -44,13 +44,22 @@ def initialize(executable:, config:, timeout:, cancel:) Thread.handle_interrupt(Exception => :never) do begin check_cancel(cancel) - @directory = Dir.mktmpdir("libtmux-ruby-server-") - @endpoint = Endpoint.new(socket_path: File.join(@directory, "socket"), executable: executable) - if @endpoint.socket_path.bytesize > 103 + if endpoint + endpoint.__send__(:prepare_directory) + directory = File.join(File.dirname(endpoint.socket_path), ".libtmux-#{SecureRandom.hex(5)}") + Dir.mkdir(directory, 0o700) + @directory = directory + else + @directory = Dir.mktmpdir("libtmux-ruby-server-") + end + @launch_endpoint = Endpoint.new(socket_path: File.join(@directory, "socket"), + executable: endpoint ? endpoint.executable : executable, env: endpoint ? endpoint.environment : env) + @endpoint = endpoint || @launch_endpoint + if @launch_endpoint.socket_path.bytesize > 103 || @endpoint.socket_path.bytesize > 103 raise UnsupportedFeatureError.new("owned Unix socket path exceeds the platform limit", phase: :startup) end Internal::TmuxVersion.executable(@endpoint.executable) do |argv| - ProcessExecutor.new.run(argv, timeout: deadline - clock, cancel: cancel) + ProcessExecutor.new.run(argv, env: @endpoint.environment, replace_env: true, timeout: deadline - clock, cancel: cancel) end @readiness = SocketReadiness.new(@directory) @child = OwnedChild.new @@ -58,9 +67,9 @@ def initialize(executable:, config:, timeout:, cancel:) begin check_cancel(cancel) check_deadline(deadline) - pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, - @endpoint.executable, "-u", "-D", *@readiness.arguments, "-S", @endpoint.socket_path, "-f", config, - in: File::NULL, out: File::NULL, err: File::NULL, close_others: true, **@readiness.spawn_options) + pid = Process.spawn(@endpoint.environment, + @endpoint.executable, "-u", "-D", *@readiness.arguments, "-S", @launch_endpoint.socket_path, "-f", config, + in: File::NULL, out: File::NULL, err: File::NULL, close_others: true, unsetenv_others: true, **@readiness.spawn_options) rescue SystemCallError, IOError => error raise TransportError.new("owned daemon could not start (#{error.class})", phase: :spawn), cause: nil ensure @@ -69,12 +78,19 @@ def initialize(executable:, config:, timeout:, cancel:) Thread.handle_interrupt(Exception => :immediate) { await_ready(deadline, cancel) } @readiness.close @readiness.remove_files(@child.pid) + @socket_stat = File.lstat(@launch_endpoint.socket_path) + # Keep the inode allocated until published-path cleanup finishes. + @retained_socket = File.join(@directory, "identity") + File.link(@launch_endpoint.socket_path, @retained_socket) + # Atomic publication refuses existing endpoints, including concurrent owners. + File.link(@launch_endpoint.socket_path, @endpoint.socket_path) if endpoint + @published = true rescue Exception => error failure = error begin close rescue Exception => cleanup - attach_cleanup(failure, cleanup) + failure = CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: self) end end end @@ -85,7 +101,7 @@ def initialize(executable:, config:, timeout:, cancel:) begin Thread.handle_interrupt(Exception => :never) { close } rescue Exception => cleanup - attach_cleanup(failure, cleanup) + failure = CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: self) end raise failure end @@ -124,7 +140,9 @@ def close if !@child || @child.complete? attempt(errors, "startup log removal") { @readiness&.remove_files(@child&.pid) } attempt(errors, "socket removal") do - File.unlink(@endpoint.socket_path) if @endpoint && File.exist?(@endpoint.socket_path) + remove_socket(@endpoint.socket_path) if @published + remove_socket(@launch_endpoint.socket_path) if @launch_endpoint + remove_socket(@retained_socket) if @retained_socket end attempt(errors, "owned directory removal") do Dir.rmdir(@directory) if @directory && File.exist?(@directory) @@ -148,6 +166,15 @@ def close private + def remove_socket(path) + stat = File.lstat(path) + return if @socket_stat && [stat.dev, stat.ino] != [@socket_stat.dev, @socket_stat.ino] + + File.unlink(path) + rescue Errno::ENOENT + nil + end + def await_ready(deadline, cancel) loop do if @child.observed? || @child.observation_error || @child.complete? @@ -195,19 +222,18 @@ def attempt(errors, operation) errors.concat(error.cleanup_errors) if error.is_a?(Error) end - def attach_cleanup(failure, cleanup) - if failure.is_a?(Error) - failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) - end - end end class OwnedServer < Server - def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **options) + def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, env: nil, endpoint: nil, **options) + raise ArgumentError, "endpoint must be an Endpoint" if endpoint && !endpoint.is_a?(Endpoint) + if endpoint && (executable != "tmux" || env) + raise ArgumentError, "endpoint cannot be combined with executable or env options" + end begin Thread.handle_interrupt(Exception => :never) do @startup_budget = operation_budget(timeout, cancel) - @daemon = OwnedDaemon.new(executable: executable, config: config, timeout: timeout, cancel: cancel) + @daemon = OwnedDaemon.new(executable: executable, config: config, timeout: timeout, cancel: cancel, env: env || ENV, endpoint: endpoint) super(endpoint: @daemon.endpoint, **options) @binding_ready = true @startup_budget.options @@ -217,7 +243,7 @@ def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **opt begin Thread.handle_interrupt(Exception => :never) { close } rescue Exception => cleanup - failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) if failure.is_a?(Error) + failure = CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: self) end raise failure ensure @@ -241,8 +267,7 @@ def close begin @daemon&.close rescue Exception => cleanup - failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) if failure.is_a?(Error) - failure ||= cleanup + failure = failure ? CleanupError.new(body_error: failure, cleanup_error: cleanup, recovery: self) : cleanup end end end diff --git a/gems/libtmux/lib/libtmux/process.rb b/gems/libtmux/lib/libtmux/process.rb index 1de5af1..561a41a 100644 --- a/gems/libtmux/lib/libtmux/process.rb +++ b/gems/libtmux/lib/libtmux/process.rb @@ -136,15 +136,17 @@ def initialize(stdout_limit: 1 << 20, stderr_limit: 1 << 18, input_limit: 1 << 2 # +discard_stdout+ gives the child the null device for stdout, so the # result reports no stdout and the call does not wait for a descriptor # that a daemon older than tmux 3.2 keeps open after its client exits. - def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil, discard_stdout: false, stdout_tail: nil) + def run(argv, input: "".b, env: {}, timeout: 5.0, cancel: nil, discard_stdout: false, stdout_tail: nil, + replace_env: false, interruptible: true) Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout, - discard_stdout, stdout_tail).call + discard_stdout, stdout_tail, replace_env: replace_env, interruptible: interruptible).call end class Execution CHUNK_BYTES = 16_384 - def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout, discard_stdout, stdout_tail) + def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain_timeout, discard_stdout, stdout_tail, + replace_env:, interruptible:) @started = monotonic unless argv.is_a?(Array) && !argv.empty? && argv.all? { |argument| argument.is_a?(String) && !argument.include?("\0") } raise ArgumentError, "argv must contain strings without NUL" @@ -158,6 +160,7 @@ def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain @argv = argv.map { |argument| argument.dup.freeze }.freeze @input = input.b.freeze @env = env.merge("TMUX" => nil, "TMUX_PANE" => nil) + @replace_env, @interruptible = replace_env, interruptible @deadline = @started + timeout @cancel = cancel @limits = limits @@ -180,7 +183,7 @@ def call check_deadline(:admission) check_cancel(:admission) spawn - Thread.handle_interrupt(Exception => :immediate) { result = communicate } + Thread.handle_interrupt(Exception => (@interruptible ? :immediate : :never)) { result = communicate } rescue Exception => failure error = failure ensure @@ -227,7 +230,7 @@ def spawn @owned << @exit_reader begin @pid = Process.spawn(@env, [@argv.first, @argv.first], *@argv.drop(1), - in: child_input, out: child_output, err: child_error, close_others: true) + in: child_input, out: child_output, err: child_error, close_others: true, unsetenv_others: @replace_env) ensure @child.spawned(@pid) end diff --git a/gems/libtmux/lib/libtmux/server.rb b/gems/libtmux/lib/libtmux/server.rb index 4b84197..379e780 100644 --- a/gems/libtmux/lib/libtmux/server.rb +++ b/gems/libtmux/lib/libtmux/server.rb @@ -165,10 +165,7 @@ def self.open(**options) begin server&.close rescue Exception => cleanup - if failure.is_a?(Error) - failure.__send__(:attach_cleanup_errors, ["server close failed (#{cleanup.class})"]) - end - failure ||= cleanup + failure = failure ? CleanupError.new(body_error: failure, cleanup_error: cleanup) : cleanup end end end @@ -180,10 +177,10 @@ def self.open(**options) result end - def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "tmux", max_requests: 32, max_controls: 4, close_timeout: 0.5, - version_timeout: 5.0) - if endpoint && (socket_path || socket_name || executable != "tmux") - raise ArgumentError, "endpoint cannot be combined with socket or executable options" + def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "tmux", env: nil, + max_requests: 32, max_controls: 4, close_timeout: 0.5, version_timeout: 5.0) + if endpoint && (socket_path || socket_name || executable != "tmux" || env) + raise ArgumentError, "endpoint cannot be combined with socket, executable or env options" end raise ArgumentError, "endpoint must be an Endpoint" if endpoint && !endpoint.is_a?(Endpoint) unless max_requests.is_a?(Integer) && max_requests.positive? @@ -200,7 +197,7 @@ def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "t raise ArgumentError, "version_timeout must be positive and finite" end - @endpoint = endpoint || Endpoint.new(socket_path: socket_path, socket_name: socket_name, executable: executable) + @endpoint = endpoint || Endpoint.new(socket_path: socket_path, socket_name: socket_name, executable: executable, env: env) @owner_pid = Process.pid @max_requests = max_requests @max_controls = max_controls @@ -214,11 +211,12 @@ def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "t @pin = Internal::SocketIdentity.new(@endpoint) begin @release = Internal::TmuxVersion.connected(@pin.command_prefix) do |argv| - @executor.run(argv, **version_probe_options(version_timeout), discard_stdout: true) + @executor.run(argv, env: @endpoint.environment, replace_env: true, **version_probe_options(version_timeout), discard_stdout: true) end @pin.record_release(@release) argv, marker = Internal::TmuxVersion.fence_check_argv - Internal::TmuxVersion.verify_fence(@executor.run(@pin.command_prefix + argv, **version_probe_options(version_timeout)), marker) + result = @executor.run(@pin.command_prefix + argv, env: @endpoint.environment, replace_env: true, **version_probe_options(version_timeout)) + Internal::TmuxVersion.verify_fence(result, marker) rescue Exception @pin.close raise @@ -325,6 +323,13 @@ def new_session(name: nil, command: nil, width: nil, height: nil, window_name: n create_entity(:session, arguments + creation_command(command), receipt: receipt, **budget.options) end + def with_session(name:, command:, **options) + raise ArgumentError, "with_session requires a block" unless block_given? + raise ArgumentError, "with_session does not return a creation receipt" if options.key?(:receipt) + + owned_session(name: name, command: command, **options) { |session| yield session } + end + def list_sessions(timeout: 5.0, cancel: nil) list_entities(:session, [], global: true, timeout: timeout, cancel: cancel) end @@ -489,7 +494,7 @@ def with_bound_endpoint end end - def perform_request(cancel:) + def perform_request(cancel:, interruptible: true) ensure_owner if cancel && (!cancel.respond_to?(:reader) || !cancel.respond_to?(:cancelled?)) raise ArgumentError, "cancel must provide a cancellation reader and state" @@ -520,7 +525,7 @@ def perform_request(cancel:) end end view = CancellationView.new(owned, cancel) - Thread.handle_interrupt(Exception => :immediate) do + Thread.handle_interrupt(Exception => (interruptible ? :immediate : :never)) do result = yield view end rescue Exception => error @@ -589,17 +594,19 @@ def bound_daemon_identity(timeout:, cancel:) end # Library operations that repair exact tmux 3.7's break-pane say so here. - def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil) + def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil, + interruptible: !Thread.current[:libtmux_lifecycle_cleanup]) ensure_owner started = monotonic validate_argv(argv) raise ArgumentError, "raw commands cannot override endpoint flags" if argv.first.start_with?("-") raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? Internal::NativeGuard.check(argv, @release, repaired_break: repaired_break) - perform_request(cancel: cancel) do |view| + perform_request(cancel: cancel, interruptible: interruptible) do |view| fence, marker = Internal::TmuxVersion.fence(@release) result = @executor.run(@pin.command_prefix + fence + argv, input: input, - timeout: timeout - (monotonic - started), cancel: view, stdout_tail: stdout_tail) + env: @endpoint.environment, replace_env: true, timeout: timeout - (monotonic - started), cancel: view, + interruptible: interruptible, stdout_tail: stdout_tail) Internal::TmuxVersion.check_fence(result, marker, @release) end end diff --git a/gems/libtmux/lib/libtmux/terminal.rb b/gems/libtmux/lib/libtmux/terminal.rb index e068420..f075648 100644 --- a/gems/libtmux/lib/libtmux/terminal.rb +++ b/gems/libtmux/lib/libtmux/terminal.rb @@ -65,15 +65,16 @@ def attach(session:, terminal:, term:, read_only: false, timeout: nil, cancel: n argv = @pin.command_prefix + ["attach-session", "-E", *(read_only ? ["-r"] : []), "-t", session_id] perform_request(cancel: cancel) do |view| Internal.const_get(:TerminalExecution, false).new(argv, terminal, term, - timeout && timeout - (monotonic - started), view).call + timeout && timeout - (monotonic - started), view, @endpoint.environment).call end end end module Internal class TerminalExecution - def initialize(argv, terminal, term, timeout, cancel) + def initialize(argv, terminal, term, timeout, cancel, environment) @argv, @terminal, @term, @cancel = argv, terminal, term.dup.freeze, cancel + @environment = environment @started = clock @deadline = timeout && @started + timeout end @@ -90,8 +91,8 @@ def call @mode = @tty.console_mode @child = OwnedChild.new begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil, "TERM" => @term}, - *@argv, in: @tty, out: @tty, err: @tty, close_others: true) + @pid = Process.spawn(@environment.merge("TERM" => @term), + *@argv, in: @tty, out: @tty, err: @tty, close_others: true, unsetenv_others: true) rescue SystemCallError, IOError => error raise TransportError.new("terminal client could not start (#{error.class})", **details(:spawn)), cause: nil ensure diff --git a/gems/libtmux/libtmux.gemspec b/gems/libtmux/libtmux.gemspec index af46e34..619836e 100644 --- a/gems/libtmux/libtmux.gemspec +++ b/gems/libtmux/libtmux.gemspec @@ -43,6 +43,7 @@ Gem::Specification.new do |spec| lib/libtmux/control.rb lib/libtmux/group.rb lib/libtmux/owned.rb + lib/libtmux/lifecycle.rb lib/libtmux/socket_readiness.rb lib/libtmux/terminal.rb lib/libtmux/text_wait.rb diff --git a/gems/libtmux/sig/libtmux.rbs b/gems/libtmux/sig/libtmux.rbs index 6325867..2635d90 100644 --- a/gems/libtmux/sig/libtmux.rbs +++ b/gems/libtmux/sig/libtmux.rbs @@ -20,6 +20,12 @@ module LibTmux attr_reader text: String? def initialize: (String, ?delivery: Symbol, ?phase: Symbol?, ?pid: Integer?, ?cleanup_errors: Array[String], ?entity: Symbol?, ?path: String?, ?expected: String?) -> void end + class CleanupError < Error + attr_reader body_error: Exception + attr_reader cleanup_error: Exception + attr_reader recovery: untyped + def initialize: (body_error: Exception, cleanup_error: Exception, ?recovery: untyped) -> void + end class InvalidFilterError < Error def initialize: (?String, ?entity: Symbol?, ?path: String, ?expected: String?, **untyped) -> void end @@ -64,7 +70,8 @@ module LibTmux class Endpoint attr_reader executable: String attr_reader socket_path: String - def initialize: (?socket_path: String?, ?socket_name: String?, ?executable: String, ?socket_directory: String?, ?environment: untyped) -> void + attr_reader environment: Hash[String, String] + def initialize: (?socket_path: String?, ?socket_name: String?, ?executable: String, ?socket_directory: String?, ?environment: untyped, ?env: Hash[String, String?]?) -> void def self.from_env: (?untyped, **untyped) -> Endpoint def ==: (untyped) -> bool alias eql? == @@ -227,9 +234,9 @@ module LibTmux class Server attr_reader endpoint: Endpoint - def self.open: [T] (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) { (Server) -> T } -> T - | (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) -> Server - def initialize: (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) -> void + def self.open: [T] (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?env: Hash[String, String?]?, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) { (Server) -> T } -> T + | (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?env: Hash[String, String?]?, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) -> Server + def initialize: (?endpoint: Endpoint?, ?socket_path: String?, ?socket_name: String?, ?executable: String, ?env: Hash[String, String?]?, ?max_requests: Integer, ?max_controls: Integer, ?close_timeout: Numeric, ?version_timeout: Numeric) -> void def tmux_version: () -> String def supports_control?: () -> bool def capabilities: (?timeout: Numeric, ?cancel: untyped) -> Capabilities @@ -239,6 +246,7 @@ module LibTmux def kill: (?timeout: Numeric, ?cancel: untyped) -> CommandResult def new_session: (?name: String?, ?command: Array[String]?, receipt: true, ?width: Integer?, ?height: Integer?, ?window_name: String?, ?cwd: String?, ?environment: Hash[String, String], ?timeout: Numeric, ?cancel: untyped) -> CreationReceipt | (?name: String?, ?command: Array[String]?, ?receipt: false, ?width: Integer?, ?height: Integer?, ?window_name: String?, ?cwd: String?, ?environment: Hash[String, String], ?timeout: Numeric, ?cancel: untyped) -> Session + def with_session: [T] (name: String, command: Array[String], ?width: Integer?, ?height: Integer?, ?window_name: String?, ?cwd: String?, ?environment: Hash[String, String], ?timeout: Numeric, ?cancel: untyped) { (Session) -> T } -> T def list_sessions: (?timeout: Numeric, ?cancel: untyped) -> Array[Session] def list_windows: (?timeout: Numeric, ?cancel: untyped) -> Array[Window] def list_panes: (?timeout: Numeric, ?cancel: untyped) -> Array[Pane] diff --git a/gems/libtmux/sig/owned.rbs b/gems/libtmux/sig/owned.rbs index 8904b59..45a4bfa 100644 --- a/gems/libtmux/sig/owned.rbs +++ b/gems/libtmux/sig/owned.rbs @@ -1,7 +1,79 @@ module LibTmux class Server - def self.start: (?executable: String, ?config: String?, ?timeout: Numeric, ?cancel: untyped, **untyped) -> Server - | [T] (?executable: String, ?config: String?, ?timeout: Numeric, ?cancel: untyped, **untyped) { (Server) -> T } -> T + def self.start: (?endpoint: Endpoint?, ?env: Hash[String, String?]?, ?executable: String, ?config: String?, ?timeout: Numeric, ?cancel: untyped, **untyped) -> Server + | [T] (?endpoint: Endpoint?, ?env: Hash[String, String?]?, ?executable: String, ?config: String?, ?timeout: Numeric, ?cancel: untyped, **untyped) { (Server) -> T } -> T def owned?: () -> bool + def adopt: (?timeout: Numeric, ?cancel: untyped) -> OwnedResource[self] + | [T] (?timeout: Numeric, ?cancel: untyped) { (self) -> T } -> T + def owned_session: (name: String, command: Array[String], **untyped) -> OwnedResource[Session] + | [T] (name: String, command: Array[String], **untyped) { (Session) -> T } -> T + def find_or_create_session: (name: String, command: Array[String], ?timeout: Numeric, **untyped) -> Acquisition[Session] + def self.find_or_create: (?endpoint: Endpoint?, ?timeout: Numeric, ?config: String?, **untyped) -> Acquisition[Server] + def self.discover: (?roots: Array[String]?, ?env: untyped, ?executable: String, ?max_entries: Integer, ?max_probes: Integer, ?timeout: Numeric, ?probe_timeout: Numeric) -> DiscoveryResult + end + + class Entity + def adopt: (?timeout: Numeric, ?cancel: untyped) -> OwnedResource[self] + | [T] (?timeout: Numeric, ?cancel: untyped) { (self) -> T } -> T + end + + class Session + def owned_window: (name: String, command: Array[String], **untyped) -> OwnedResource[Window] + | [T] (name: String, command: Array[String], **untyped) { (Window) -> T } -> T + def find_or_create_window: (name: String, command: Array[String], ?timeout: Numeric, **untyped) -> Acquisition[Window] + end + + class Window + def owned_pane: (direction: Symbol, command: Array[String], **untyped) -> OwnedResource[Pane] + | [T] (direction: Symbol, command: Array[String], **untyped) { (Pane) -> T } -> T + def find_or_create_pane: (identity: String, direction: Symbol, command: Array[String], ?timeout: Numeric, **untyped) -> Acquisition[Pane] + end + + class Pane + def owned_pane: (direction: Symbol, command: Array[String], **untyped) -> OwnedResource[Pane] + | [T] (direction: Symbol, command: Array[String], **untyped) { (Pane) -> T } -> T + end + + class OwnershipReceipt + private def self.new: (*untyped, **untyped) -> instance + attr_reader kind: Symbol + attr_reader id: String? + attr_reader pid: Integer + attr_reader started_at: Integer + attr_reader generation: String + end + + class OwnedResource[A] + private def self.new: (*untyped, **untyped) -> instance + attr_reader resource: A + attr_reader receipt: OwnershipReceipt + attr_reader cleanup_error: Exception? + def closed?: () -> bool + def close: (?timeout: Numeric) -> nil + def use: [T] () { (A) -> T } -> T + end + + class Acquisition[A] + private def self.new: (*untyped, **untyped) -> instance + attr_reader resource: A + attr_reader owner: OwnedResource[A]? + def created?: () -> bool + def use: [T] () { (A) -> T } -> T + end + + class DiscoveredServer + private def self.new: (*untyped, **untyped) -> instance + attr_reader endpoint: Endpoint + attr_reader pid: Integer + attr_reader started_at: Integer + end + + class DiscoveryResult + private def self.new: (*untyped, **untyped) -> instance + attr_reader servers: Array[DiscoveredServer] + attr_reader diagnostics: Array[Hash[Symbol, String | Symbol]] + attr_reader entries: Integer + attr_reader probes: Integer + def truncated?: () -> bool end end diff --git a/test/integration/default_example_test.rb b/test/integration/default_example_test.rb new file mode 100644 index 0000000..0786840 --- /dev/null +++ b/test/integration/default_example_test.rb @@ -0,0 +1,134 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/default_example_harness" + +class DefaultExampleTest < Minitest::Test + EXAMPLE = File.expand_path("../../examples/default_session.rb", __dir__) + OPTIONS = ["-I", File.expand_path("../../gems/libtmux/lib", __dir__)].freeze + + def test_unchanged_ordinary_example_uses_harness_endpoint_and_cleans_its_session + host = ENV.to_h + evidence = run_example + assert evidence.fetch(:status).success?, evidence.fetch(:stderr) + assert_equal "session windows: 1\n", evidence.fetch(:stdout) + assert_equal ["fixture"], evidence.fetch(:sessions) + assert_equal host, ENV.to_h + assert_retired(evidence) + end + + def test_example_body_failure_still_removes_the_created_session + evidence = run_example(injection: <<~RUBY) + require "libtmux" + module FailExampleBody + def list_windows(**options) + super + raise "example body failed" + end + end + LibTmux::Session.prepend(FailExampleBody) + RUBY + refute evidence.fetch(:status).success? + assert_includes evidence.fetch(:stderr), "example body failed" + assert_equal ["fixture"], evidence.fetch(:sessions) + assert_retired(evidence) + end + + def test_example_cleanup_failure_is_visible_and_harness_retires_its_daemon + evidence = run_example(injection: <<~RUBY) + require "libtmux" + module FailExampleCleanup + def destroy_owned(*, **) + raise "example cleanup failed" + end + end + LibTmux::Server.prepend(FailExampleCleanup) + RUBY + refute evidence.fetch(:status).success? + assert_includes evidence.fetch(:stderr), "example cleanup failed" + assert_equal 1, evidence.fetch(:sessions).count { |name| name.start_with?("ruby-example-") } + assert_retired(evidence) + end + + def test_both_example_body_and_cleanup_failures_survive + evidence = run_example(injection: <<~RUBY) + require "libtmux" + module FailBothExampleOperations + def list_windows(**) + raise "body witness" + end + end + module FailBothExampleCleanup + def destroy_owned(*, **) + raise "cleanup witness" + end + end + LibTmux::Session.prepend(FailBothExampleOperations) + LibTmux::Server.prepend(FailBothExampleCleanup) + at_exit do + failure = $! + if failure.is_a?(LibTmux::CleanupError) + warn "retained: \#{failure.body_error.message}; \#{failure.cleanup_error.message}" + end + end + RUBY + refute evidence.fetch(:status).success? + assert_includes evidence.fetch(:stderr), "retained: body witness; cleanup witness" + assert_retired(evidence) + end + + def test_child_environment_overrides_preserve_absent_and_existing_host_values + host = ENV.to_h + [nil, "existing"].each do |value| + child = host.merge("LIBTMUX_RUBY_HARNESS" => value) + child["LIBTMUX_RUBY_HARNESS"] = "first" + child["LIBTMUX_RUBY_HARNESS"] = "second" + evidence = run_example(environment: child, injection: 'raise "child failed"') + refute evidence.fetch(:status).success? + assert_equal host, ENV.to_h + assert_retired(evidence) + end + end + + def test_timed_out_example_retires_its_worker_and_fixture + host = ENV.to_h + assert_raises(LibTmux::DeadlineExceeded) do + run_example(timeout: 0.1, injection: 'loop { sleep 10 }') + end + assert_equal host, ENV.to_h + end + + def test_crashed_example_worker_still_retires_the_fixture + evidence = run_example(injection: 'Process.kill("KILL", Process.pid)') + assert evidence.fetch(:status).signaled? + assert_equal Signal.list.fetch("KILL"), evidence.fetch(:status).termsig + assert_equal ["fixture"], evidence.fetch(:sessions) + assert_retired(evidence) + end + + def test_lifecycle_examples_run_unchanged_with_external_endpoint_defaults + {"lifecycle.rb" => "session reused: true\npane created: true\nadopted panes: 1\n", + "lifecycle_discovery.rb" => "servers: 1\n"}.each do |program, expected| + example = File.expand_path("../../examples/#{program}", __dir__) + evidence = LibTmuxTest::DefaultExampleHarness.run(example: example, ruby_options: OPTIONS) + assert evidence.fetch(:status).success?, evidence.fetch(:stderr) + assert_equal expected, evidence.fetch(:stdout) + assert_equal ["fixture"], evidence.fetch(:sessions) + assert_retired(evidence) + end + end + + private + + def run_example(**options) + LibTmuxTest::DefaultExampleHarness.run(example: EXAMPLE, ruby_options: OPTIONS, **options) + end + + def assert_retired(evidence) + assert evidence.fetch(:retired_before_removal) + assert_instance_of Process::Status, evidence.fetch(:daemon_status) + assert_raises(Errno::ECHILD) { Process.waitpid(evidence.fetch(:daemon_pid), Process::WNOHANG) } + assert_raises(Errno::ESRCH) { Process.kill(0, evidence.fetch(:daemon_pid)) } + refute File.exist?(evidence.fetch(:root)) + end +end diff --git a/test/integration/endpoint_defaults_test.rb b/test/integration/endpoint_defaults_test.rb new file mode 100644 index 0000000..711939b --- /dev/null +++ b/test/integration/endpoint_defaults_test.rb @@ -0,0 +1,244 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/stub_executable" +require_relative "../support/tmux_fixture" +require "libtmux" +require "libtmux/async" +require "pty" + +class EndpointDefaultsTest < Minitest::Test + def test_default_server_captures_endpoint_environment_and_executable_for_all_clients + original = ENV.to_h + LibTmuxTest::TmuxFixture.open do |fixture| + directory = File.dirname(fixture.socket_path) + log = File.join(directory, "clients.jsonl") + executable = File.join(directory, "tmux") + real_tmux = LibTmux::Endpoint.new(socket_path: fixture.socket_path, executable: fixture.executable).executable + LibTmuxTest::StubExecutable.write(executable, <<~'STUB', LOG: log, CLIENT: real_tmux) + flags = %w[LIBTMUX_RUBY_ADDED TMUX TMUX_PANE].map { |name| "x" if ENV.key?(name) } + File.open(LOG, "a") do |file| + file.puts [ENV["LIBTMUX_RUBY_KEEP"], *flags, ENV["PATH"], ARGV.join(" ")].join("\t") + end + exec CLIENT, *ARGV + STUB + ENV["PATH"] = directory + ENV["LIBTMUX_SOCKET_PATH"] = fixture.socket_path + ENV["LIBTMUX_SOCKET"] = "../ignored" + ENV["TMUX"] = "invalid-but-lower-precedence" + ENV["TMUX_PANE"] = "%99" + ENV["LIBTMUX_RUBY_KEEP"] = "captured" + ENV.delete("LIBTMUX_RUBY_ADDED") + LibTmux::Server.open do |server| + assert_equal fixture.socket_path, server.endpoint.socket_path + assert_equal executable, server.endpoint.executable + ENV["PATH"] = "/does-not-exist" + ENV["LIBTMUX_SOCKET_PATH"] = "/must-not-connect" + ENV["LIBTMUX_RUBY_KEEP"] = "changed" + ENV["LIBTMUX_RUBY_ADDED"] = "after-construction" + host = ENV.to_h + probe = server.run(["display-message", "-p", "captured"]) + assert probe.success?, probe.stderr + session = server.list_sessions.fetch(0) + server.open_control(session: session.ref) do |control| + assert_equal "core\n", control.exchange('display-message -p core').blocks.last.body + end + Async do |task| + LibTmux::Async.open(parent: task, server: server) do |scope| + assert_equal [session.id], scope.server.list_sessions.map(&:id) + scope.server.open_control(session: session.ref) do |control| + assert_equal "async\n", control.exchange('display-message -p async').blocks.last.body + end + end + end.wait + server.run(["set-hook", "-g", "client-attached", "wait-for -S defaults-terminal"]) + PTY.open do |_master, slave| + slave.winsize = [24, 80] + worker = Thread.new { server.attach(session: session.ref, terminal: slave, term: "xterm", timeout: 0.5) } + begin + assert server.run(["wait-for", "defaults-terminal"]).success? + assert server.run(["detach-client", "-s", session.id]).success? + assert worker.join(0.5), "terminal client did not retire" + assert worker.value.success? + ensure + worker.join(0.5) + end + end + LibTmux::Server.start(env: server.endpoint.environment) do |owned| + assert_equal "captured", owned.environment("LIBTMUX_RUBY_KEEP") + end + LibTmux::Server.open(env: server.endpoint.environment) do |borrowed| + Async do |task| + LibTmux::Async.open(parent: task, server: borrowed) do |scope| + assert_equal [session.id], scope.server.list_sessions.map(&:id) + end + end.wait + end + assert_equal host, ENV.to_h + end + clients = File.readlines(log).map do |line| + keep, added, tmux, pane, path, arguments = line.chomp.split("\t", -1) + {"keep" => keep, "added" => added == "x", "tmux" => tmux == "x", "pane" => pane == "x", "path" => path, + "control" => arguments.match?(/(?:\A| )-C attach-session(?: |\z)/), "daemon" => arguments.split.include?("-D")} + end + assert_operator clients.length, :>=, 6 + assert_equal 2, clients.count { |client| client.fetch("control") } + assert_equal 1, clients.count { |client| client.fetch("daemon") } + clients.each do |client| + assert_equal "captured", client.fetch("keep") + assert_equal directory, client.fetch("path") + refute client.fetch("added") + refute client.fetch("tmux") + refute client.fetch("pane") + end + end + ensure + ENV.replace(original) + end + + def test_session_scope_cleans_the_captured_id_after_rename_and_name_reuse + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + owned_id = nil + value = server.with_session(name: "scope", command: ["/bin/cat"]) do |session| + owned_id = session.id + assert server.run(["rename-session", "-t", session.id, "renamed"]).success? + server.new_session(name: "scope", command: ["/bin/cat"]) + :result + end + assert_equal :result, value + refute_includes server.list_sessions.map(&:id), owned_id + assert_equal ["fixture", "scope"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + end + end + end + + def test_selection_environment_still_opens_the_running_server_with_core_and_async + LibTmuxTest::TmuxFixture.open do |fixture| + endpoint = LibTmux::Endpoint.new(environment: {"LIBTMUX_SOCKET_PATH" => fixture.socket_path, "PATH" => "/no-executables"}) + LibTmux::Server.open(endpoint: endpoint) do |server| + assert_equal ["fixture"], server.list_sessions.map { |session| session.snapshot.name } + Async do |task| + LibTmux::Async.open(parent: task, server: server) do |scope| + assert_equal ["fixture"], scope.server.list_sessions.map { |session| session.snapshot.name } + end + end.wait + end + end + end + + def test_explicit_owned_named_endpoint_starts_in_a_fresh_root_and_retires_daemon + Dir.mktmpdir("libtmux-ruby-named-") do |root| + endpoint = LibTmux::Endpoint.new(env: {"LIBTMUX_SOCKET" => "selected", "TMUX_TMPDIR" => root}) + pid = private_path = nil + LibTmux::Server.start(endpoint: endpoint) do |server| + assert_equal endpoint, server.endpoint + assert File.socket?(endpoint.socket_path) + assert_equal 0o700, File.stat(File.dirname(endpoint.socket_path)).mode & 0o777 + pid = Integer(server.run(["display-message", "-p", '#{pid}']).text) + private_path = server.run(["display-message", "-p", '#{socket_path}']).text.strip + assert private_path.start_with?(File.dirname(endpoint.socket_path) + "/") + retained = File.join(File.dirname(private_path), "identity") + assert_equal File.lstat(endpoint.socket_path).ino, File.lstat(retained).ino + LibTmux::Server.open(env: {"LIBTMUX_SOCKET" => "selected", "TMUX_TMPDIR" => root}) do |borrowed| + assert_equal "#{pid}\n", borrowed.run(["display-message", "-p", '#{pid}']).text + end + end + assert_raises(Errno::ESRCH) { Process.kill(0, pid) } + assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } + refute File.exist?(endpoint.socket_path) + refute File.exist?(File.dirname(private_path)) + end + end + + def test_named_directory_permissions_collisions_and_filesystem_components + Dir.mktmpdir("libtmux-ruby-root-") do |root| + directory = File.join(root, "tmux-#{Process.uid}") + endpoint = LibTmux::Endpoint.new(socket_name: "selected", socket_directory: root) + Dir.mkdir(directory, 0o750) + LibTmux::Server.start(endpoint: endpoint) do |server| + pid = server.run(["display-message", "-p", '#{pid}']).text + assert_raises(Errno::EEXIST) { LibTmux::Server.start(endpoint: endpoint) } + assert_equal pid, server.run(["display-message", "-p", '#{pid}']).text + assert_equal 1, Dir.children(directory).count { |name| name.start_with?(".libtmux-") } + end + File.chmod(0o705, directory) + assert_raises(ArgumentError) { LibTmux::Server.start(endpoint: endpoint) } + File.chmod(0o700, directory) + Dir.rmdir(directory) + Dir.mkdir(File.join(root, "real"), 0o700) + File.symlink(File.join(root, "real"), directory) + assert_raises(ArgumentError) { LibTmux::Server.start(endpoint: endpoint) } + File.unlink(directory) + File.write(directory, "not a directory") + assert_raises(ArgumentError) { LibTmux::Server.start(endpoint: endpoint) } + File.unlink(directory) + missing = LibTmux::Endpoint.new(socket_name: "selected", socket_directory: File.join(root, "missing", "..")) + assert_raises(Errno::ENOENT) { LibTmux::Server.start(endpoint: missing) } + refute File.exist?(directory) + if Process.uid.zero? + Dir.mkdir(directory, 0o700) + File.chown(1, -1, directory) + assert_raises(ArgumentError) { LibTmux::Server.start(endpoint: endpoint) } + File.chown(Process.uid, -1, directory) + end + end + end + + def test_published_endpoint_collision_cannot_remove_an_existing_file_or_replacement_daemon + Dir.mktmpdir("libtmux-ruby-publish-") do |root| + endpoint = LibTmux::Endpoint.new(socket_path: File.join(root, "socket")) + File.write(endpoint.socket_path, "keep existing file") + assert_raises(Errno::EEXIST) { LibTmux::Server.start(endpoint: endpoint) } + assert_equal "keep existing file", File.read(endpoint.socket_path) + assert_equal ["socket"], Dir.children(root) + File.unlink(endpoint.socket_path) + first = LibTmux::Server.start(endpoint: endpoint) + first_pid = Integer(first.run(["display-message", "-p", '#{pid}']).text) + File.unlink(endpoint.socket_path) + second = LibTmux::Server.start(endpoint: endpoint) + second_pid = Integer(second.run(["display-message", "-p", '#{pid}']).text) + first.close + assert_raises(Errno::ESRCH) { Process.kill(0, first_pid) } + assert File.socket?(endpoint.socket_path) + assert_equal "#{second_pid}\n", second.run(["display-message", "-p", '#{pid}']).text + ensure + first&.close + second&.close + end + end + + def test_removed_root_and_explicit_missing_parent_do_not_start_elsewhere + Dir.mktmpdir("libtmux-ruby-removed-") do |root| + selected = File.join(root, "selected") + Dir.mkdir(selected) + endpoint = LibTmux::Endpoint.new(socket_name: "unique", socket_directory: selected) + Dir.rmdir(selected) + original = Process.method(:spawn) + Process.define_singleton_method(:spawn) { |*_, **| flunk "missing root attempted a process launch" } + begin + assert_raises(Errno::ENOENT) { LibTmux::Server.start(endpoint: endpoint) } + ensure + Process.define_singleton_method(:spawn, original) + end + refute Dir.exist?(selected) + endpoint = LibTmux::Endpoint.new(socket_path: File.join(selected, "socket")) + assert_raises(Errno::ENOENT) { LibTmux::Server.start(endpoint: endpoint) } + refute Dir.exist?(selected) + end + end + + def test_symlink_parent_traversal_keeps_the_filesystem_selected_root + Dir.mktmpdir("libtmux-ruby-parent-") do |root| + Dir.mkdir(File.join(root, "actual")) + Dir.mkdir(File.join(root, "actual", "child")) + File.symlink(File.join(root, "actual", "child"), File.join(root, "link")) + endpoint = LibTmux::Endpoint.new(socket_name: "selected", socket_directory: File.join(root, "link", "..")) + LibTmux::Server.start(endpoint: endpoint) do |server| + assert File.socket?(File.join(root, "actual", "tmux-#{Process.uid}", "selected")) + refute File.exist?(File.join(root, "tmux-#{Process.uid}")) + assert server.run(["display-message", "-p", "selected"]).success? + end + end + end +end diff --git a/test/integration/lifecycle_async_test.rb b/test/integration/lifecycle_async_test.rb new file mode 100644 index 0000000..718eb3a --- /dev/null +++ b/test/integration/lifecycle_async_test.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/tmux_fixture" +require "libtmux/async" + +class LifecycleAsyncTest < Minitest::Test + def test_async_body_cancellation_leaves_no_owned_session + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |source| + Async do |parent| + LibTmux::Async.open(parent: parent, server: source) do |scope| + ready = ::Async::Notification.new + child = parent.async do + scope.server.owned_session(name: "async-cancel", command: ["cat"]) do + ready.signal + ::Async::Notification.new.wait + end + end + ready.wait + child.cancel + child.wait + assert_equal ["$0"], source.list_sessions.map(&:id) + end + end.wait + end + end + end + + def test_async_receipt_handoff_cancellation_rolls_back + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |source| + Async do |parent| + LibTmux::Async.open(parent: parent, server: source) do |scope| + original = scope.server.method(:owner_from_output) + scope.server.define_singleton_method(:owner_from_output) do |*arguments| + original.call(*arguments).tap { ::Async::Task.current.cancel } + end + child = parent.async { scope.server.owned_session(name: "async-handoff", command: ["cat"]) } + child.wait + assert_equal ["$0"], source.list_sessions.map(&:id) + end + end.wait + end + end + end + + def test_async_scope_retains_body_and_cleanup_error_objects + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |source| + Async do |parent| + LibTmux::Async.open(parent: parent, server: source) do |scope| + owner = scope.server.owned_session(name: "async-errors", command: ["cat"]) + original = source.method(:destroy_owned) + body = RuntimeError.new("body") + cleanup = IOError.new("cleanup") + source.define_singleton_method(:destroy_owned) { |*, **| raise cleanup } + failure = assert_raises(LibTmux::CleanupError) { owner.use { raise body } } + assert_same body, failure.body_error + assert_same cleanup, failure.cleanup_error + source.define_singleton_method(:destroy_owned, original) + failure.recovery.close + assert_equal ["$0"], source.list_sessions.map(&:id) + end + end.wait + end + end + end +end diff --git a/test/integration/lifecycle_cancellation_test.rb b/test/integration/lifecycle_cancellation_test.rb new file mode 100644 index 0000000..4e7d477 --- /dev/null +++ b/test/integration/lifecycle_cancellation_test.rb @@ -0,0 +1,237 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/tmux_fixture" +require "libtmux" + +class LifecycleCancellationTest < Minitest::Test + %i[server session window pane].each do |kind| + define_method("test_adoption_cancelled_after_receipt_for_#{kind}") do + with_resource(kind) do |server, resource, fixture| + with_cancel do |cancel| + cancel_after_receipt(server, cancel) + failure = assert_raises(LibTmux::Cancelled) { resource.adopt(cancel: cancel) } + assert_equal :handoff, failure.phase + assert_equal :observed, failure.delivery + assert_removed(server, resource, kind, fixture) + end + end + end + + define_method("test_adoption_block_skipped_after_cancelled_receipt_for_#{kind}") do + with_resource(kind) do |server, resource, fixture| + with_cancel do |cancel| + cancel_after_receipt(server, cancel) + entered = false + assert_raises(LibTmux::Cancelled) { resource.adopt(cancel: cancel) { entered = true } } + refute entered + assert_removed(server, resource, kind, fixture) + end + end + end + + define_method("test_pre_cancelled_adoption_preserves_borrowed_#{kind}") do + with_resource(kind) do |server, resource, _fixture| + with_cancel do |cancel| + before = inventory(server) + commands = [] + original = server.method(:run) + server.define_singleton_method(:run) { |*args, **options| commands << args; original.call(*args, **options) } + cancel.cancel + assert_raises(LibTmux::Cancelled) { resource.adopt(cancel: cancel) } + assert_empty commands + assert_equal before, inventory(server) + end + end + end + end + + %i[session window pane].each do |kind| + define_method("test_pre_cancelled_reuse_preserves_borrowed_#{kind}") do + with_reused_resource(kind) do |server, find| + with_cancel do |cancel| + before = inventory(server) + cancel.cancel + assert_raises(LibTmux::Cancelled) { find.call(cancel) } + assert_equal before, inventory(server) + end + end + end + + define_method("test_reuse_cancellation_after_list_command_for_#{kind}") do + with_reused_resource(kind) do |server, find| + with_cancel do |cancel| + before = inventory(server) + original = server.method(:run) + server.define_singleton_method(:run) do |arguments, **options| + original.call(arguments, **options).tap { cancel.cancel if arguments.first.start_with?("list-") } + end + assert_raises(LibTmux::Cancelled) { find.call(cancel) } + assert_equal before, inventory(server) + end + end + end + + define_method("test_reuse_cancellation_at_value_handoff_for_#{kind}") do + with_reused_resource(kind) do |server, find| + with_cancel do |cancel| + before = inventory(server) + original = server.method(:lifecycle_value) + expected = {session: "cancel-target", window: "cancel-window", pane: "cancel-pane"}.fetch(kind).b + server.define_singleton_method(:lifecycle_value) do |*args, **options| + original.call(*args, **options).tap { |value| cancel.cancel if value == expected } + end + assert_raises(LibTmux::Cancelled) { find.call(cancel) } + assert_equal before, inventory(server) + end + end + end + end + + def test_adoption_cancellation_and_failed_rollback_retain_recovery_owner + with_resource(:window) do |server, resource, _fixture| + with_cancel do |cancel| + cancel_after_receipt(server, cancel) + cleanup = IOError.new("adoption rollback failed").freeze + original_destroy = server.method(:destroy_owned) + server.define_singleton_method(:destroy_owned) { |*, **| raise cleanup } + original_rollback = server.method(:rollback_owner) + accepted_failure = nil + server.define_singleton_method(:rollback_owner) do |owner, failure| + accepted_failure = failure + original_rollback.call(owner, failure) + end + failure = assert_raises(LibTmux::CleanupError) { resource.adopt(cancel: cancel) } + assert_instance_of LibTmux::Cancelled, failure.body_error + assert_same accepted_failure, failure.body_error + assert_same cleanup, failure.cleanup_error + assert_same resource, failure.recovery.resource + refute failure.recovery.closed? + assert_includes server.list_windows.map(&:id), resource.id + server.define_singleton_method(:destroy_owned, original_destroy) + failure.recovery.close + assert failure.recovery.closed? + refute_includes server.list_windows.map(&:id), resource.id + end + end + end + + def test_cancelled_waiter_leaves_gate_without_waiting_for_holder + with_reused_resource(:session) do |server, find| + with_cancel do |cancel| + before = inventory(server) + gate = LibTmux::Internal.const_get(:LifecycleGate, false) + held, release, waiting = Queue.new, Queue.new, Queue.new + condition = gate.instance_variable_get(:@condition) + original_wait = condition.method(:wait) + condition.define_singleton_method(:wait) do |*args| + waiting << true + original_wait.call(*args) + end + holder = Thread.new { gate.synchronize(timeout: 5.0) { held << true; release.pop } } + held.pop + waiter = Thread.new do + assert_raises(LibTmux::Cancelled) { find.call(cancel) } + end + waiting.pop + cancel.cancel + assert waiter.join(1.0), "cancelled waiter remained behind the gate holder" + assert_equal before, inventory(server) + ensure + release << true if holder + holder&.join + waiter&.join + condition&.define_singleton_method(:wait, original_wait) + end + end + end + + def test_pane_identity_handoff_cancellation_rolls_back_created_pane + with_resource(:window) do |server, window, _fixture| + with_cancel do |cancel| + before = window.list_panes.map(&:id) + original = server.method(:lifecycle_value) + server.define_singleton_method(:lifecycle_value) do |entity, *args, **options| + original.call(entity, *args, **options).tap { cancel.cancel unless before.include?(entity.id) } + end + assert_raises(LibTmux::Cancelled) do + window.find_or_create_pane(identity: "new-identity", direction: :horizontal, command: ["cat"], cancel: cancel) + end + assert_equal before, window.list_panes.map(&:id) + end + end + end + + def test_find_or_create_keeps_positive_timeout_validation + with_reused_resource(:session) do |server, _find| + before = inventory(server) + [0, -1, Float::INFINITY, Float::NAN].each do |timeout| + assert_raises(ArgumentError) do + server.find_or_create_session(name: "cancel-target", command: ["cat"], timeout: timeout) + end + end + assert_equal before, inventory(server) + end + end + + private + + def with_cancel + cancel = LibTmux::Cancellation.new + yield cancel + ensure + cancel&.close + end + + def with_resource(kind) + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + resource = if kind == :server + server + else + session = server.new_session(name: "cancel-target", window_name: "cancel-window", command: ["cat"]) + window = session.list_windows.first + {session: session, window: window, pane: window.list_panes.first}.fetch(kind) + end + yield server, resource, fixture + end + end + end + + def with_reused_resource(kind) + with_resource(kind) do |server, resource, _fixture| + find = case kind + when :session + ->(cancel) { server.find_or_create_session(name: "cancel-target", command: ["cat"], cancel: cancel) } + when :window + session = server.list_sessions.find { |entry| entry.id != "$0" } + ->(cancel) { session.find_or_create_window(name: "cancel-window", command: ["cat"], cancel: cancel) } + when :pane + resource.options.set("@libtmux_pane_identity", "cancel-pane") + window = server.list_windows.find { |entry| entry.id != "@0" } + ->(cancel) { window.find_or_create_pane(identity: "cancel-pane", direction: :horizontal, command: ["cat"], cancel: cancel) } + end + yield server, find + end + end + + def cancel_after_receipt(server, cancel) + original = server.method(:lifecycle_execute) + server.define_singleton_method(:lifecycle_execute) do |*args| + original.call(*args).tap { cancel.cancel } + end + end + + def inventory(server) + [server.list_sessions, server.list_windows, server.list_panes].map { |resources| resources.map(&:id) } + end + + def assert_removed(server, resource, kind, fixture) + if kind == :server + assert fixture.instance_variable_get(:@server).last.wait_observed(0.5) + else + refute_includes server.public_send("list_#{kind}s").map(&:id), resource.id + assert_includes server.list_sessions.map(&:id), "$0" + end + end +end diff --git a/test/integration/lifecycle_test.rb b/test/integration/lifecycle_test.rb new file mode 100644 index 0000000..2ad2af3 --- /dev/null +++ b/test/integration/lifecycle_test.rb @@ -0,0 +1,445 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/tmux_fixture" +require "libtmux" +require "pathname" +require "socket" + +class LifecycleTest < Minitest::Test + def test_owned_session_block_returns_body_value_and_removes_only_its_session + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + fixture_ids = server.list_sessions.map(&:id) + result = server.owned_session(name: "scope", command: ["cat"]) do |session| + assert_includes server.list_sessions.map(&:id), session.id + :body_value + end + assert_equal :body_value, result + assert_equal fixture_ids, server.list_sessions.map(&:id) + end + end + end + + def test_owned_resource_is_explicit_and_cleanup_is_repeatable + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + session = server.new_session(name: "adopt", command: ["cat"]) + owner = session.adopt + assert_same session, owner.resource + assert_match(/\A[0-9a-f]{32}\z/, owner.receipt.generation) + refute owner.closed? + owner.close + assert owner.closed? + assert_nil owner.close + refute_includes server.list_sessions.map(&:id), session.id + end + end + end + + def test_all_entity_kinds_follow_ids_after_rename_and_move + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + session = server.owned_session(name: "rename", command: ["cat"]) + window = session.resource.owned_window(name: "moving", command: ["cat"]) + pane = window.resource.owned_pane(direction: :horizontal, command: ["cat"]) + fixture.tmux("rename-session", "-t", session.resource.id, "renamed") + fixture.tmux("move-window", "-s", window.resource.id, "-t", "$0:9") + fixture.tmux("move-pane", "-s", pane.resource.id, "-t", "%0") + pane.close + refute_includes server.list_panes.map(&:id), pane.resource.id + window.close + refute_includes server.list_windows.map(&:id), window.resource.id + session.close + assert_equal ["$0"], server.list_sessions.map(&:id) + end + end + end + + def test_window_adoption_destroys_all_links_and_panes + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + session = server.new_session(name: "linked", command: ["cat"]) + window = session.list_windows.first + pane = window.list_panes.first + fixture.tmux("link-window", "-s", window.id, "-t", "$0:9") + window.adopt { |borrowed| assert_same window, borrowed } + refute_includes server.list_windows.map(&:id), window.id + refute_includes server.list_panes.map(&:id), pane.id + assert_empty server.list_window_links.select { |link| link.id == window.id } + end + end + end + + def test_body_failure_cleanup_failure_and_retry_preserve_original_exceptions + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + owner = server.owned_session(name: "failure", command: ["cat"]) + body = RuntimeError.new("body") + cleanup = IOError.new("cleanup") + original = server.method(:destroy_owned) + server.define_singleton_method(:destroy_owned) { |*, **| raise cleanup } + error = assert_raises(LibTmux::CleanupError) { owner.use { raise body } } + assert_same body, error.body_error + assert_same cleanup, error.cleanup_error + assert_same owner, error.recovery + assert_same cleanup, owner.cleanup_error + refute owner.closed? + assert_includes server.list_sessions.map(&:id), owner.resource.id + server.define_singleton_method(:destroy_owned, original) + owner.close + assert owner.closed? + assert_nil owner.cleanup_error + end + end + end + + def test_block_break_and_throw_clean_up + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + assert_equal :break_value, server.owned_session(name: "break", command: ["cat"]) { break :break_value } + assert_equal :throw_value, catch(:done) { server.owned_session(name: "throw", command: ["cat"]) { throw :done, :throw_value } } + assert_equal ["$0"], server.list_sessions.map(&:id) + end + end + end + + def test_invalid_generation_fails_without_creating_or_overwriting + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + ["", "bad", "a" * 33].each do |token| + server.options(scope: :server).set("@libtmux_owner_generation", token) + assert_raises(LibTmux::ProtocolError) { server.owned_session(name: "invalid", command: ["cat"]) } + assert_equal ["$0"], server.list_sessions.map(&:id) + assert_equal token, server.options(scope: :server).get("@libtmux_owner_generation").as(:string) + end + token = "abcdef0123456789" * 2 + server.options(scope: :server).set("@libtmux_owner_generation", token) + owner = server.owned_session(name: "valid", command: ["cat"]) + assert_equal token, owner.receipt.generation + owner.close + end + end + end + + def test_generation_guard_refuses_same_numeric_identity_with_different_token_for_every_kind + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + session = server.owned_session(name: "guard", command: ["cat"]) + window = session.resource.owned_window(name: "guard", command: ["cat"]) + pane = window.resource.owned_pane(direction: :horizontal, command: ["cat"]) + daemon = server.adopt + token = session.receipt.generation + server.options(scope: :server).set("@libtmux_owner_generation", "b" * 32 == token ? "c" * 32 : "b" * 32) + [pane, window, session, daemon].each do |owner| + assert_raises(LibTmux::TargetNotFoundError) { owner.close } + refute owner.closed? + end + assert_includes server.list_panes.map(&:id), pane.resource.id + server.options(scope: :server).set("@libtmux_owner_generation", token) + [pane, window, session].each(&:close) + end + end + end + + def test_complete_receipt_with_duplicate_record_rolls_back + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + original = server.method(:lifecycle_execute) + server.define_singleton_method(:lifecycle_execute) do |program, names, budget| + result = original.call(program, names, budget) + next result unless program.include?("'new-session'") + LibTmux::CommandResult.new(stdout: result.stdout * 2, stderr: result.stderr, status: result.status, + elapsed_seconds: result.elapsed_seconds, pid: result.pid, argv: result.argv) + end + assert_raises(LibTmux::ProtocolError) { server.owned_session(name: "duplicate", command: ["cat"]) } + assert_equal ["$0"], server.list_sessions.map(&:id) + end + end + end + + def test_find_or_create_reports_created_reused_and_ambiguity + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + first = server.find_or_create_session(name: "find", command: ["cat"]) + second = server.find_or_create_session(name: "find", command: ["cat"]) + assert first.created? + refute second.created? + assert_nil second.owner + assert_equal first.resource, second.resource + window = first.resource.find_or_create_window(name: "find", command: ["cat"]) + refute first.resource.find_or_create_window(name: "find", command: ["cat"]).created? + pane = window.resource.find_or_create_pane(identity: "worker-λ", direction: :horizontal, command: ["cat"]) + refute window.resource.find_or_create_pane(identity: "worker-λ", direction: :horizontal, command: ["cat"]).created? + window.resource.list_panes.find { |candidate| candidate.id != pane.resource.id }.options.set("@libtmux_pane_identity", "worker-λ") + assert_raises(LibTmux::MultipleMatchesError) { window.resource.find_or_create_pane(identity: "worker-λ", direction: :horizontal, command: ["cat"]) } + first.resource.new_window(name: "find", command: ["cat"]) + assert_raises(LibTmux::MultipleMatchesError) { first.resource.find_or_create_window(name: "find", command: ["cat"]) } + first.owner.close + end + end + end + + def test_threads_share_find_or_create_serialization_across_bindings + LibTmuxTest::TmuxFixture.open do |fixture| + workers = 4.times.map do + Thread.new do + server = LibTmux::Server.new(socket_path: fixture.socket_path) + [server, server.find_or_create_session(name: "concurrent", command: ["cat"])] + end + end + workers.each(&:join) + results = workers.map(&:value) + assert_equal 1, results.count { |_, result| result.created? } + assert_equal 1, results.map { |_, result| result.resource.id }.uniq.length + ensure + results&.each { |server, result| result.owner&.close; server.close } + end + end + + def test_discovery_is_bounded_and_reports_stale_symlink_and_missing_roots + LibTmuxTest::TmuxFixture.open do |first| + LibTmuxTest::TmuxFixture.open do |second| + root = File.dirname(first.socket_path) + socket = UNIXServer.new(File.join(root, "stale")) + socket.close + File.symlink(first.socket_path, File.join(root, "symlink")) + File.link(first.socket_path, File.join(root, "same-daemon")) + result = LibTmux::Server.discover(roots: [root, File.dirname(second.socket_path), File.join(root, "missing")], timeout: 2) + assert_equal [first.daemon_pid, second.daemon_pid].sort, result.servers.map(&:pid).sort + %i[symlink duplicate_socket probe_failed root_failed].each { |reason| assert_includes result.diagnostics.map { |entry| entry[:reason] }, reason } + refute result.truncated? + bounded = LibTmux::Server.discover(roots: [root], max_entries: 1) + assert bounded.truncated? + assert_empty bounded.servers + assert_equal :entry_bound, bounded.diagnostics.last[:reason] + assert File.socket?(File.join(root, "stale")) + end + end + end + + def test_discovery_resolves_implicit_relative_and_home_roots + LibTmuxTest::TmuxFixture.open do |fixture| + Dir.mktmpdir("libtmux-ruby-discovery-") do |root| + endpoint = LibTmux::Endpoint.new(socket_name: "default", socket_directory: root, executable: fixture.executable) + LibTmux::Server.start(endpoint: endpoint) do |server| + server.new_session(name: "discovery", command: ["/bin/cat"]) + pid = Integer(server.display('#{pid}').text) + named_root = File.dirname(endpoint.socket_path) + named_entries = 1 + Dir.children(named_root).length + relative = Pathname.new(root).relative_path_from(Pathname.pwd).to_s + home_relative = Pathname.new(root).relative_path_from(Pathname.new(Dir.home)).to_s + + result = LibTmux::Server.discover(env: {"TMUX_TMPDIR" => relative}, executable: fixture.executable, + max_entries: named_entries, probe_timeout: 0.5) + assert_equal [pid], result.servers.map(&:pid) + + explicit_entries = 1 + Dir.children(File.dirname(fixture.socket_path)).length + environment = {"TMUX_TMPDIR" => "~/#{home_relative}", "LIBTMUX_SOCKET_PATH" => fixture.socket_path} + result = LibTmux::Server.discover(env: environment, executable: fixture.executable, + max_entries: explicit_entries + named_entries, probe_timeout: 0.5) + assert_equal [fixture.daemon_pid, pid], result.servers.map(&:pid) + assert_raises(ArgumentError) { LibTmux::Server.discover(roots: [relative], executable: fixture.executable) } + end + end + end + end + + def test_server_find_or_create_keeps_reused_server_borrowed_and_cleans_new_server + Dir.mktmpdir("libtmux-ruby-find-server-") do |root| + endpoint = LibTmux::Endpoint.new(socket_path: File.join(root, "socket")) + first = LibTmux::Server.find_or_create(endpoint: endpoint) + second = LibTmux::Server.find_or_create(endpoint: endpoint) + assert first.created? + refute second.created? + second.resource.close + assert first.resource.display("alive").success? + pid = first.owner.receipt.pid + first.owner.close + assert first.owner.closed? + assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } + refute File.exist?(endpoint.socket_path) + ensure + first&.resource&.close + second&.resource&.close + end + end + + def test_replacement_daemon_survives_stale_route_and_simulated_numeric_collision + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |old| + old_owner = old.adopt + previous_socket = File.stat(fixture.socket_path) + old.kill + assert fixture.instance_variable_get(:@server).last.wait_observed(0.5) + if File.exist?(fixture.socket_path) + assert_equal [previous_socket.dev, previous_socket.ino], File.stat(fixture.socket_path).then { |stat| [stat.dev, stat.ino] } + File.unlink(fixture.socket_path) + end + endpoint = LibTmux::Endpoint.new(socket_path: fixture.socket_path) + LibTmux::Server.start(endpoint: endpoint) do |replacement| + session = replacement.owned_session(name: "replacement", command: ["cat"]) + window = session.resource.owned_window(name: "replacement", command: ["cat"]) + pane = window.resource.owned_pane(direction: :horizontal, command: ["cat"]) + assert_raises(LibTmux::CommandError) { old_owner.close } + [replacement.adopt, session, window, pane].each do |fresh| + prior = fresh.receipt + collision = LibTmux::OwnershipReceipt.__send__(:new, kind: prior.kind, id: prior.id, + pid: prior.pid, started_at: prior.started_at, generation: old_owner.receipt.generation) + stale = LibTmux::OwnedResource.__send__(:new, fresh.resource, collision) + assert_raises(LibTmux::TargetNotFoundError) { stale.close } + end + assert_includes replacement.list_panes.map(&:id), pane.resource.id + end + end + end + end + + def test_cancellation_at_receipt_handoff_rolls_back_and_preserves_exception + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + failure = Interrupt.new("handoff cancelled") + original = server.method(:owner_from_output) + server.define_singleton_method(:owner_from_output) do |*arguments| + owner = original.call(*arguments) + Thread.current.raise(failure) + owner + end + assert_same failure, assert_raises(Interrupt) { server.owned_session(name: "cancelled", command: ["cat"]) } + assert_equal ["$0"], server.list_sessions.map(&:id) + end + end + end + + def test_cancellation_token_after_creation_is_rolled_back + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + cancel = LibTmux::Cancellation.new + original = server.method(:owner_from_output) + server.define_singleton_method(:owner_from_output) do |*arguments| + owner = original.call(*arguments) + cancel.cancel + owner + end + assert_raises(LibTmux::Cancelled) { server.owned_session(name: "cancelled", command: ["cat"], cancel: cancel) } + assert_equal ["$0"], server.list_sessions.map(&:id) + ensure + cancel&.close + end + end + end + + def test_receipt_and_later_pane_identity_failures_expose_retryable_owner + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + window = server.list_windows.first + before = window.list_panes.map(&:id) + original = server.method(:lifecycle_value) + body = RuntimeError.new("identity verification failed") + server.define_singleton_method(:lifecycle_value) do |entity, field, **options| + raise body unless before.include?(entity.id) + original.call(entity, field, **options) + end + assert_same body, assert_raises(RuntimeError) { window.find_or_create_pane(identity: "worker", direction: :horizontal, command: ["cat"]) } + assert_equal before, window.list_panes.map(&:id) + cleanup = IOError.new("rollback failed") + destroy = server.method(:destroy_owned) + server.define_singleton_method(:destroy_owned) { |*, **| raise cleanup } + failure = assert_raises(LibTmux::CleanupError) { window.find_or_create_pane(identity: "worker", direction: :horizontal, command: ["cat"]) } + assert_same body, failure.body_error + assert_same cleanup, failure.cleanup_error + refute failure.recovery.closed? + server.define_singleton_method(:destroy_owned, destroy) + failure.recovery.close + assert_equal before, window.list_panes.map(&:id) + end + end + end + + def test_uncertain_creation_receipt_does_not_guess_an_owned_object + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + original = server.method(:lifecycle_execute) + server.define_singleton_method(:lifecycle_execute) do |*arguments| + result = original.call(*arguments) + LibTmux::CommandResult.new(stdout: "lost receipt\n", stderr: result.stderr, status: result.status, + elapsed_seconds: result.elapsed_seconds, pid: result.pid, argv: result.argv) + end + failure = assert_raises(LibTmux::OutcomeUnknown) { server.owned_session(name: "unknown", command: ["cat"]) } + assert_equal :possibly_sent, failure.delivery + assert_equal 2, server.list_sessions.length + end + end + end + + def test_literal_names_and_identity_survive_format_metacharacters_and_transport_escaping + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + name = "literal-λ-\#{pid}-comma,quote'back\\slash" + assert_raises(ArgumentError) { server.find_or_create_session(name: name, command: ["cat"]) } + session_name = name.delete("\\") + session = server.find_or_create_session(name: session_name, command: ["cat"]) + refute server.find_or_create_session(name: session_name, command: ["cat"]).created? + assert_raises(ArgumentError) { session.resource.find_or_create_window(name: name, command: ["cat"]) } + window = session.resource.find_or_create_window(name: session_name, command: ["cat"]) + refute session.resource.find_or_create_window(name: session_name, command: ["cat"]).created? + identity = "identity-λ\tline\n\#{pid}\\" + pane = window.resource.find_or_create_pane(identity: identity, direction: :horizontal, command: ["cat"]) + refute window.resource.find_or_create_pane(identity: identity, direction: :horizontal, command: ["cat"]).created? + assert pane.created? + session.owner.close + end + end + end + + def test_concurrent_windows_and_panes_reuse_one_creation + LibTmuxTest::TmuxFixture.open do |fixture| + LibTmux::Server.open(socket_path: fixture.socket_path) do |server| + session = server.list_sessions.first + windows = 3.times.map { Thread.new { session.find_or_create_window(name: "parallel", command: ["cat"]) } }.map(&:value) + assert_equal 1, windows.count(&:created?) + window = windows.first.resource + panes = 3.times.map { Thread.new { window.find_or_create_pane(identity: "parallel", direction: :horizontal, command: ["cat"]) } }.map(&:value) + assert_equal 1, panes.count(&:created?) + windows.find(&:created?).owner.close + end + end + end + + def test_concurrent_servers_publish_one_owned_daemon + Dir.mktmpdir("libtmux-ruby-concurrent-server-") do |root| + endpoint = LibTmux::Endpoint.new(socket_path: File.join(root, "socket")) + workers = 3.times.map { Thread.new { LibTmux::Server.find_or_create(endpoint: endpoint) } } + workers.each(&:join) + results = workers.map(&:value) + assert_equal 1, results.count(&:created?) + assert_equal 1, results.map { |entry| entry.resource.display("\#{pid}").stdout }.uniq.length + ensure + results&.each { |entry| entry.resource.close unless entry.created? } + results&.find(&:created?)&.owner&.close + end + end + + def test_server_owner_retries_local_cleanup_after_confirmed_daemon_destruction + Dir.mktmpdir("libtmux-ruby-owner-retry-") do |root| + endpoint = LibTmux::Endpoint.new(socket_path: File.join(root, "socket")) + result = LibTmux::Server.find_or_create(endpoint: endpoint) + server = result.resource + original = server.method(:close) + cleanup = IOError.new("local cleanup") + attempts = 0 + server.define_singleton_method(:close) do + attempts += 1 + raise cleanup if attempts == 1 + original.call + end + assert_same cleanup, assert_raises(IOError) { result.owner.close } + refute result.owner.closed? + result.owner.close + assert result.owner.closed? + assert_equal 2, attempts + ensure + result&.resource&.close + end + end +end diff --git a/test/support/default_example_harness.rb b/test/support/default_example_harness.rb new file mode 100644 index 0000000..7d62c48 --- /dev/null +++ b/test/support/default_example_harness.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +require "open3" +require "libtmux" +require_relative "tmux_fixture" + +module LibTmuxTest + # Executes an unchanged consumer file against one foreground-owned daemon. + class DefaultExampleHarness + def self.run(example:, environment: ENV.to_h, ruby_options: [], injection: nil, timeout: 5.0) + original = ENV.to_h + executable = LibTmux::Endpoint.new(socket_path: "/unused", env: environment, + executable: environment.fetch("LIBTMUX_TEST_TMUX", "tmux")).executable + fixture = TmuxFixture.new(executable: executable) + result = failure = nil + begin + fixture.start + root = File.dirname(fixture.socket_path) + bin = File.join(root, "bin") + Dir.mkdir(bin, 0o700) + File.symlink(executable, File.join(bin, "tmux")) + options = ruby_options.dup + if injection + probe = File.join(root, "example-probe.rb") + File.write(probe, injection) + options.concat(["-r", probe]) + end + child = environment.merge("PATH" => [bin, environment.fetch("PATH", "/usr/bin:/bin")].join(File::PATH_SEPARATOR), + "LIBTMUX_SOCKET_PATH" => fixture.socket_path, + "LIBTMUX_SOCKET" => "../ignored", "TMUX" => "/ignored,1,0", "TMUX_PANE" => "%99") + worker = LibTmux::Internal::ProcessExecutor.new.run([Gem.ruby, *options, example], + env: child, replace_env: true, timeout: timeout) + stdout, stderr, status = worker.stdout, worker.stderr, worker.status + names, error, observed = fixture.tmux("list-sessions", "-F", '#{session_name}') + raise "example observation failed: #{error}" unless observed.success? + + result = {stdout: stdout, stderr: stderr, status: status, sessions: names.lines.map(&:chomp), + daemon_pid: fixture.daemon_pid, root: root, child_environment: child} + rescue Exception => error + failure = error + ensure + begin + fixture.close + rescue Exception => cleanup + failure = failure ? LibTmux::CleanupError.new(body_error: failure, cleanup_error: cleanup) : cleanup + end + end + raise failure if failure + raise "example harness changed its host environment" unless original == ENV.to_h + + result.merge(daemon_status: fixture.daemon_status, retired_before_removal: fixture.retired_before_removal) + end + end +end diff --git a/test/support/installed_gems.rb b/test/support/installed_gems.rb index 01c373d..511c0b9 100644 --- a/test/support/installed_gems.rb +++ b/test/support/installed_gems.rb @@ -87,8 +87,20 @@ def run_installed_examples(package, environment, directory, root, *ruby_options) warn "Omitted installed example #{entry.fetch('id')} on tmux #{release.text}. It requires tmux #{minimum} or newer." next end - output, status = Open3.capture2e(environment.merge("LIBTMUX_EXAMPLE_INSTALLED" => "1"), - Gem.ruby, *ruby_options, "-W:no-experimental", File.join(directory, entry.fetch("path")), chdir: directory) + example = File.join(directory, entry.fetch("path")) + example_environment = environment.merge("LIBTMUX_EXAMPLE_INSTALLED" => "1") + example_options = [*ruby_options, "-W:no-experimental"] + if entry["endpoint"] == "borrowed" + require_relative "default_example_harness" + evidence = DefaultExampleHarness.run(example: example, + environment: ENV.to_h.merge(example_environment), ruby_options: example_options) + output, status = evidence.values_at(:stdout, :status) + output += evidence.fetch(:stderr) + assert_equal ["fixture"], evidence.fetch(:sessions) + assert evidence.fetch(:retired_before_removal) + else + output, status = Open3.capture2e(example_environment, Gem.ruby, *example_options, example, chdir: directory) + end unless unavailable.empty? # The program must reach the library's typed refusal. assert_equal 1, status.exitstatus, "expected feature refusal in #{entry.fetch('id')}: #{output}" diff --git a/test/support/tmux_fixture.rb b/test/support/tmux_fixture.rb index d825a38..05edd56 100644 --- a/test/support/tmux_fixture.rb +++ b/test/support/tmux_fixture.rb @@ -55,7 +55,7 @@ def value DEADLINE_SECONDS = 0.5 private_constant :CLEAN_ENV, :DEADLINE_SECONDS - attr_reader :socket_path, :cleanup_errors, :executable + attr_reader :socket_path, :cleanup_errors, :executable, :daemon_pid, :daemon_status, :retired_before_removal def self.open fixture = error = result = nil @@ -104,6 +104,7 @@ def start # -D keeps the daemon as our child; its exit can be observed and reaped. @server = spawn_owned(@executable, "-D", *readiness.arguments, "-S", @socket_path, "-f", config_path, **readiness.spawn_options) + @daemon_pid = @server.last.pid @server.first.close end _, error, status = capture("new-session", "-d", "-s", "fixture", "-x", "80", "-y", "24", "cat") @@ -155,8 +156,12 @@ def close end end attempt_cleanup(errors, "server retirement") { retire(@server) } if @server - attempt_cleanup(errors, "temporary directory removal") do - FileUtils.remove_entry(@directory) if File.exist?(@directory) + if !@server || @server.last.complete? + @daemon_status = @server.last.status if @server + @retired_before_removal = !@server || @daemon_status.is_a?(Process::Status) + attempt_cleanup(errors, "temporary directory removal") do + FileUtils.remove_entry(@directory) if File.exist?(@directory) + end end @cleanup_errors = errors.freeze @cleanup_complete = errors.empty? diff --git a/test/types/consumer.rb b/test/types/consumer.rb index 9c22cdd..daa9e7e 100644 --- a/test/types/consumer.rb +++ b/test/types/consumer.rb @@ -94,6 +94,35 @@ def verify_rejects_wrong_return(value = Object.new) unless capabilities.feature("owned-terminal-program").supported? == supports_programs raise "owned program discovery disagrees with admission" end + endpoint = consumer.call("singleton(::LibTmux::Endpoint)", LibTmux::Endpoint, :new, + environment: {"LIBTMUX_SOCKET_PATH" => server.endpoint.socket_path, "PATH" => "/no-executables"}, + expected: "::LibTmux::Endpoint") + consumer.call("::LibTmux::Endpoint", endpoint, :environment, expected: "Hash[String, String]") + consumer.verify_rejects_wrong_return(42) + captured = consumer.call("singleton(::LibTmux::Endpoint)", LibTmux::Endpoint, :new, + env: {"LIBTMUX_SOCKET_PATH" => server.endpoint.socket_path}, executable: server.endpoint.executable, + expected: "::LibTmux::Endpoint") + consumer.call("singleton(::LibTmux::Server)", LibTmux::Server, :open, + env: captured.environment, executable: captured.executable, + expected: "String") { |borrowed| borrowed.tmux_version } + consumer.call("::LibTmux::Server", server, :with_session, name: "types-scope", command: ["/bin/cat"], + expected: "String") { |owned_session| owned_session.id } + owner = consumer.call("::LibTmux::Server", server, :owned_session, name: "owned-types", command: ["/bin/cat"], + expected: "::LibTmux::OwnedResource[::LibTmux::Session]") + owned_session = consumer.call("::LibTmux::OwnedResource[::LibTmux::Session]", owner, :resource, expected: "::LibTmux::Session") + consumer.call("::LibTmux::OwnedResource[::LibTmux::Session]", owner, :receipt, expected: "::LibTmux::OwnershipReceipt") + consumer.verify_rejects_wrong_return(42) + acquisition = consumer.call("::LibTmux::Session", owned_session, :find_or_create_window, name: "types-worker", command: ["/bin/cat"], + expected: "::LibTmux::Acquisition[::LibTmux::Window]") + consumer.call("::LibTmux::Acquisition[::LibTmux::Window]", acquisition, :created?, expected: "bool") + window = owned_session.new_window(name: "types-adopt", command: ["/bin/cat"]) + consumer.call("::LibTmux::Window", window, :adopt, expected: "Integer") do |adopted| + consumer.call("::LibTmux::Window", adopted, :list_panes, expected: "Array[::LibTmux::Pane]").length + end + consumer.call("::LibTmux::OwnedResource[::LibTmux::Session]", owner, :close, expected: "nil") + discovery = consumer.call("singleton(::LibTmux::Server)", LibTmux::Server, :discover, + roots: [File.dirname(server.endpoint.socket_path)], expected: "::LibTmux::DiscoveryResult") + consumer.call("::LibTmux::DiscoveryResult", discovery, :servers, expected: "Array[::LibTmux::DiscoveredServer]") consumer.call("::LibTmux::Server", server, :diagnostics, expected: "{admitted_requests: Integer, reserved_process_slots: Integer, control_connections: Integer, closed: bool, limits: Hash[Symbol, Numeric]}") receipt = consumer.call("::LibTmux::Server", server, :new_session, name: "types", command: ["/bin/cat"], receipt: true, diff --git a/test/unit/endpoint_test.rb b/test/unit/endpoint_test.rb index 6bfadc3..905f234 100644 --- a/test/unit/endpoint_test.rb +++ b/test/unit/endpoint_test.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative "../test_helper" +require_relative "../support/stub_executable" require_relative "../../gems/libtmux/lib/libtmux/endpoint" class EndpointTest < Minitest::Test @@ -43,6 +44,13 @@ def test_the_path_variable_names_the_socket assert_equal File.expand_path("relative.sock"), endpoint("LIBTMUX_SOCKET_PATH" => "relative.sock").socket_path end + def test_selection_environment_does_not_override_the_client_executable_or_environment + selected = endpoint("LIBTMUX_SOCKET_PATH" => "/chosen/path.sock", "PATH" => "/no-executables") + assert_equal "/chosen/path.sock", selected.socket_path + assert_equal endpoint.executable, selected.executable + assert_equal ENV["PATH"], selected.environment["PATH"] + end + def test_the_name_variable_names_a_socket_in_the_tmux_directory assert_equal "#{PRIVATE_DIRECTORY}/named", endpoint("LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path @@ -144,6 +152,62 @@ def test_the_process_environment_is_the_default end end + def test_complete_child_environment_and_executable_are_captured_without_host_mutation + host = ENV.to_h + Dir.mktmpdir("libtmux-ruby-endpoint-") do |directory| + executable = File.join(directory, "tmux") + LibTmuxTest::StubExecutable.write(executable, "exit 0\n") + env = {"PATH" => directory, "KEEP" => +"before", "DROP" => nil, + "TMUX" => "/selected/socket,1,-1", "TMUX_PANE" => "%7"} + endpoint = LibTmux::Endpoint.new(env: env) + env.fetch("KEEP").replace("after") + env["PATH"] = "/missing" + assert_equal executable, endpoint.executable + assert_equal({"PATH" => directory, "KEEP" => "before"}, endpoint.environment) + assert endpoint.environment.frozen? + assert endpoint.environment.values.all?(&:frozen?) + assert_equal host, ENV.to_h + end + end + + def test_explicit_selector_ignores_invalid_lower_precedence_values + env = {"LIBTMUX_SOCKET_PATH" => "relative", "LIBTMUX_SOCKET" => "../bad", "TMUX" => "bad", "TMUX_TMPDIR" => "relative"} + assert_equal "/chosen/socket", LibTmux::Endpoint.new(socket_path: "/chosen/socket", env: env).socket_path + assert_equal "/chosen/tmux-#{Process.uid}/name", LibTmux::Endpoint.new(socket_name: "name", socket_directory: "/chosen", env: env).socket_path + end + + def test_named_root_is_captured_and_invalid_child_environment_is_rejected + env = {"TMUX_TMPDIR" => +"/selected/root", "LIBTMUX_SOCKET" => "chosen"} + endpoint = LibTmux::Endpoint.new(env: env) + env["TMUX_TMPDIR"].replace("/changed/root") + assert_equal "/selected/root/tmux-#{Process.uid}/chosen", endpoint.socket_path + [{"BAD=KEY" => "x"}, {"" => "x"}, {"KEY" => 1}, {"KEY" => "nul\0"}].each do |invalid| + assert_raises(ArgumentError) { LibTmux::Endpoint.new(socket_path: "/unused", env: invalid) } + end + end + + def test_named_directory_rejects_a_different_uid_before_binding + Dir.mktmpdir("libtmux-ruby-owner-") do |root| + directory = File.join(root, "tmux-#{Process.uid}") + Dir.mkdir(directory, 0o700) + endpoint = LibTmux::Endpoint.new(socket_name: "selected", socket_directory: root) + original = File.method(:lstat) + foreign = original.call(directory) + foreign.define_singleton_method(:uid) { Process.uid + 1 } + File.define_singleton_method(:lstat) { |path| path == directory ? foreign : original.call(path) } + begin + assert_raises(ArgumentError) { endpoint.__send__(:validate_directory) } + ensure + File.define_singleton_method(:lstat, original) + end + end + end + + def test_explicit_paths_retain_filesystem_parent_components + raw = "/owned/missing/../selected.sock" + assert_equal raw, LibTmux::Endpoint.new(socket_path: raw).socket_path + end + private # Every case names its own environment, so none reaches the tmux server of whoever runs the suite. diff --git a/test/unit/session_scope_test.rb b/test/unit/session_scope_test.rb new file mode 100644 index 0000000..b79ef8c --- /dev/null +++ b/test/unit/session_scope_test.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require "libtmux" + +class SessionScopeTest < Minitest::Test + def test_server_block_retains_body_and_close_exceptions + body = RuntimeError.new("body witness") + cleanup = IOError.new("close witness") + type = Class.new(LibTmux::Server) do + define_method(:initialize) { |**| nil } + define_method(:close) { raise cleanup } + end + failure = assert_raises(LibTmux::CleanupError) { type.open { raise body } } + assert_equal :possibly_sent, failure.delivery + assert_same body, failure.body_error + assert_same cleanup, failure.cleanup_error + refute_includes failure.cleanup_errors.join, "close witness" + end + + def test_session_scope_requires_a_block_before_creating_a_session + server = LibTmux::Server.allocate + assert_raises(ArgumentError) { server.with_session(name: "unused", command: ["/bin/cat"]) } + end +end