diff --git a/CHANGES.md b/CHANGES.md index db784cc9..99c8fa54 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,22 @@ ## Unreleased +- Server ownership: accept and clean up created daemons through their private endpoints. Retain the published socket alias after daemon exit or startup rollback so cleanup cannot unlink a concurrent replacement. Reusing a stale path requires caller-coordinated alias retirement or a different path. +- Discovery: use the same first `TMUX_TMPDIR` value as connection defaults, including an empty value that selects `/tmp`. + +- Add task-scoped ownership and explicit adoption for servers, sessions, windows and panes, generation-guarded cleanup, retryable owners and complete-receipt rollback. +- Add foreground server startup, bounded discovery and created/reused results for server, session, window and keyed-pane lookup. + +- Connections: select an existing daemon through captured path/name defaults, + tmux context or the default named socket. Explicit selectors still take + precedence. Resolve omitted executables through captured `PATH`; accept + copied `client_env` overrides and remove nested tmux context from clients. +- Runtime: add `defer` for asynchronous task cleanup after success, body errors + and cancellation, with body and teardown failures retained in the result. +- Examples: add an ordinary default-connection example and an external private + harness that verifies its session cleanup. Use owned server scopes for + fresh-daemon creation and cleanup. + - Docs: add complete common API examples with private tmux setup and cleanup. ## 0.1.0alpha2-1 diff --git a/README.md b/README.md index e9385724..bca1f55e 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,28 @@ tmux or an event loop. CI runs unit tests on Lua 5.1–5.5 and LuaJIT, plus live tests across tmux 3.2a–3.7c. See the [compatibility matrix](docs/compatibility.md) for exact versions and remaining platform coverage. +## Ordinary defaults + +With tmux already running, the [ordinary example](examples/ordinary.lua) +connects without socket arguments, creates a session, reads it, and removes +that session when the runtime body finishes or fails: + +```console +$ lua examples/ordinary.lua +``` + +`runtime:connect()` selects `LIBTMUX_SOCKET_PATH`, `LIBTMUX_SOCKET_NAME`, the +current `TMUX` context, or tmux's default named socket, in that order. Explicit +API selectors take precedence. The library captures the endpoint and client +environment at the call. See [connection defaults](docs/snapshots.md) for +validation, named roots and per-client overrides. Connect requires an existing +daemon. [Owned scopes, server startup and discovery](docs/lifecycle.md) add +explicit lifecycle operations without changing borrowed connections. + +The [external test harness](tests/integration/test_lifecycle.py) runs the exact +example file at owned private endpoints and checks cleanup after injected +failure. Private socket setup belongs to that harness. + ## Read a server Connect to an existing server by its explicit socket path. This is the full @@ -218,6 +240,7 @@ server running. See [runtime ownership and cancellation](docs/runtime.md). ## Guides - **Clients:** [switch sessions and detach terminals](docs/clients.md). +- **Ownership:** [owned scopes, discovery and find-or-create](docs/lifecycle.md). - **Read and watch:** [snapshots](docs/snapshots.md), [session notifications and pane streams](docs/control.md). - **Run and arrange:** [commands and batches](docs/commands.md), diff --git a/docs/commands.md b/docs/commands.md index b59eb192..1bdf2cb9 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -54,3 +54,11 @@ reported with byte counts and truncation metadata; it is not silently kept. The raw API is an escape hatch. Named domain operations, owned command completion and observation APIs are still under development. A successful `send-keys` process does not report the exit of a pane application. + +## Client environment + +Commands inherit the connection's captured client environment. A command's +`env` option supplies a complete replacement sequence of `NAME=value` strings +for that client. The library copies the sequence and removes `TMUX` and +`TMUX_PANE`; the pinned socket still selects the accepted daemon. These +values do not edit the host process or tmux's persistent environment store. diff --git a/docs/creation.md b/docs/creation.md index 7f145fdd..a54b9d9b 100644 --- a/docs/creation.md +++ b/docs/creation.md @@ -10,6 +10,9 @@ made from tmux's returned IDs. Its `created` sequence names the objects this operation created: all four for a session, window/pane/link for a window, and only the pane for a split. Other handles describe the containing context. Creating a pane proves neither application readiness nor command success. +Use [deferred cleanup](runtime.md#deferred-cleanup) for a session that should +end with its task. The [ordinary example](../examples/ordinary.lua) includes +imports, default connection and cleanup. ## Commands and literal values @@ -60,3 +63,7 @@ state. Closing the Server connection leaves created sessions running. The [public creation fixture](../tests/integration/domain.lua) exercises the same API through luv and Neovim with literal arguments, environment and directory values, returned IDs, explicit shell text and missing directories. + +## Owned creation + +Use [owned lifecycle operations](lifecycle.md) to destroy created sessions, windows or panes at task exit, or to accept destruction responsibility for an existing handle. The borrowed creation methods above keep their existing lifetime semantics. diff --git a/docs/environment.md b/docs/environment.md index 082d3327..7359925d 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -1,5 +1,9 @@ # Persistent environment +Connection `client_env` and command `env` configure the launched tmux client; +see [connection defaults](snapshots.md). Those copied values leave the host +environment unchanged. There is no `LIBTMUX_SOCKET_ENV` variable. + Server methods address tmux's global environment store. Session methods address that session's local store. Each method returns a Request; reads never evaluate shell text. Window and Pane handles reject these operations with `invalid_scope`. diff --git a/docs/lifecycle.md b/docs/lifecycle.md new file mode 100644 index 00000000..4662dce8 --- /dev/null +++ b/docs/lifecycle.md @@ -0,0 +1,196 @@ +# Ownership, discovery and example testing + +Use an owned scope when Lua should destroy the tmux objects it creates. A borrowed connection leaves the daemon running. Ownership lasts until the current managed task exits, or until you call the owner's `close()` or `release()` method. The scopes use the existing coroutine runtime and support Lua 5.1; they do not depend on garbage collection or Lua 5.4 closing variables. + +## Automatic examples and test fixtures + +Run this complete [example](../examples/owned_session.lua) with an existing default tmux server. It creates `owned-example`, prints its name, and removes that session after the body returns. A duplicate session name fails creation without adopting the existing session. + +```lua +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err then + error(err, 0) + end + return value +end + +local result, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + return server + :with_session({ name = "owned-example", argv = { "/bin/cat" } }, function(session) + local snapshot = must(session:snapshot():await()) + print("session: " .. snapshot.name) + return true + end) + :await() +end) +assert(result, tostring(err)) +``` + +The external test runner supplies `LIBTMUX_SOCKET_PATH` or `LIBTMUX_SOCKET_NAME` before launching Lua. The file stays unchanged. `runtime:connect()` requires a running daemon. Use `runtime:owned_server(options)` to start a daemon on an unused endpoint, or `runtime:find_or_create_server(options)` to connect or start. + +## Taking ownership of existing objects + +Call `adopt()` on a server, session, window or pane handle. The returned `Owned` value has the accepted object in `value`, a copied identity from `receipt()`, and asynchronous `close()`. This complete program creates a borrowed session first, then adopts that existing session: + +```lua +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err then error(err, 0) end + return value +end + +local result, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + local existing = must(server:new_session({ + name = "adoption-example", + argv = { "/bin/cat" }, + }):await()) + local owner = must(existing.session:adopt():await()) + must(owner.value:rename("adoption-renamed"):await()) + return owner:close():await() +end) +assert(result, tostring(err)) +``` + +`window:adopt()` destroys that window across its links. `pane:adopt()` destroys that pane after a move. Session owners destroy the accepted session after a rename. Server owners destroy the whole daemon; use an explicit disposable endpoint for server-ownership demonstrations. + +Acceptance initializes the reserved server option `@libtmux_owner_generation` with 32 random hexadecimal characters if it is absent. It preserves a valid existing token and rejects an empty or malformed token. Keep this option unchanged and do not shadow it on sessions, windows or panes. Destruction checks the accepted token, PID and start time inside tmux. The connection also pins the socket inode and retains a private route to it. Numeric IDs, rather than mutable names or indexes, identify owned objects. + +A daemon started through `owned_server` has an additional native child-process handle. Startup accepts ownership and returns a server handle through that child's private endpoint. If another daemon replaces the published socket before handoff or close, commands on this handle and owner cleanup still address the child that startup created. A separate `runtime:connect` to the public path sees its current daemon. An adopted daemon has no startup child handle and refuses a replaced or uncertain endpoint. Closing the borrowed server connection does not discard a live owner's pin. + +## Finding running tmux servers + +Discovery returns metadata and per-path diagnostics. It does not start servers or adopt them. + +```lua +local adapter = require("libtmux.runtime.luv") + +local result, err = adapter.run(function(runtime) + local found, failure = runtime:discover_servers():await() + if not found then return nil, failure end + for _, server in ipairs(found.servers) do + print(server.socket_path, server.pid, server.version) + end + print("truncated", found.truncated) + return true +end) +assert(result, tostring(err)) +``` + +The default roots are the current user's `tmux-UID` directories below captured `TMUX_TMPDIR` and `/tmp`. Pass `roots` to replace those directories and `paths` to add exact endpoints. Each list accepts up to 32 absolute paths. The defaults limit enumeration to 256 entries, probes to 32, and elapsed time between probes to 2,000 ms. One in-flight probe can add up to 750 ms. Discovery reads directory batches of 16 entries, rejects symlink roots and foreign-user sockets, reports failed probes, and deduplicates socket inodes. It does not promise a system-wide inventory or scan process tables. + +## Find or create + +Each result has `value` and `created`. A newly created result also has an `owner`; a reused result has none. This program creates or reuses a named session and window, then finds a pane by its application key: + +```lua +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err then error(err, 0) end + return value +end + +local result, err = adapter.run(function(runtime) + local found = must(runtime:find_or_create_server():await()) + local server = found.value + local session = must(server:find_or_create_session("lookup-example"):await()) + local window = must(session.value:find_or_create_window("editor"):await()) + local pane = must(window.value:find_or_create_pane("editor-process"):await()) + print(found.created, session.created, window.created, pane.created) + return true +end) +assert(result, tostring(err)) +``` + +Session and window lookup use exact names; both reject backslashes because tmux rewrites them. Session names also exclude dots and colons. Pane lookup uses an exact value in the pane option `@libtmux_pane_key`; it searches the containing window when called on a pane. A missing key creates a split and stores that key on the new pane. More than one match returns `ambiguous`. + +Find-or-create requests serialize within one Lua runtime for one captured socket path. Other processes and alternate path spellings can race. tmux enforces session-name uniqueness; window names and pane keys do not carry a cross-process uniqueness guarantee. Server startup publishes its private foreground socket with an atomic hard link and returns a concurrent winner as borrowed when the selected path already exists. `owned_server` refuses an occupied endpoint. + +After closing a newly created server, the owner retains its published socket alias. A later `find_or_create_server` at that stale path returns a connection error; it does not remove the alias or start a replacement. `owned_server` returns `already_exists`. A caller that controls the directory namespace can retire the stale alias after proving the old daemon has exited and coordinating with other publishers, or select an unused path. Repeated calls work without alias retirement while the existing daemon remains live: they return it with `created = false` and no owner. + +## Cleanup at scope exit + +`server:with_session(options, body)`, `session:with_window(options, body)`, and `pane:with_pane(options, body)` invoke the body with the owned object and its owner. `runtime:with_server(options, body)` supplies a new server. `owner:scope(body)` limits an existing owner's lifetime to that body. + +```lua +local adapter = require("libtmux.runtime.luv") + +local result, err = adapter.run(function(runtime) + local server, failure = runtime:connect():await() + if not server then return nil, failure end + local owner + owner, failure = server:owned_session({ + name = "cleanup-example", + argv = { "/bin/cat" }, + }):await() + if not owner then return nil, failure end + return owner:scope(function(session) + return session:rename("cleanup-renamed"):await() + end):await() +end) +assert(result, tostring(err)) +``` + +Use `owned_session`, `owned_window`, `owned_pane` or `owned_server` for an owner that lasts to the current managed task's exit. `owner:close():await()` permits early cleanup and repeat calls. A failed attempt retains `cleanup_error` and permits retry. `owner:release()` relinquishes destruction responsibility and returns the borrowed object. Releasing a newly started server also transfers responsibility for its private startup directory and socket links to the caller; the library retains them so the daemon stays usable. + +Server cleanup waits for the accepted child to exit, then removes its private startup socket and directory. It leaves the published alias in place during normal close and startup rollback. An inode check followed by a pathname unlink cannot exclude a concurrent replacement between those operations. Keeping the alias protects that replacement, at the cost of leaving a stale socket path for the directory owner to manage. Releasing an owner retains both private and public routes for the caller. + +Body failure and cancellation still run task cleanup. If both the body and cleanup fail, `cleanup_failed.cause` retains the body error and `cleanup_failed.errors` retains cleanup errors. The runtime retains deferred-cleanup diagnostics even after code handles a nested failure and retries; inspect the final adapter result as well as the local request. + +Owned creation accepts one complete identity receipt before returning an owner. A later creation failure rolls back through that receipt; a rollback failure exposes its recovery owner. Cancellation cannot turn incomplete output into an object identity. An unknown receipt reports `creation_unknown`; the outer test harness owns final fixture cleanup. Caller cancellation does not prove that tmux rejected a command. + +## Environment defaults and overrides + +The library captures defaults at the public call. Explicit `socket_path` or `socket_name` wins, followed by nonempty `LIBTMUX_SOCKET_PATH`, nonempty `LIBTMUX_SOCKET_NAME`, a valid `TMUX` context, then tmux's named `default` socket. Supplying both explicit selectors fails. An invalid selected value fails without trying weaker selectors. + +Named endpoints use the captured absolute `TMUX_TMPDIR` or `/tmp`. Startup creates only a missing `tmux-UID` directory, with mode 0700, below an existing root. It rejects foreign ownership, symlinks at the UID directory, and other-user permission bits; group permissions remain valid. Explicit paths create no parent directories. Filesystem lookup preserves `missing/..` and `symlink/..` semantics. + +`client_env` copies child-only overrides; a `false` value removes a key. The additive connection option `ConnectOptions.env` supplies a complete child-environment sequence: `env = {}` means an empty environment, and supplied entries retain order, duplicates, empty entries and bare entries. It does not inherit host values. The existing per-command `CommandOptions.env` retains those sequence semantics. Choose either connection `env` or `client_env`; supplying a complete environment and an override map together fails validation because their meanings conflict. The library captures either form at the public call and removes `TMUX` and `TMUX_PANE` from launched clients. It leaves Lua's host environment unchanged and defines no `LIBTMUX_SOCKET_ENV` variable. tmux's server/session environment methods remain a separate API. + +Endpoint selection and discovery use the first value for each name in a complete environment sequence. For `TMUX_TMPDIR`, an empty first value selects `/tmp` even when a later duplicate supplies a nonempty directory. The child receives the original order and duplicate values, apart from the tmux-context filtering above. + +```lua +local adapter = require("libtmux.runtime.luv") + +local result, err = adapter.run(function(runtime) + local server, failure = runtime:connect({ + client_env = { EXAMPLE_MODE = "documentation", OLD_SETTING = false }, + }):await() + if not server then return nil, failure end + return server:command({ "display-message", "-p", "connected" }):await() +end) +assert(result, tostring(err)) +``` + +## Sandbox and example testing + +The lifecycle evidence runner starts a foreground fixture under an owned `/dev/shm/libtmux-lua-*` directory, passes a child environment, and executes the example file from the checkout. It accepts daemon process identities through pidfds and observes exits before removing the outer fixture root. Injected body, transport and cleanup failures exercise the library's error paths. The same imported example file is also run with an external output hook that throws a body error, stalls until the outer timeout, or kills the Lua worker. The source bytes stay unchanged. The body error runs Lua cleanup; timeout and worker death require the outer harness to stop its accepted processes before deleting its root. + +Run the collected checks with `python3 tests/run_integration.py --pattern test_ownership.py`. They use the installed `LIBTMUX_TEST_LUA` and `TMUX_BIN` executables; `LIBTMUX_TEST_NVIM` adds the Neovim host check. For a persistent receipt from one unchanged example: + +```sh +python3 tests/support/ownership_fixture.py ordinary examples/owned_session.lua \ + --evidence .cache/lifecycle-results --lua lua --tmux tmux +``` + +The shared documentation-testing scope includes Markdown, Astro Markdown/MDX, Sphinx reStructuredText/MyST and Python doctest. This Lua change supplies native Lua programs and an external environment boundary. Reusable format adapters, rendered-source binding across those formats, and hosted CI/release evidence remain separate gates. A killed Lua worker needs outer harness cleanup; in-process scopes cannot run after that worker exits. + +For an explicit whole-server cleanup demonstration, choose an unused path below a directory you own before running this program. Socket configuration belongs in this example because it demonstrates daemon ownership. The scope stops its daemon and retires its private startup directory; the published alias remains. Retire that alias under your directory's namespace coordination before rerunning with the same path: + +```lua +local adapter = require("libtmux.runtime.luv") + +local result, err = adapter.run(function(runtime) + return runtime:with_server({ + socket_path = assert(os.getenv("EXAMPLE_UNUSED_SOCKET")), + }, function(server) + return server:command({ "display-message", "-p", "owned daemon" }):await() + end):await() +end) +assert(result, tostring(err)) +``` diff --git a/docs/runtime.md b/docs/runtime.md index 97b52d7e..02bb51de 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -17,6 +17,36 @@ function returns the runtime and root Request immediately. It borrows the host loop and schedules callbacks outside fast events. `on_done(value, err)` runs after owned cleanup; unrelated host handles remain open. +## Deferred cleanup + +Register `runtime:defer(function(runtime) ... end)` inside a managed task to +run cleanup at that task's exit. The function can await requests. The runtime +joins body work, runs deferred functions in reverse registration order, then +closes client resources. A body exception or cancellation still runs those +functions with a path for asynchronous work. Repeated `close` calls do not +repeat cleanup; deferred functions run once. + +The [ordinary example](../examples/ordinary.lua) registers a session kill +before creating the session, then captures the returned handle for cleanup. +It connects to an existing daemon and destroys only the session it created. +The handle retains the daemon generation and session ID. Keep the connection +open until deferred operations finish. Closing the client connection itself +leaves remote objects intact. + +If teardown fails, the result has code `cleanup_failed`, the body error in +`cause`, and teardown errors in `errors`. Additional transport diagnostics +appear in `runtime_errors`. The adapter waits for teardown before returning +or calling `on_done`. Cleanup still depends on a functioning host dispatcher +and transport; host failure reports incomplete cleanup. Client cancellation +cannot recover an object ID from an ambiguous creation result, so deferred +cleanup is not a transaction or an adoption/find-or-create API. Use the +[owned lifecycle operations](lifecycle.md) for those contracts and creation receipts. + +Deferred registrations share `max_resources` as a separate count limit. A +registration failure returns `nil, err` before adding a callback. A cleanup +function runs in a managed coroutine, including on Lua 5.1; it does not yield +through `pcall` or `xpcall`. + ## Tasks and results The body receives its runtime. `runtime:spawn(body)` creates a child task and @@ -48,8 +78,8 @@ can settle before retirement, so these states differ. The task that creates an operation owns its cancellation. Canceling another task that waits on that operation detaches its wait; it does not cancel the producer. `request:cancel(reason)` cancels the requested operation explicitly. -`runtime:close(reason)` rejects new work, cancels owned work and returns the -root Request; repeated close calls are safe. +`runtime:close(reason)` rejects new body work, cancels owned work and returns +the root Request; repeated close calls are safe. Transport errors preserve `effect`: `not_sent`, `unknown`, or `completed`. Canceling a tmux client cannot prove that accepted daemon work stopped. diff --git a/docs/snapshots.md b/docs/snapshots.md index 722f8fba..da3a506e 100644 --- a/docs/snapshots.md +++ b/docs/snapshots.md @@ -5,10 +5,46 @@ Use `runtime:connect(options):await()` to bind a borrowed tmux daemon, then returns a Request. The [snapshot example](../examples/snapshot.lua) prints each unique pane and its window ID using the public API. -Pass an absolute `binary` and explicit absolute `socket_path` to `connect`. -Optional `config_path` defaults to `/dev/null`. Connection options are copied -before dispatch. The library does not select a default server or start one. -Importing the library and inspecting captured records perform no I/O. +`runtime:connect():await()` selects an existing daemon from captured defaults. +Pass `socket_path` or `socket_name` to select one explicitly; supplying both +returns `invalid_endpoint`. Selection follows this order: + +1. An explicit path or name. +2. Nonempty `LIBTMUX_SOCKET_PATH`. +3. Nonempty `LIBTMUX_SOCKET_NAME`. +4. Nonempty `TMUX`, parsed from its last two commas. +5. The named socket `default`. + +An empty environment selector counts as absent. A selected invalid value +returns `invalid_endpoint`; lower-precedence selectors do not override it. +Paths must be absolute and NUL-free. Names must be nonempty leaf names, +exclude `/`, `\` and NUL, and differ from `.` and `..`. The selected `TMUX` +context requires an absolute path, a positive decimal PID and a nonnegative +decimal session ID or `-1`; one leading `$` on a session ID is accepted. Paths +retain commas and whitespace. + +Named sockets use captured `TMUX_TMPDIR`, or `/tmp` when it is empty or absent, +followed by `tmux-UID/name`. The root must exist. Connection setup creates a +missing per-UID directory with mode 0700, without creating parent directories. +It accepts an existing real directory owned by the current UID with no +other-user permission bits; group permissions are allowed. Filesystem lookup +preserves `missing/..` failures and `symlink/..` traversal. Explicit paths do +not create parent directories. + +The connection captures its endpoint and client environment at the `connect` +call, before its Request runs. Later host edits cannot redirect commands or +cleanup. `binary` accepts an absolute path; omission resolves `tmux` through +the captured `PATH`. Optional `config_path` defaults to `/dev/null`. +`client_env` applies copied string overrides to the child environment; `false` +removes a key. These overrides also participate in endpoint selection. Clients +receive that snapshot with `TMUX` and `TMUX_PANE` removed. These settings leave +the host and tmux's [persistent environment](environment.md) unchanged. + +The additive connection option `env` supplies a complete child-environment sequence; `env = {}` supplies an empty environment. It preserves entry order, duplicate names, empty entries and bare entries, apart from filtering `TMUX` and `TMUX_PANE` before child launch. Endpoint selection uses the first value for each name, including an empty value. Connection and discovery use that same rule for `TMUX_TMPDIR`; an empty first value selects `/tmp`. Choose `env` or `client_env`, since complete replacement and overrides have different meanings. The existing per-command `CommandOptions.env` remains available with its sequence semantics and the same tmux-context filtering. + +Connect requires a running daemon, including on a fresh valid root. Preparing a directory does not start tmux. Use [`runtime:owned_server(options)`](lifecycle.md#taking-ownership-of-existing-objects) to start and own a daemon on an unused endpoint, or [`runtime:find_or_create_server(options)`](lifecycle.md#find-or-create) to reuse an existing daemon or start an owned one. The creator's managed task owns cleanup; a reused daemon remains borrowed. Server cleanup retains the published socket alias, so a later call cannot recreate a daemon at that stale path until the directory owner retires the alias under its own namespace coordination. Importing the library performs no I/O. +The [ordinary example](../examples/ordinary.lua) uses defaults and removes its +created session through [deferred cleanup](runtime.md#deferred-cleanup). Connection setup reads the actual daemon's version and identity. Linux socket binding creates a private socket alias in the selected socket's parent diff --git a/examples/ordinary.lua b/examples/ordinary.lua new file mode 100644 index 00000000..5c2cfd97 --- /dev/null +++ b/examples/ordinary.lua @@ -0,0 +1,24 @@ +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err ~= nil then + error(err, 0) + end + return value +end + +local result, failure = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + local created + must(runtime:defer(function() + if created then + must(created.session:kill():await()) + end + end)) + created = must(server:new_session({ name = "ordinary-example", argv = { "/bin/cat" } }):await()) + local snapshot = must(created.session:snapshot():await()) + assert(snapshot.name == "ordinary-example", "created session has the wrong name") + print("session: " .. snapshot.name) + return true +end) +assert(result, tostring(failure)) diff --git a/examples/owned_session.lua b/examples/owned_session.lua new file mode 100644 index 00000000..c661c7f9 --- /dev/null +++ b/examples/owned_session.lua @@ -0,0 +1,20 @@ +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err then + error(err, 0) + end + return value +end + +local result, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + return server + :with_session({ name = "owned-example", argv = { "/bin/cat" } }, function(session) + local snapshot = must(session:snapshot():await()) + print("session: " .. snapshot.name) + return true + end) + :await() +end) +assert(result, tostring(err)) diff --git a/lua/libtmux/_internal/command.lua b/lua/libtmux/_internal/command.lua index d3ab05b4..92fc8d00 100644 --- a/lua/libtmux/_internal/command.lua +++ b/lua/libtmux/_internal/command.lua @@ -115,7 +115,13 @@ function M.prepare(endpoint, commands) return invalid("invalid_endpoint", "tmux endpoint must be a plain table") end for key in next, endpoint do - if key ~= "binary" and key ~= "socket" and key ~= "config" and key ~= "no_start" then + if + key ~= "binary" + and key ~= "socket" + and key ~= "config" + and key ~= "no_start" + and key ~= "env" + then return invalid("invalid_endpoint", "unknown tmux endpoint field") end end @@ -125,11 +131,13 @@ function M.prepare(endpoint, commands) end local socket, config = rawget(endpoint, "socket"), rawget(endpoint, "config") local no_start = rawget(endpoint, "no_start") + local env = rawget(endpoint, "env") if not string_value(binary, true) or not string_value(socket, true) or (config ~= nil and not string_value(config, true)) or (no_start ~= nil and type(no_start) ~= "boolean") + or (env ~= nil and not process.prepare({ "tmux" }, { env = env })) then return invalid( "invalid_endpoint", @@ -172,9 +180,30 @@ function M.prepare(endpoint, commands) return result end +function M.process_options(endpoint, options) + local prepared, err = process.prepare({ endpoint.binary or "tmux" }, options) + if not prepared then + return nil, err + end + local copied = prepared.options + local selected = copied.env or endpoint.env + if selected then + copied.env = {} + for _, entry in ipairs(selected) do + if not entry:match("^TMUX=") and not entry:match("^TMUX_PANE=") then + copied.env[#copied.env + 1] = entry + end + end + end + return copied +end + function M.group(runtime, endpoint, commands, options) local argv, err = M.prepare(endpoint, commands) - if not argv then + if argv then + options, err = M.process_options(endpoint, options) + end + if err then return runtime:_request({ bytes = 0, start = function(settle, retire) diff --git a/lua/libtmux/_internal/control_io.lua b/lua/libtmux/_internal/control_io.lua index d917e9b3..ba5f6fbe 100644 --- a/lua/libtmux/_internal/control_io.lua +++ b/lua/libtmux/_internal/control_io.lua @@ -242,7 +242,7 @@ function M.start(runtime, endpoint, options, on_data, on_end) local ok, handle, cause = pcall( uv.spawn, endpoint.binary, - { args = args, stdio = pipes }, + { args = args, stdio = pipes, env = endpoint.env }, function(status, term_signal) exited, code, signal = true, status, term_signal close(child) diff --git a/lua/libtmux/_internal/defaults.lua b/lua/libtmux/_internal/defaults.lua new file mode 100644 index 00000000..64538428 --- /dev/null +++ b/lua/libtmux/_internal/defaults.lua @@ -0,0 +1,242 @@ +local errors = require("libtmux._internal.error") +local command = require("libtmux._internal.command") +local M = {} + +local function failure(message, cause) + return nil, + errors.new("invalid_endpoint", message, { + operation = "connect", + effect = "not_sent", + cause = cause, + }) +end + +local function plain(value) + return type(value) == "table" and getmetatable(value) == nil +end + +local function text(value) + return type(value) == "string" and not value:find("\000", 1, true) +end + +local function absolute(value) + return text(value) and value:sub(1, 1) == "/" and #value <= 4096 +end + +local function present(value) + return value ~= nil and value ~= "" +end + +local function name(value) + return text(value) + and value ~= "" + and value ~= "." + and value ~= ".." + and not value:find("/", 1, true) + and not value:find("\\", 1, true) +end + +local function context(value) + if not text(value) then + return failure("TMUX must contain a socket path, PID and session ID") + end + local path, pid, session = value:match("^(.*),([^,]*),([^,]*)$") + if not absolute(path) or not pid:match("^[0-9]+$") or not pid:find("[1-9]") then + return failure("TMUX needs an absolute socket path and positive decimal PID") + end + if session ~= "-1" and not session:match("^%$?[0-9]+$") then + return failure("TMUX needs a nonnegative decimal session ID or -1") + end + return { socket = path, pid = pid, session = session } +end + +local function environment(uv, overrides) + if not uv or type(uv.os_environ) ~= "function" then + return failure("connection requires a host environment snapshot") + end + local captured, cause = uv.os_environ() + if not captured then + return failure("cannot capture the client environment", cause) + end + local copied = {} + for key, value in pairs(captured) do + copied[key] = value + end + if overrides ~= nil then + if not plain(overrides) then + return failure("client_env must be a plain environment override map") + end + for key, value in next, overrides do + if + not text(key) + or key == "" + or key:find("=", 1, true) + or (value ~= false and not text(value)) + then + return failure("client_env needs NUL-free names and string values or false") + end + copied[key] = value ~= false and value or nil + end + end + return copied +end + +local function environment_values(entries) + local values = {} + for _, entry in ipairs(entries) do + local key, value = entry:match("^([^=]+)=(.*)$") + -- getenv uses the first entry, including an empty value. + if key and values[key] == nil then + values[key] = value + end + end + return values +end + +local function socket_root(env) + return present(env.TMUX_TMPDIR) and env.TMUX_TMPDIR or "/tmp" +end + +function M.socket_root(entries) + return socket_root(environment_values(entries)) +end + +local function explicit_environment(entries) + local prepared, err = command.process_options({}, { env = entries }) + if not prepared then + return failure("env must be a dense sequence of NUL-free environment entries", err) + end + local captured, copied = environment_values(prepared.env), {} + for _, entry in ipairs(prepared.env) do + local key = entry:match("^([^=]+)=") + -- Match getenv's first entry while preserving the original full sequence. + if key ~= "TMUX" and key ~= "TMUX_PANE" then + copied[#copied + 1] = entry + end + end + return captured, nil, copied +end + +local function executable(uv, env) + local search = env.PATH or "/usr/bin:/bin" + for component in (search .. ":"):gmatch("(.-):") do + local directory = component + if directory:sub(1, 1) ~= "/" then + local cwd, cause = uv.cwd() + if not cwd then + return failure("cannot resolve relative executable search directory", cause) + end + directory = cwd .. "/" .. directory + end + local candidate = directory .. "/tmux" + local stat = uv.fs_stat(candidate) + if stat and stat.type == "file" and uv.fs_access(candidate, "X") then + return candidate + end + end + return failure("cannot find tmux in the captured client PATH") +end + +function M.resolve(uv, options) + options = options == nil and {} or options + if not plain(options) then + return failure("connection options must be a plain record") + end + local allowed = { + binary = true, + socket_path = true, + socket_name = true, + config_path = true, + client_env = true, + env = true, + } + for key in next, options do + if not allowed[key] then + return failure("unknown connection option") + end + end + if options.socket_path ~= nil and options.socket_name ~= nil then + return failure("socket_path and socket_name are mutually exclusive") + end + if options.env ~= nil and options.client_env ~= nil then + return failure("env supplies the complete environment; choose env or client_env") + end + local env, err, explicit_entries + if options.env ~= nil then + env, err, explicit_entries = explicit_environment(options.env) + else + env, err = environment(uv, options.client_env) + end + if not env then + return nil, err + end + local path, selected_name, selected_context + if options.socket_path ~= nil then + path = options.socket_path + elseif options.socket_name ~= nil then + selected_name = options.socket_name + elseif present(env.LIBTMUX_SOCKET_PATH) then + path = env.LIBTMUX_SOCKET_PATH + elseif present(env.LIBTMUX_SOCKET_NAME) then + selected_name = env.LIBTMUX_SOCKET_NAME + elseif present(env.TMUX) then + selected_context, err = context(env.TMUX) + if not selected_context then + return nil, err + end + path = selected_context.socket + selected_context.pane = env.TMUX_PANE + else + selected_name = "default" + end + local root, uid + if selected_name ~= nil then + if not name(selected_name) then + return failure("socket_name must be a nonempty leaf name") + end + root = socket_root(env) + if not absolute(root) then + return failure("TMUX_TMPDIR must be an absolute NUL-free path") + end + uid = uv.getuid() + if type(uid) ~= "number" or uid < 0 or uid % 1 ~= 0 then + return failure("cannot determine the current UID for the named socket") + end + -- Keep components for filesystem resolution, including missing/.. and symlink/... + path = root .. "/tmux-" .. string.format("%.0f", uid) .. "/" .. selected_name + end + if not absolute(path) or path:sub(-1) == "/" then + return failure("socket_path must be an absolute NUL-free socket path") + end + local binary = options.binary + if binary == nil then + binary, err = executable(uv, env) + if not binary then + return nil, err + end + end + if + not absolute(binary) or (options.config_path ~= nil and not absolute(options.config_path)) + then + return failure("binary and config_path must be absolute NUL-free paths") + end + env.TMUX, env.TMUX_PANE = nil, nil + local entries = explicit_entries or {} + if not explicit_entries then + for key, value in pairs(env) do + entries[#entries + 1] = key .. "=" .. value + end + table.sort(entries) + end + return { + binary = binary, + socket = path, + config = options.config_path or "/dev/null", + env = entries, + root = root, + uid = uid, + context = selected_context, + } +end + +return M diff --git a/lua/libtmux/_internal/domain.lua b/lua/libtmux/_internal/domain.lua index b75b34f7..556161dc 100644 --- a/lua/libtmux/_internal/domain.lua +++ b/lua/libtmux/_internal/domain.lua @@ -385,6 +385,9 @@ local function receipt(state, generation, kind, parent, result, wrap) return created end +-- Owned creation reuses validation and argv semantics, with its own identity receipt. +M.prepare = prepare + function M.create(state, parent, kind, options, wrap) local generation, ref = current(state, parent) local plan, validation_error diff --git a/lua/libtmux/_internal/endpoint.lua b/lua/libtmux/_internal/endpoint.lua index 6275626f..3d693b88 100644 --- a/lua/libtmux/_internal/endpoint.lua +++ b/lua/libtmux/_internal/endpoint.lua @@ -35,18 +35,37 @@ local function options_copy(options) end local copied = {} for key, value in next, options do - if key ~= "binary" and key ~= "socket" and key ~= "config" then + if key == "env" then + local prepared, err = command.process_options({}, { env = value }) + if not prepared then + return nil, err + end + copied.env = prepared.env + elseif key == "uid" or key == "context" then + copied[key] = value + elseif + key == "binary" + or key == "socket" + or key == "config" + or key == "root" + or key == "pin_parent" + then + if not absolute(value) then + return nil, + failure("invalid_endpoint", "endpoint paths must be absolute and NUL-free") + end + copied[key] = value + else return nil, failure("invalid_endpoint", "unknown endpoint option") end - if not absolute(value) then - return nil, failure("invalid_endpoint", "endpoint paths must be absolute and NUL-free") - end - copied[key] = value end if not copied.binary or not copied.socket or copied.socket:sub(-1) == "/" then return nil, failure("invalid_endpoint", "endpoint needs explicit executable and socket paths") end + if copied.root and (type(copied.uid) ~= "number" or copied.uid < 0 or copied.uid % 1 ~= 0) then + return nil, failure("invalid_endpoint", "named endpoint requires a nonnegative UID") + end return copied end @@ -245,15 +264,41 @@ end function Bound:close() local state = assert(bindings[self], "invalid endpoint") + if (state.owners or 0) > 0 then + state.close_requested = true + return state.runtime:_operation(function() + return true + end, { operation = "endpoint.close" }) + end invalidate(state, "endpoint closed") return state.lease:close() end -local function execute(state, commands, options, raw_result) +-- Remote owners keep the accepted pin alive after their borrowed client closes. +function Bound:_hold() + local state = assert(bindings[self], "invalid endpoint") + state.owners = (state.owners or 0) + 1 + local held = true + return function() + if not held then + return + end + held, state.owners = false, state.owners - 1 + if state.owners == 0 and state.close_requested then + return self:close() + end + end +end + +local function execute(state, commands, options, raw_result, capture) local prepared, preparation_error = command.prepare(state.endpoint, commands) local plan if not preparation_error then - plan, preparation_error = process.prepare(prepared, options) + local copied + copied, preparation_error = command.process_options(state.endpoint, options) + if copied then + plan, preparation_error = process.prepare(prepared, copied) + end end state.active = state.active + 1 local request = state.runtime:_operation(function(rt, operation) @@ -267,7 +312,15 @@ local function execute(state, commands, options, raw_result) end operation:_set_effect("unknown") local result - result, err = process.execute(rt, plan.argv, plan.options):await() + local child = process.execute(rt, plan.argv, plan.options) + if capture then + -- A cancelled waiter must not discard a complete creation receipt. + child:_on_retire(function() + local value, cause = child:result() + capture(value or (cause and cause.partial), cause) + end) + end + result, err = child:await() result, err = process.retain_output(operation, result, err, "endpoint") if raw_result and err and err.code == "exit_failed" and err.effect == "completed" then return err.partial @@ -296,6 +349,11 @@ function Bound:group(commands, options) return execute(assert(bindings[self], "invalid endpoint"), commands, options, true) end +-- Lifecycle captures transport output before asynchronous delivery can be cancelled. +function Bound:_receipt(commands, options, capture) + return execute(assert(bindings[self], "invalid endpoint"), commands, options, true, capture) +end + -- Only the private observation transport receives the pinned endpoint and lease. function Bound:_client(open, close) local state = assert(bindings[self], "invalid endpoint") @@ -378,6 +436,38 @@ function M.bind(runtime, options) end state.lease = lease local stat + if copied.root then + stat, err = fs(state, "fs_stat", { copied.root }):await() + if not stat or stat.type ~= "directory" then + return nil, + failure( + "invalid_endpoint", + "named socket root is not an accessible directory", + err + ) + end + local directory = copied.root .. "/tmux-" .. string.format("%.0f", copied.uid) + local made + made, err = fs(state, "fs_mkdir", { directory, 448 }):await() + if not made and not tostring(err.cause):match("^EEXIST") then + return nil, err + end + stat, err = fs(state, "fs_lstat", { directory }):await() + if + not stat + or stat.type ~= "directory" + or stat.uid ~= copied.uid + or type(stat.mode) ~= "number" + or stat.mode % 8 ~= 0 + then + return nil, + failure( + "invalid_endpoint", + "named socket directory needs current UID and no other-user permissions", + err + ) + end + end stat, err = fs(state, "fs_lstat", { copied.socket }):await() if not stat or stat.type ~= "socket" then return nil, @@ -388,7 +478,9 @@ function M.bind(runtime, options) failure("uncertain_generation", "socket identity is not represented precisely") end state.stat = { dev = stat.dev, ino = stat.ino } - local parent = copied.socket:match("^(.*)/[^/]+$") + -- Startup keeps its pin beside the private directory so daemon + -- retirement can remove that directory before the owner drops its pin. + local parent = copied.pin_parent or copied.socket:match("^(.*)/[^/]+$") local directory directory, err = fs( state, @@ -422,6 +514,7 @@ function M.bind(runtime, options) socket = state.alias, config = copied.config, no_start = true, + env = copied.env, } state.evidence, err = read_evidence(state, operation) if not state.evidence then diff --git a/lua/libtmux/_internal/entity.lua b/lua/libtmux/_internal/entity.lua index 1b033c45..810414d3 100644 --- a/lua/libtmux/_internal/entity.lua +++ b/lua/libtmux/_internal/entity.lua @@ -318,6 +318,86 @@ function Entity:split(options) return domain.create(stored.server, stored.identity, "pane", options, M.from_reference) end +function Entity:adopt() + local stored = handles[self] + return require("libtmux._internal.lifecycle").adopt( + stored.server, + stored.identity, + self, + M.from_reference + ) +end + +function Entity:owned_window(options) + local stored = handles[self] + return require("libtmux._internal.lifecycle").create( + stored.server, + stored.identity, + "window", + options, + M.from_reference + ) +end + +function Entity:owned_pane(options) + local stored = handles[self] + return require("libtmux._internal.lifecycle").create( + stored.server, + stored.identity, + "pane", + options, + M.from_reference + ) +end + +function Entity:with_window(options, body) + local stored = handles[self] + return require("libtmux._internal.lifecycle").scoped_create( + stored.server, + stored.identity, + "window", + options, + M.from_reference, + body + ) +end + +function Entity:with_pane(options, body) + local stored = handles[self] + return require("libtmux._internal.lifecycle").scoped_create( + stored.server, + stored.identity, + "pane", + options, + M.from_reference, + body + ) +end + +function Entity:find_or_create_window(name, options) + local stored = handles[self] + return require("libtmux._internal.lifecycle").find( + stored.server, + stored.identity, + "window", + name, + options, + M.from_reference + ) +end + +function Entity:find_or_create_pane(pane_key, options) + local stored = handles[self] + return require("libtmux._internal.lifecycle").find( + stored.server, + stored.identity, + "pane", + pane_key, + options, + M.from_reference + ) +end + function Entity:snapshot(options) local stored = handles[self] return stored.server.runtime:_operation(function(_, operation) @@ -414,6 +494,13 @@ end --- A tmux session. ---@class libtmux.Session: libtmux.Configurable +---@field adopt fun(self:libtmux.Session):libtmux.Request> +---@field owned_window fun(self:libtmux.Session,options?:libtmux.NewWindowOptions): +--- libtmux.Request> +---@field with_window fun(self:libtmux.Session,options:libtmux.NewWindowOptions?, +--- body:fun(value:libtmux.Window,owner:libtmux.Owned):any):libtmux.Request +---@field find_or_create_window fun(self:libtmux.Session,key:string, +--- options?:libtmux.NewWindowOptions):libtmux.Request> ---@field new_window fun(self:libtmux.Session,options?:libtmux.NewWindowOptions): --- libtmux.Request Creates a window in this session. ---@field rename fun(self:libtmux.Session,name:string,options?:libtmux.TopologyOptions): @@ -443,6 +530,9 @@ end --- A tmux window. Placement in a session belongs to its window links. ---@class libtmux.Window: libtmux.Configurable +---@field adopt fun(self:libtmux.Window):libtmux.Request> +---@field find_or_create_pane fun(self:libtmux.Window,key:string, +--- options?:libtmux.SplitOptions):libtmux.Request> ---@field rename fun(self:libtmux.Window,name:string,options?:libtmux.TopologyOptions): --- libtmux.Request Renames this window. ---@field kill fun(self:libtmux.Window,options?:libtmux.TopologyOptions): @@ -469,6 +559,13 @@ end --- A tmux pane. ---@class libtmux.Pane: libtmux.Configurable +---@field adopt fun(self:libtmux.Pane):libtmux.Request> +---@field owned_pane fun(self:libtmux.Pane,options?:libtmux.SplitOptions): +--- libtmux.Request> +---@field with_pane fun(self:libtmux.Pane,options:libtmux.SplitOptions?, +--- body:fun(value:libtmux.Pane,owner:libtmux.Owned):any):libtmux.Request +---@field find_or_create_pane fun(self:libtmux.Pane,key:string, +--- options?:libtmux.SplitOptions):libtmux.Request> ---@field send_keys fun(self:libtmux.Pane,keys:string[],options?:libtmux.KeyOptions): --- libtmux.Request Sends key names, as tmux's send-keys reads them. ---@field send_text fun(self:libtmux.Pane,text:string,options?:libtmux.PaneOptions): diff --git a/lua/libtmux/_internal/lifecycle.lua b/lua/libtmux/_internal/lifecycle.lua new file mode 100644 index 00000000..b098fdd9 --- /dev/null +++ b/lua/libtmux/_internal/lifecycle.lua @@ -0,0 +1,857 @@ +local codec = require("libtmux._internal.codec") +local command = require("libtmux._internal.command") +local domain = require("libtmux._internal.domain") +local errors = require("libtmux._internal.error") +local identity = require("libtmux._internal.identity") +local M, Owner = {}, {} +local owners = setmetatable({}, { __mode = "k" }) +local queues = setmetatable({}, { __mode = "k" }) +local token_option = "@libtmux_owner_generation" +local pane_option = "@libtmux_pane_key" +local fields = + { "pid", "start_time", token_option, "session_id", "window_id", "pane_id", "window_index" } +local creation_format = assert(codec.format(fields)) +local prefixes = { session = "$", window = "@", pane = "%" } + +local function failure(code, message, details) + details = details or {} + details.operation, details.effect = "lifecycle", details.effect or "not_sent" + return errors.new(code, message, details) +end + +local function plain(value) + return type(value) == "table" and getmetatable(value) == nil +end + +local function copy_options(options) + local entries, bytes = 0, 0 + local function copy(value, depth) + if type(value) == "string" then + bytes = bytes + #value + if bytes > 1048576 then + error(failure("invalid_options", "lifecycle input exceeds one MiB"), 0) + end + elseif type(value) == "table" then + if not plain(value) or depth > 4 then + error( + failure("invalid_options", "lifecycle options require bounded plain records"), + 0 + ) + end + local result = {} + for key, item in pairs(value) do + entries = entries + 1 + if entries > 4096 or (type(key) ~= "number" and type(key) ~= "string") then + error( + failure("invalid_options", "lifecycle options exceed their entry limit"), + 0 + ) + end + result[key] = copy(item, depth + 1) + end + return result + end + return value + end + local ok, copied = pcall(copy, options or {}, 0) + if not ok then + return nil, copied + end + return copied +end + +local function valid_token(value) + return type(value) == "string" and #value == 32 and value:match("^[0-9a-fA-F]+$") ~= nil +end + +local function decimal(value, positive) + return type(value) == "string" + and value:match("^[0-9]+$") + and (not positive or value:find("[1-9]")) +end + +local function nonce(uv) + local bytes, cause = uv.random(16) + if not bytes or #bytes ~= 16 then + return nil, failure("unsupported", "cannot obtain ownership randomness", { cause = cause }) + end + return ( + bytes:gsub(".", function(byte) + return string.format("%02x", byte:byte()) + end) + ) +end + +local function program(commands) + return assert(command.prepare_program({ commands = commands }, true)) +end + +local function condition(receipt) + return "#{&&:#{==:#{pid}," + .. receipt.pid + .. "},#{&&:#{==:#{start_time}," + .. receipt.started + .. "},#{==:#{" + .. token_option + .. "}," + .. receipt.token + .. "}}}" +end + +local function guarded(receipt, commands) + return { + "if-shell", + "-F", + condition(receipt), + program(commands), + program({ { "display-message", "-p", "libtmux-stale-owner" } }), + } +end + +local function current(state, reference) + if state.closed then + return nil, failure("closed", "server handle is closed") + end + local generation, err = state.bound:generation() + if not generation then + return nil, err + end + if reference then + local ref + ref, err = identity.inspect(generation, reference) + if not ref then + return nil, err + end + return generation, ref + end + return generation +end + +local function proc(uv, pid) + local fd, cause = uv.fs_open("/proc/" .. pid .. "/stat", "r", 0) + if not fd then + if tostring(cause):match("^ENOENT") then + return { gone = true } + end + return nil, cause + end + local text, err = uv.fs_read(fd, 16384, 0) + uv.fs_close(fd) + local rest = text and text:match("^%d+ %b() (.*)$") + -- Process names may contain parentheses; the final ') ' starts the fields. + if text then + rest = text:match("^%d+ %(.*%) (.*)$") + end + if not rest then + return nil, err or "malformed process identity" + end + local values = {} + for field in rest:gmatch("%S+") do + values[#values + 1] = field + end + if not decimal(values[20], false) then + return nil, "missing process start tick" + end + return { start = values[20], gone = values[1] == "Z" or values[1] == "X" } +end + +local function process_exited(stored) + local observed, err = proc(stored.state.runtime._driver.uv, stored.receipt.pid) + if not observed then + return nil, err + end + return observed.gone or observed.start ~= stored.process_start +end + +local function wait_exit(stored) + local runtime = stored.state.runtime + return runtime:_request({ + bytes = 0, + timeout = 750, + operation = "owner.exit", + start = function(settle, retire) + local timer = runtime._driver.uv.new_timer() + local finished = false + local function finish(value, err) + if finished then + return + end + finished = true + timer:stop() + timer:close(function() + retire() + end) + settle(value, err) + end + local function check() + local gone, err = process_exited(stored) + if gone then + finish(true) + elseif gone == nil then + finish( + nil, + failure( + "uncertain_exit", + "cannot observe accepted daemon exit", + { cause = err } + ) + ) + end + end + timer:start(0, 5, check) + return function(err) + finish(nil, err) + end + end, + }) +end + +local function parse(result, kind, expected, generation) + local rows, cause + if result then + rows, cause = codec.decode(result.stdout, 7, { max_rows = 1, max_bytes = 16384 }) + end + local row = rows and rows[1] + if + not row + or #rows ~= 1 + or not decimal(row[1], true) + or not decimal(row[2], false) + or not valid_token(row[3]) + then + return nil, + failure( + "invalid_receipt", + "ownership requires one complete daemon receipt", + { cause = cause, partial = result, effect = "unknown" } + ) + end + local receipt = + { pid = row[1], started = row[2], token = row[3], kind = kind, generation = generation } + if kind ~= "server" then + for i, key in ipairs({ "session", "window", "pane" }) do + if not row[i + 3]:match("^" .. "%" .. prefixes[key] .. "[0-9]+$") then + return nil, + failure( + "invalid_receipt", + "ownership receipt has an invalid object ID", + { partial = result, effect = "unknown" } + ) + end + receipt[key] = row[i + 3] + end + if not decimal(row[7], false) or tonumber(row[7]) > 2147483647 then + return nil, + failure( + "invalid_receipt", + "ownership receipt has an invalid window index", + { partial = result, effect = "unknown" } + ) + end + receipt.index, receipt.id = tonumber(row[7]), receipt[kind] + if expected and receipt.id ~= expected then + return nil, + failure( + "invalid_receipt", + "ownership receipt identifies another object", + { partial = result, effect = "unknown" } + ) + end + end + return receipt +end + +local function wrap_owner(state, value, receipt, process_start) + local stored = { + state = state, + value = value, + receipt = receipt, + process_start = process_start, + unpin = state.bound:_hold(), + } + local owner = setmetatable({}, { + __index = function(_, key) + if key == "value" then + return stored.value + end + if key == "closed" then + return stored.closed == true + end + if key == "cleanup_error" then + return stored.cleanup_error + end + return Owner[key] + end, + __metatable = "libtmux.Owned", + }) + owners[owner] = stored + return owner +end + +local function owner_from_receipt(state, receipt, wrap, value) + local evidence, err = state.bound:evidence() + if not evidence or evidence.pid ~= receipt.pid or evidence.started ~= receipt.started then + return nil, err or failure("stale_generation", "receipt does not identify the bound daemon") + end + local observed, cause = proc(state.runtime._driver.uv, receipt.pid) + if not observed or observed.gone then + return nil, + failure( + "uncertain_generation", + "cannot accept live daemon process identity", + { cause = cause } + ) + end + if not value then + value, err = + wrap(state, { kind = receipt.kind, id = receipt.id, generation = receipt.generation }) + end + return wrap_owner(state, value, receipt, observed.start), err +end + +function Owner:receipt() + local result = {} + for key, value in pairs(owners[self].receipt) do + if key ~= "generation" then + result[key] = value + end + end + return result +end + +function Owner:release() + local stored = owners[self] + if stored.inflight and not stored.inflight:is_retired() then + return nil, failure("busy", "cannot release ownership during cleanup") + end + stored.released = true + stored.unpin() + if stored.on_release then + stored.on_release() + end + return stored.value +end + +function Owner:close() + local stored = owners[self] + if stored.inflight and not stored.inflight:is_retired() then + return stored.inflight + end + local state, receipt = stored.state, stored.receipt + local request = state.runtime:_operation(function() + if stored.closed or stored.released then + return true + end + local gone, cause = process_exited(stored) + if gone then + stored.closed = true + return true + end + if gone == nil then + return nil, + failure( + "uncertain_exit", + "cannot verify accepted daemon process", + { cause = cause } + ) + end + local commands = { { "kill-" .. receipt.kind } } + if receipt.id then + commands[1][2], commands[1][3] = "-t", receipt.id + end + local result, err = state.bound + :execute(guarded(receipt, commands), { timeout = 750, max_output_bytes = 16384 }) + :await() + if not result then + local exited = process_exited(stored) + if exited then + stored.closed = true + return true + end + -- Exact IDs cannot be reused in one daemon generation. Confirm absence + -- through a successful guarded listing rather than parsing locale text. + if receipt.id then + local listing = "list-" .. receipt.kind .. "s" + local argv = { listing, "-F", "#{" .. receipt.kind .. "_id}" } + if receipt.kind ~= "session" then + table.insert(argv, 2, "-a") + end + local observed, observe_error = + state.bound:execute(guarded(receipt, { argv }), { timeout = 750 }):await() + if observed and observed.stdout ~= "libtmux-stale-owner\n" then + local found = false + for id in observed.stdout:gmatch("[^\n]+") do + if not id:match("^%" .. prefixes[receipt.kind] .. "[0-9]+$") then + return nil, + failure("invalid_receipt", "cleanup listing contains malformed IDs") + end + if id == receipt.id then + found = true + end + end + if not found then + stored.closed = true + return true + end + end + if observe_error then + err.observation_error = observe_error + end + end + return nil, err + end + if result.stdout == "libtmux-stale-owner\n" then + return nil, + failure("stale_generation", "reserved generation token changed; cleanup refused") + end + if result.stdout ~= "" or result.stderr ~= "" then + return nil, + failure( + "invalid_receipt", + "cleanup returned unexpected output", + { partial = result } + ) + end + if receipt.kind == "server" then + local exited, exit_error = wait_exit(stored):await() + if not exited then + return nil, exit_error + end + end + stored.closed, stored.cleanup_error = true, nil + return true + end, { operation = "owner.close", effect = "not_sent" }) + do + local remote = request + request = state.runtime:_operation(function() + local value, err = remote:await() + if not value and not stored.finalize then + return nil, err + end + if stored.released then + return true + end + if stored.finalize then + value, err = stored.finalize():await() + if not value then + return nil, err + end + -- Foreground startup also owns a native child handle. That exact + -- process remains ours when the published socket is replaced. + stored.closed, stored.cleanup_error = true, nil + end + local retired = stored.unpin() + if retired then + return retired:await() + end + return true + end, { operation = "owner.retire", effect = "not_sent" }) + end + stored.inflight = request + request:_on_retire(function() + local _, err = request:result() + if err then + stored.cleanup_error, stored.closed = err, false + end + end) + return request +end + +function M.transfer(owner) + local stored = owners[owner] + stored.released = true + local transferred = wrap_owner(stored.state, stored.value, stored.receipt, stored.process_start) + stored.unpin() + owners[transferred].finalize, owners[transferred].on_release = + stored.finalize, stored.on_release + return transferred +end + +function M.attach(owner, finalize, on_release) + owners[owner].finalize, owners[owner].on_release = finalize, on_release +end + +local function register(runtime, holder) + return runtime:defer(function() + if holder.owner then + return holder.owner:close():await() + end + return true + end) +end + +function M.adopt(state, reference, value, wrap) + local generation, ref = current(state, reference) + local holder = {} + local registered, registration_error = register(state.runtime, holder) + return state.runtime:_operation(function() + if not registered then + return nil, registration_error + end + if not generation then + return nil, ref + end + local kind, id = ref and ref.kind or "server", ref and ref.id + if kind ~= "server" and not prefixes[kind] then + return nil, + failure("invalid_target", "ownership requires a server, session, window or pane") + end + local token, err = nonce(state.runtime._driver.uv) + if not token then + return nil, err + end + local display = { "display-message", "-p" } + if id then + display[#display + 1], display[#display + 2] = "-t", id + end + display[#display + 1] = creation_format + local result + result, err = state.bound + :group( + { { "set-option", "-soq", token_option, token }, display }, + { timeout = 750, max_output_bytes = 16384 } + ) + :await() + if not result then + return nil, err + end + if result.exit_code ~= 0 or result.stderr ~= "" then + return nil, + failure("accept_failed", "cannot accept object ownership", { partial = result }) + end + local receipt + receipt, err = parse(result, kind, id, generation) + if not receipt then + return nil, err + end + holder.owner, err = owner_from_receipt(state, receipt, wrap, value) + return holder.owner, err + end, { operation = "adopt", effect = "not_sent" }) +end + +function M.create(state, parent, kind, options, wrap) + local generation, ref = current(state, parent) + local plan, preparation_error + if generation then + local ok, prepared = pcall(domain.prepare, state.runtime, kind, ref, options) + if ok then + plan = prepared + else + preparation_error = prepared + end + else + preparation_error = ref + end + local holder = {} + local registered, registration_error = register(state.runtime, holder) + return state.runtime:_operation(function(rt) + if not registered then + return nil, registration_error + end + if not plan then + return nil, preparation_error + end + local handed_off, attempted, receipt_error = false, false, nil + local deferred, defer_error = rt:defer(function() + if handed_off then + return true + end + if holder.owner then + local cleaned, err = holder.owner:close():await() + if not cleaned then + return nil, + failure( + "rollback_failed", + "created object cleanup failed; retry through owner", + { cause = err, owner = holder.owner } + ) + end + elseif attempted then + return nil, + failure( + "creation_unknown", + "creation has no complete accepted receipt; cleanup cannot guess a target", + { cause = receipt_error, effect = "unknown" } + ) + end + return true + end) + if not deferred then + return nil, defer_error + end + if plan.cwd then + local valid, err = domain.directory(state, plan.cwd):await() + if not valid then + return nil, err + end + end + local token, err = nonce(rt._driver.uv) + if not token then + return nil, err + end + local accepted + accepted, err = state.bound + :group({ + { "set-option", "-soq", token_option, token }, + { "display-message", "-p", creation_format }, + }, { timeout = 750, max_output_bytes = 16384 }) + :await() + if not accepted then + return nil, err + end + local before + before, err = parse(accepted, "server", nil, generation) + if not before then + return nil, err + end + for index, value in ipairs(plan.argv) do + if value == "-F" then + plan.argv[index + 1] = creation_format + break + end + end + local acquisition = state.bound:_receipt( + { guarded(before, { plan.argv }) }, + plan.options, + function(result, cause) + attempted = not cause or cause.effect ~= "not_sent" + if result and result.stdout == "libtmux-stale-owner\n" then + attempted, receipt_error = + false, failure("stale_generation", "generation changed before creation") + return + end + local receipt + receipt, receipt_error = parse(result, kind, nil, generation) + if receipt and kind == "window" and (not ref or receipt.session ~= ref.id) then + receipt, receipt_error = + nil, failure("invalid_receipt", "created window belongs to another session") + end + if receipt then + holder.owner, receipt_error = owner_from_receipt(state, receipt, wrap) + end + end + ) + local result + result, err = acquisition:await() + if not result then + return nil, err + end + if result.exit_code ~= 0 or result.stderr ~= "" then + return nil, + failure( + "create_failed", + "tmux creation failed", + { partial = result, owner = holder.owner, effect = "completed" } + ) + end + if receipt_error then + receipt_error.owner = holder.owner + return nil, receipt_error + end + if not holder.owner then + return nil, failure("invalid_receipt", "creation did not yield an accepted owner") + end + handed_off = true + return holder.owner + end, { operation = "owned_" .. kind, effect = "not_sent" }) +end + +function M.scoped_create(state, parent, kind, options, wrap, body) + local copied, err = copy_options(options) + return state.runtime:_operation(function() + if not copied then + return nil, err + end + if type(body) ~= "function" then + return nil, failure("invalid_callback", "owned scope requires a function") + end + local owner, cause = M.create(state, parent, kind, copied, wrap):await() + if not owner then + return nil, cause + end + return body(owner.value, owner) + end, { operation = "owned_scope", effect = "not_sent" }) +end + +function Owner:scope(body) + local stored = owners[self] + return stored.state.runtime:_operation(function(rt) + if type(body) ~= "function" then + return nil, failure("invalid_callback", "owned scope requires a function") + end + local ok, err = rt:defer(function() + return self:close():await() + end) + if not ok then + return nil, err + end + return body(stored.value, self) + end, { operation = "owned_scope", effect = "not_sent" }) +end + +local function key_text(value) + return type(value) == "string" + and #value > 0 + and #value <= 1024 + and not value:find("[%z\001-\031\127]") +end + +function M.find(state, parent, kind, key, options, wrap) + local generation, ref = current(state, parent) + local rt, holder = state.runtime, {} + local registered, registration_error = register(rt, holder) + local copied, invalid = copy_options(options) + if type(copied) ~= "table" or not plain(copied) then + copied, invalid = + {}, + invalid or failure("invalid_options", "find-or-create options must be a plain record") + end + if + not key_text(key) + or (kind ~= "pane" and key:find("\\", 1, true)) + or (kind == "session" and key:find("[.:]")) + then + invalid = failure( + "invalid_options", + "lookup names exclude backslashes; session names also exclude dots and colons" + ) + end + if kind ~= "pane" then + if copied.name and copied.name ~= key then + invalid = failure("invalid_options", "creation name must match the lookup name") + end + copied.name = key + end + local bucket = queues[rt] or {} + queues[rt] = bucket + local endpoint = state.endpoint.socket + local previous = bucket[endpoint] + local request = rt:_operation(function() + if previous then + previous:await() + end + if not registered then + return nil, registration_error + end + if invalid then + return nil, invalid + end + if not generation then + return nil, ref + end + if kind == "window" and (not ref or ref.kind ~= "session") then + return nil, failure("invalid_target", "window lookup requires a session") + end + if kind == "pane" and (not ref or (ref.kind ~= "pane" and ref.kind ~= "window")) then + return nil, failure("invalid_target", "pane lookup requires a pane or window") + end + local argv = { + "list-" .. kind .. "s", + "-F", + assert( + codec.format({ kind .. "_id", kind == "pane" and pane_option or kind .. "_name" }) + ), + } + if ref then + argv[#argv + 1], argv[#argv + 2] = "-t", ref.id + end + local result, err = + state.bound:execute(argv, { timeout = 750, max_output_bytes = 1048576 }):await() + if not result then + return nil, err + end + local rows + rows, err = codec.decode(result.stdout, 2, { max_rows = 16384, max_bytes = 1048576 }) + if not rows then + return nil, err + end + local selected, first + for _, row in ipairs(rows) do + if not row[1]:match("^%" .. prefixes[kind] .. "[0-9]+$") then + return nil, failure("invalid_receipt", "lookup returned a malformed object ID") + end + first = first or row[1] + if row[2] == key then + if selected then + return nil, + failure("ambiguous", "more than one object matches the exact lookup key") + end + selected = row[1] + end + end + if selected then + local value + value, err = wrap(state, { kind = kind, id = selected, generation = generation }) + if not value then + return nil, err + end + return { value = value, created = false } + end + local creation_parent = parent + if kind == "pane" and ref and ref.kind == "window" then + if not first then + return nil, failure("target_missing", "window has no pane to split") + end + creation_parent, err = + identity.bind(generation, { kind = "pane", id = first, generation = generation }) + if not creation_parent then + return nil, err + end + end + local owner + owner, err = M.create(state, creation_parent, kind, copied, wrap):await() + if not owner then + return nil, err + end + if kind == "pane" then + local receipt = owners[owner].receipt + local configured + configured, err = state.bound + :execute( + guarded(receipt, { + { "set-option", "-p", "-t", receipt.id, pane_option, key }, + }), + { timeout = 750 } + ) + :await() + if not configured or configured.stdout ~= "" then + return nil, + err or failure( + "stale_generation", + "pane identity changed while assigning its key" + ) + end + end + -- Move automatic cleanup from this finite lookup task to its caller. + holder.owner = M.transfer(owner) + return { value = holder.owner.value, created = true, owner = holder.owner } + end, { operation = "find_or_create_" .. kind, effect = "not_sent" }) + bucket[endpoint] = request + request:_on_retire(function() + if bucket[endpoint] == request then + bucket[endpoint] = nil + end + end) + return request +end + +M.parse, M.nonce = parse, nonce + +---@class libtmux.Owned +---@field value T Accepted object; its client connection remains borrowed. +---@field closed boolean True only after successful cleanup. +---@field cleanup_error? libtmux.Error Last failed cleanup attempt. +---@field close fun(self:libtmux.Owned):libtmux.Request +--- Retryable destruction of the accepted generation. +---@field release fun(self:libtmux.Owned):T?,libtmux.Error? +--- Relinquish destruction responsibility. +---@field receipt fun(self:libtmux.Owned):table Copy of the accepted daemon and object identity. +---@field scope fun(self:libtmux.Owned, +--- body:fun(value:T,owner:libtmux.Owned):any):libtmux.Request + +---@class libtmux.FoundOrCreated +---@field value T +---@field created boolean +---@field owner? libtmux.Owned Present only for this call's new object. + +return M diff --git a/lua/libtmux/_internal/runtime.lua b/lua/libtmux/_internal/runtime.lua index b1474ee6..d8a01a6d 100644 --- a/lua/libtmux/_internal/runtime.lua +++ b/lua/libtmux/_internal/runtime.lua @@ -97,6 +97,7 @@ function M.new(driver, options) _bytes = 0, _resource_bytes = 0, _tasks = 0, + _deferred = 0, _callbacks = 0, _resources = {}, _resources_closing = 0, @@ -183,7 +184,7 @@ function Runtime:_owner() return nil end scope = scope or self._root_scope - if self._closing or not scope or scope.finished or scope.error then + if not scope or (self._closing and not scope.cleanup) or scope.finished or scope.error then return nil end return scope @@ -522,11 +523,17 @@ function Runtime:_start_request(req) end function Runtime:_admit() - if self._closing then - return - end while self._active < self._limits.max_active and #self._pending > 0 do - local req = table.remove(self._pending, 1) + local index = 1 + if self._closing then + while self._pending[index] and not self._pending[index]._owner.cleanup do + index = index + 1 + end + if not self._pending[index] then + return + end + end + local req = table.remove(self._pending, index) if not req._retired then req._queued, req._admitted = false, true self._active = self._active + 1 @@ -634,6 +641,33 @@ function Runtime:_join(scope) then return end + if scope.deferred and #scope.deferred > 0 then + local fn = table.remove(scope.deferred) + self._deferred = self._deferred - 1 + scope.joining = true + local cleanup = self:_task(fn, scope, nil, true, true) + cleanup:_on_retire(function() + local _, err = cleanup:result() + if err then + scope.cleanup_errors = scope.cleanup_errors or {} + scope.cleanup_errors[#scope.cleanup_errors + 1] = err + self:_record(cleanup_error(err)) + end + end) + scope.joining = false + if cleanup:is_retired() then + self:_join(scope) + end + return + end + if scope.cleanup_errors and not scope.cleanup_reported then + scope.cleanup_reported = true + scope.value, scope.error = + nil, errors.new("cleanup_failed", "deferred cleanup failed", { + cause = scope.error, + errors = scope.cleanup_errors, + }) + end if scope == self._root_scope then self._closing = true if #self._resources > 0 then @@ -682,7 +716,10 @@ function Runtime:_abort(scope, err) remove(scope.waiting._waiters, scope) scope.waiting = nil end - scope.request:_settle(nil, err) + -- Deferred teardown can still fail; publish its combined result after it retires. + if not scope.deferred then + scope.request:_settle(nil, err) + end local owned = {} for i, req in ipairs(scope.owned) do owned[i] = req @@ -737,7 +774,7 @@ function Runtime:_resume(scope, ...) end end -function Runtime:_task(fn, owner, context, boundary) +function Runtime:_task(fn, owner, context, boundary, cleanup) if type(fn) ~= "function" then return self:_rejected_request("invalid_task", "task body must be a function") end @@ -746,12 +783,15 @@ function Runtime:_task(fn, owner, context, boundary) end local req = request(self, owner) req._context, req._effect = context, context and context.effect + cleanup = cleanup or (owner and owner.cleanup) + req._cleanup = cleanup local scope = { runtime = self, request = req, owned = {}, callbacks = 0, boundary = boundary, + cleanup = cleanup, } scope.co = coroutine.create(function() return fn(self, req) @@ -781,6 +821,25 @@ function Runtime:start(fn) return req end +--- Register an asynchronous cleanup in the current task, in reverse registration order. +function Runtime:defer(fn) + local co = coroutine.running() + local scope = co and managed[co] + if not scope or scope.runtime ~= self or scope.body_done or scope.error then + return nil, errors.new("invalid_scope", "defer needs a live managed task") + end + if type(fn) ~= "function" then + return nil, errors.new("invalid_callback", "defer needs a cleanup function") + end + if self._deferred >= self._limits.max_resources then + return nil, errors.new("queue_full", "deferred cleanup limit reached") + end + scope.deferred = scope.deferred or {} + scope.deferred[#scope.deferred + 1] = fn + self._deferred = self._deferred + 1 + return true +end + function Runtime:spawn(fn) local owner = self:_owner() if not owner then @@ -986,6 +1045,7 @@ function Runtime:stats() bytes = self._bytes, resource_bytes = self._resource_bytes, tasks = self._tasks, + deferred = self._deferred, callbacks = self._callbacks, resources = #self._resources, resources_closing = self._resources_closing, @@ -1007,6 +1067,22 @@ function Runtime:connect(options) return require("libtmux._internal.server").connect(self, options) end +function Runtime:owned_server(options) + return require("libtmux._internal.servers").start(self, options, false) +end + +function Runtime:find_or_create_server(options) + return require("libtmux._internal.servers").start(self, options, true) +end + +function Runtime:discover_servers(options) + return require("libtmux._internal.servers").discover(self, options) +end + +function Runtime:with_server(options, body) + return require("libtmux._internal.servers").scope(self, options, body) +end + function Runtime:errors() local result = {} for i, err in ipairs(self._errors) do @@ -1022,6 +1098,8 @@ end ---@field effect? "not_sent"|"unknown"|"completed" ---@field cause? unknown ---@field partial? unknown +---@field errors? libtmux.Error[] Deferred teardown errors. +---@field runtime_errors? libtmux.Error[] Additional runtime cleanup diagnostics. ---@class libtmux.Request ---@field await fun(self:libtmux.Request):T?, libtmux.Error? @@ -1043,8 +1121,18 @@ end ---@field dispatch_budget? integer ---@class libtmux.Runtime +---@field owned_server fun(self:libtmux.Runtime,options?:libtmux.ConnectOptions): +--- libtmux.Request> +---@field find_or_create_server fun(self:libtmux.Runtime,options?:libtmux.ConnectOptions): +--- libtmux.Request> +---@field discover_servers fun(self:libtmux.Runtime,options?:libtmux.DiscoveryOptions): +--- libtmux.Request +---@field with_server fun(self:libtmux.Runtime,options:libtmux.ConnectOptions?, +--- body:fun(server:libtmux.Server,owner:libtmux.Owned):any):libtmux.Request ---@field connect fun(self:libtmux.Runtime, ---- options:libtmux.ConnectOptions):libtmux.Request +--- options?:libtmux.ConnectOptions):libtmux.Request +---@field defer fun(self:libtmux.Runtime, +--- cleanup:fun(runtime:libtmux.Runtime)):boolean?, libtmux.Error? ---@field spawn fun(self:libtmux.Runtime, --- body:fun(runtime:libtmux.Runtime):T?, libtmux.Error?):libtmux.Request ---@field close fun(self:libtmux.Runtime, reason?:string):libtmux.Request diff --git a/lua/libtmux/_internal/server.lua b/lua/libtmux/_internal/server.lua index 43dda968..8e428341 100644 --- a/lua/libtmux/_internal/server.lua +++ b/lua/libtmux/_internal/server.lua @@ -3,6 +3,7 @@ local environment = require("libtmux._internal.environment") local buffer = require("libtmux._internal.buffer") local client = require("libtmux._internal.client") local endpoints = require("libtmux._internal.endpoint") +local defaults = require("libtmux._internal.defaults") local errors = require("libtmux._internal.error") local fields = require("libtmux._internal.fields") local graph = require("libtmux._internal.graph") @@ -39,21 +40,6 @@ local function integer(value, maximum) return type(value) == "number" and value >= 1 and value <= maximum and value % 1 == 0 end -local function connection_options(options) - if not plain(options) then - return nil, failure("invalid_options", "connection options must be a plain record") - end - local copied, mapping = - {}, { binary = "binary", socket_path = "socket", config_path = "config" } - for key, value in next, options do - if not mapping[key] then - return nil, failure("invalid_options", "unknown connection option") - end - copied[mapping[key]] = value - end - return copied -end - local function capture_options(state, options) options = options == nil and {} or options if not plain(options) then @@ -460,6 +446,48 @@ function Server:new_session(options) return domain.create(servers[self], nil, "session", options, entities.from_reference) end +--- Accept destruction responsibility for this daemon in the current managed task. +function Server:adopt() + return require("libtmux._internal.lifecycle").adopt( + servers[self], + nil, + self, + entities.from_reference + ) +end + +function Server:owned_session(options) + return require("libtmux._internal.lifecycle").create( + servers[self], + nil, + "session", + options, + entities.from_reference + ) +end + +function Server:with_session(options, body) + return require("libtmux._internal.lifecycle").scoped_create( + servers[self], + nil, + "session", + options, + entities.from_reference, + body + ) +end + +function Server:find_or_create_session(name, options) + return require("libtmux._internal.lifecycle").find( + servers[self], + nil, + "session", + name, + options, + entities.from_reference + ) +end + function Server:observe(session, options) return observation.open(servers[self], session, options) end @@ -513,8 +541,13 @@ function Server:close() return state.bound:close() end -function M.connect(runtime, options) - local copied, validation_error = connection_options(options) +function M.connect(runtime, options, resolved) + local copied, validation_error + if resolved then + copied = options + else + copied, validation_error = defaults.resolve(runtime._driver.uv, options) + end local binding local request = runtime:_operation(function(rt) if not copied then @@ -531,7 +564,13 @@ function M.connect(runtime, options) bound:close():await() return nil, err end - local state = { runtime = rt, bound = bound, version = evidence.version, methods = Server } + local state = { + runtime = rt, + bound = bound, + version = evidence.version, + methods = Server, + endpoint = copied, + } local server = setmetatable({}, { __index = function(_, key) return state.methods[key] @@ -562,10 +601,20 @@ function M.connect(runtime, options) return request end +-- Startup and discovery already captured defaults before scheduling work. +function M.resolved(runtime, endpoint) + return M.connect(runtime, endpoint, true) +end + ---@class libtmux.ConnectOptions ----@field binary string Absolute tmux executable path. ----@field socket_path string Absolute existing daemon socket path. +---@field binary? string Absolute executable; omitted resolves tmux through captured PATH. +---@field socket_path? string Absolute existing daemon socket path; excludes socket_name. +---@field socket_name? string Named socket leaf; excludes socket_path. ---@field config_path? string Absolute configuration path. +--- Defaults to /dev/null. +---@field env? string[] Explicit process environment entries. +--- Complete child environment, including an empty sequence; excludes client_env. +---@field client_env? table Copied client overrides; false removes a variable. ---@class libtmux.SnapshotOptions ---@field strict? boolean Perform one additional topology verification pass. @@ -577,7 +626,7 @@ end ---@class libtmux.CommandOptions ---@field stdin? string ---@field cwd? string ----@field env? string[] Explicit process environment entries. +---@field env? string[] Per-command client environment; TMUX and TMUX_PANE are removed. ---@field timeout? number ---@field deadline? number ---@field max_output_bytes? integer @@ -601,6 +650,14 @@ end ---@field error? libtmux.Error ---@class libtmux.Server +---@field adopt fun(self:libtmux.Server):libtmux.Request> +---@field owned_session fun(self:libtmux.Server,options?:libtmux.NewSessionOptions): +--- libtmux.Request> +---@field with_session fun(self:libtmux.Server,options:libtmux.NewSessionOptions?, +--- body:fun(session:libtmux.Session,owner:libtmux.Owned):any): +--- libtmux.Request +---@field find_or_create_session fun(self:libtmux.Server,name:string, +--- options?:libtmux.NewSessionOptions):libtmux.Request> ---@field get_option fun(self:libtmux.Server,name:string,options?:libtmux.SettingGetOptions): --- libtmux.Request ---@field list_options fun(self:libtmux.Server,options?:libtmux.SettingListOptions): diff --git a/lua/libtmux/_internal/servers.lua b/lua/libtmux/_internal/servers.lua new file mode 100644 index 00000000..f4098036 --- /dev/null +++ b/lua/libtmux/_internal/servers.lua @@ -0,0 +1,653 @@ +local defaults = require("libtmux._internal.defaults") +local errors = require("libtmux._internal.error") +local endpoints = require("libtmux._internal.endpoint") +local lifecycle = require("libtmux._internal.lifecycle") +local process = require("libtmux._internal.process") +local server = require("libtmux._internal.server") +local M = {} + +local function failure(code, message, cause) + return errors.new(code, message, { operation = "servers", effect = "not_sent", cause = cause }) +end + +local function same(first, second) + return first + and second + and first.type == second.type + and first.dev == second.dev + and first.ino == second.ino +end + +local function prepare_directory(uv, endpoint) + if endpoint.root then + local root, cause = uv.fs_stat(endpoint.root) + if not root or root.type ~= "directory" then + return nil, + failure( + "invalid_endpoint", + "named socket root is not an accessible directory", + cause + ) + end + local directory = endpoint.root .. "/tmux-" .. string.format("%.0f", endpoint.uid) + local made, err = uv.fs_mkdir(directory, 448) + if not made and not tostring(err):match("^EEXIST") then + return nil, failure("filesystem_error", "cannot prepare named socket directory", err) + end + local stat = uv.fs_lstat(directory) + if + not stat + or stat.type ~= "directory" + or stat.uid ~= endpoint.uid + or stat.mode % 8 ~= 0 + then + return nil, + failure( + "invalid_endpoint", + "named socket directory needs current UID and no other-user permissions" + ) + end + end + local parent = endpoint.socket:match("^(.*)/[^/]+$") + local stat, cause = uv.fs_stat(parent == "" and "/" or parent) + if not stat or stat.type ~= "directory" then + return nil, failure("invalid_endpoint", "socket parent must already exist", cause) + end + return parent == "" and "/" or parent +end + +local function owned_process(runtime, endpoint, parent) + local uv = runtime._driver.uv + local directory, err = uv.fs_mkdtemp(parent .. "/libtmux-lua-start-XXXXXX") + if not directory then + return nil, failure("filesystem_error", "cannot allocate private server startup path", err) + end + local directory_stat = uv.fs_lstat(directory) + local state = + { directory = directory, private = directory .. "/s", listeners = {}, endpoint = endpoint } + local lease, cleanup + local function remove_paths() + if state.released then + return true + end + if not state.exited and state.child then + return nil, failure("cleanup_failed", "daemon exit is unproved; startup paths retained") + end + if state.child and state.exited and not state.socket_stat then + -- Cancellation may precede socket creation. The exact native child + -- has now exited, so inspect only its private, unpublished path in + -- the unchanged directory allocated for that child. + local directory_now = uv.fs_lstat(state.directory) + local late_socket = uv.fs_lstat(state.private) + if + same(directory_now, directory_stat) + and late_socket + and late_socket.type == "socket" + then + state.socket_stat = late_socket + end + end + -- The published alias is shared with other publishers. A pathname + -- check cannot make unlink atomic; leave that alias to its directory + -- owner, even when it still refers to our retired daemon. + for _, path in ipairs({ state.private }) do + local stat, cause = uv.fs_lstat(path) + if stat and same(stat, state.socket_stat) then + local removed, remove_error = uv.fs_unlink(path) + if not removed then + return nil, + failure("cleanup_failed", "cannot remove owned socket link", remove_error) + end + elseif not stat and not tostring(cause):match("^ENOENT") then + return nil, failure("cleanup_failed", "cannot inspect owned socket link", cause) + end + end + local stat, cause = uv.fs_lstat(state.directory) + if not stat and tostring(cause):match("^ENOENT") then + return true + end + if not same(stat, directory_stat) then + return nil, + failure("cleanup_failed", "startup directory identity changed; retaining path") + end + local removed, remove_error = uv.fs_rmdir(state.directory) + if not removed then + return nil, failure("cleanup_failed", "cannot remove startup directory", remove_error) + end + return true + end + local function finish() + if + not state.cleaning + or (state.child and not state.exited and not state.released and not state.expired) + then + return + end + if state.timer then + state.timer:stop() + state.timer:close() + state.timer = nil + end + local value, cause = remove_paths() + local listeners = state.listeners + state.listeners, state.cleaning = {}, false + local function deliver() + for _, done in ipairs(listeners) do + done(value and nil or cause) + end + end + if state.child and not state.exited and not state.released then + state.child:unref() + deliver() + elseif state.child and not state.handle_closed then + state.handle_closed = true + state.child:close(deliver) + else + deliver() + end + end + cleanup = function(done) + state.listeners[#state.listeners + 1] = done + if state.cleaning then + return + end + state.cleaning, state.expired = true, false + if not state.child or state.exited or state.released then + finish() + return + end + if not state.socket_stat then + local stat = uv.fs_lstat(state.private) + if stat and stat.type == "socket" then + state.socket_stat = stat + end + end + state.child:ref() + local sent, cause = state.child:kill("sigterm") + if not sent then + state.signal_error = cause + end + state.timer = uv.new_timer() + state.timer:start(100, 0, function() + if not state.exited then + state.child:kill("sigkill") + end + if state.timer then + state.timer:start(500, 0, function() + state.expired = true + finish() + end) + end + end) + end + lease, err = runtime:_resource(cleanup) + if not lease then + uv.fs_rmdir(directory) + return nil, err + end + state.lease = lease + state.child, state.pid = uv.spawn(endpoint.binary, { + args = { "-D", "-u", "-f", endpoint.config, "-S", state.private }, + env = endpoint.env, + stdio = { nil, nil, nil }, + }, function(code, signal) + state.exited, state.exit_code, state.exit_signal = true, code, signal + finish() + end) + if not state.child then + state.exited = true + lease:close() + return nil, failure("spawn_failed", "cannot start foreground tmux daemon", state.pid) + end + function state.retire() + return runtime:_request({ + bytes = 0, + operation = "server.retire", + timeout = 750, + start = function(settle, retire) + cleanup(function(cause) + settle(cause == nil and true or nil, cause) + retire() + end) + -- Retirement continues after waiter cancellation; the lease retains it. + return function() end + end, + }) + end + return state +end + +local function socket_ready(runtime, state) + return runtime:_request({ + bytes = 0, + operation = "server.start", + timeout = 750, + start = function(settle, retire) + local uv, finished = runtime._driver.uv, false + local timer = uv.new_timer() + local function finish(value, err) + if finished then + return + end + finished = true + timer:stop() + timer:close(function() + retire() + end) + settle(value, err) + end + timer:start(0, 5, function() + if state.exited then + finish( + nil, + failure("startup_failed", "foreground tmux exited before socket readiness") + ) + return + end + local stat, cause = uv.fs_lstat(state.private) + if stat and stat.type == "socket" then + state.socket_stat = stat + finish(true) + elseif stat or not tostring(cause):match("^ENOENT") then + finish( + nil, + failure("startup_failed", "private startup endpoint is not a socket", cause) + ) + end + end) + return function(err) + finish(nil, err) + end + end, + }) +end + +local function ready(runtime, state) + local deadline = runtime._driver.now() + 750 + return runtime:_operation(function(rt) + local available, err = socket_ready(rt, state):await() + if not available then + return nil, err + end + local endpoint = state.endpoint + local result + repeat + if state.exited then + return nil, failure("startup_failed", "foreground daemon exited before readiness") + end + result, err = process + .execute(rt, { + endpoint.binary, + "-N", + "-u", + "-S", + state.private, + "display-message", + "-p", + "#{pid}", + }, { + env = endpoint.env, + deadline = deadline, + max_output_bytes = 4096, + }) + :await() + if + result + and result.exit_code == 0 + and result.stderr == "" + and result.stdout == tostring(state.pid) .. "\n" + then + return true + end + -- A socket inode can appear before tmux starts accepting clients. + -- Each no-start probe yields through the native process adapter. + until rt._driver.now() >= deadline + return nil, failure("startup_failed", "daemon did not confirm its native child PID", err) + end, { operation = "server.ready", effect = "not_sent" }) +end + +function M.start(runtime, options, find, resolved) + local endpoint, validation_error + if resolved then + endpoint = options + else + endpoint, validation_error = defaults.resolve(runtime._driver.uv, options) + end + local holder = {} + local registered, registration_error = runtime:defer(function() + if holder.owner then + return holder.owner:close():await() + end + return true + end) + return runtime:_operation(function(rt) + if not registered then + return nil, registration_error + end + if not endpoint then + return nil, validation_error + end + local uv = rt._driver.uv + local parent, err = prepare_directory(uv, endpoint) + if not parent then + return nil, err + end + local existing, cause = uv.fs_lstat(endpoint.socket) + if existing then + if not find then + return nil, failure("already_exists", "owned_server requires an unused socket path") + end + local borrowed + borrowed, err = server.resolved(rt, endpoint):await() + if not borrowed then + return nil, err + end + return { value = borrowed, created = false } + elseif not tostring(cause):match("^ENOENT") then + return nil, failure("filesystem_error", "cannot inspect selected socket", cause) + end + local process_state, delivered + local deferred + deferred, err = rt:defer(function() + if process_state and not delivered then + return process_state.retire():await() + end + return true + end) + if not deferred then + return nil, err + end + process_state, err = owned_process(rt, endpoint, parent) + if not process_state then + return nil, err + end + local started + started, err = ready(rt, process_state):await() + if not started then + return nil, err + end + local linked, link_error = uv.fs_link(process_state.private, endpoint.socket) + if not linked then + if find and tostring(link_error):match("^EEXIST") then + local cleaned + cleaned, err = process_state.retire():await() + if not cleaned then + return nil, err + end + local borrowed + borrowed, err = server.resolved(rt, endpoint):await() + if not borrowed then + return nil, err + end + return { value = borrowed, created = false } + end + return nil, failure("publish_failed", "cannot claim selected socket path", link_error) + end + -- Only our allocated private route can authorize startup ownership. + -- The published alias may already point to another daemon. + local private_endpoint = {} + for key, value in pairs(endpoint) do + private_endpoint[key] = value + end + private_endpoint.socket, private_endpoint.pin_parent = process_state.private, parent + local connected + connected, err = server.resolved(rt, private_endpoint):await() + if not connected then + return nil, err + end + local owner + owner, err = connected:adopt():await() + if not owner then + return nil, err + end + if owner:receipt().pid ~= tostring(process_state.pid) then + owner:release() + return nil, + failure("stale_generation", "private socket does not identify the spawned daemon") + end + lifecycle.attach(owner, process_state.retire, function() + process_state.released = true + end) + holder.owner = lifecycle.transfer(owner) + delivered = true + if find then + return { value = connected, created = true, owner = holder.owner } + end + return holder.owner + end, { operation = find and "find_or_create_server" or "owned_server", effect = "not_sent" }) +end + +function M.scope(runtime, options, body) + local endpoint, err = defaults.resolve(runtime._driver.uv, options) + return runtime:_operation(function() + if not endpoint then + return nil, err + end + if type(body) ~= "function" then + return nil, failure("invalid_callback", "server scope requires a function") + end + local owner, cause = M.start(runtime, endpoint, false, true):await() + if not owner then + return nil, cause + end + return body(owner.value, owner) + end, { operation = "owned_scope", effect = "not_sent" }) +end + +function M.discover(runtime, options) + options = options or {} + local validation_error, copied, resolve_options = nil, {}, {} + if type(options) ~= "table" or getmetatable(options) ~= nil then + validation_error = failure("invalid_options", "discovery options must be a plain record") + else + local accepted = { + roots = true, + paths = true, + max_entries = true, + max_probes = true, + timeout = true, + binary = true, + client_env = true, + env = true, + } + for key, value in pairs(options) do + if not accepted[key] then + validation_error = failure("invalid_options", "unknown discovery option") + end + if key == "binary" or key == "client_env" or key == "env" then + resolve_options[key] = value + else + copied[key] = value + end + end + end + local endpoint, endpoint_error = defaults.resolve(runtime._driver.uv, resolve_options) + for key, default in pairs({ max_entries = 256, max_probes = 32, timeout = 2000 }) do + copied[key] = copied[key] == nil and default or copied[key] + if + type(copied[key]) ~= "number" + or copied[key] < 1 + or copied[key] > (key == "timeout" and 60000 or 4096) + or copied[key] % 1 ~= 0 + then + validation_error = + failure("invalid_options", "discovery limits must be positive bounded integers") + end + end + for _, key in ipairs({ "roots", "paths" }) do + if copied[key] ~= nil then + if type(copied[key]) ~= "table" or getmetatable(copied[key]) ~= nil then + validation_error = + failure("invalid_options", "discovery roots and paths must be dense sequences") + else + local list, count = {}, 0 + for index, value in pairs(copied[key]) do + count = count + 1 + if + type(index) ~= "number" + or index < 1 + or index % 1 ~= 0 + or type(value) ~= "string" + or value:sub(1, 1) ~= "/" + or #value > 4096 + or value:find("\000", 1, true) + then + validation_error = + failure("invalid_options", "discovery needs absolute bounded paths") + else + list[index] = value + end + end + if count > 32 or count ~= #list then + validation_error = failure( + "invalid_options", + "discovery accepts at most 32 dense roots or paths" + ) + end + copied[key] = list + end + end + end + if endpoint and copied.roots == nil then + local root = defaults.socket_root(endpoint.env) + if root:sub(1, 1) ~= "/" then + validation_error = failure("invalid_options", "discovery TMUX_TMPDIR must be absolute") + end + local suffix = "/tmux-" .. tostring(runtime._driver.uv.getuid()) + copied.roots = { root .. suffix } + if root ~= "/tmp" then + copied.roots[#copied.roots + 1] = "/tmp" .. suffix + end + end + return runtime:_operation(function(rt) + if validation_error then + return nil, validation_error + end + if not endpoint then + return nil, endpoint_error + end + local uv, result, candidates, seen, identities = + rt._driver.uv, + { servers = {}, diagnostics = {}, truncated = false, entries = 0, probes = 0 }, + {}, + {}, + {} + local deadline = rt._driver.now() + copied.timeout + local function diagnostic(path, code, cause) + result.diagnostics[#result.diagnostics + 1] = + { path = path, code = code, cause = cause } + end + local function candidate(path) + if not seen[path] then + seen[path] = true + candidates[#candidates + 1] = path + end + end + for _, path in ipairs(copied.paths or {}) do + candidate(path) + end + for _, root in ipairs(copied.roots or {}) do + local stat, cause = uv.fs_lstat(root) + if not stat or stat.type ~= "directory" or stat.uid ~= uv.getuid() then + diagnostic(root, "invalid_root", cause) + else + local scan, scan_error = uv.fs_opendir(root, nil, 16) + if not scan then + diagnostic(root, "scan_failed", scan_error) + else + local stop = false + while not stop do + local entries, read_error = uv.fs_readdir(scan) + if not entries then + if read_error then + diagnostic(root, "scan_failed", read_error) + end + break + end + for _, entry in ipairs(entries) do + if + result.entries >= copied.max_entries + or rt._driver.now() >= deadline + then + result.truncated, stop = true, true + break + end + result.entries = result.entries + 1 + if entry.type == "socket" or entry.type == "unknown" then + candidate(root .. "/" .. entry.name) + end + end + end + local closed, close_error = uv.fs_closedir(scan) + if not closed then + diagnostic(root, "scan_close_failed", close_error) + end + end + end + end + table.sort(candidates) + for _, path in ipairs(candidates) do + if result.probes >= copied.max_probes or rt._driver.now() >= deadline then + result.truncated = true + break + end + local stat, cause = uv.fs_lstat(path) + if not stat or stat.type ~= "socket" or stat.uid ~= uv.getuid() then + diagnostic(path, "invalid_socket", cause) + elseif identities[tostring(stat.dev) .. ":" .. tostring(stat.ino)] then + diagnostic(path, "duplicate_socket") + else + identities[tostring(stat.dev) .. ":" .. tostring(stat.ino)] = true + result.probes = result.probes + 1 + local probe = { + binary = endpoint.binary, + socket = path, + config = endpoint.config, + env = endpoint.env, + } + local bound, err = endpoints.bind(rt, probe):await() + if bound then + local evidence = bound:evidence() + result.servers[#result.servers + 1] = { + socket_path = path, + pid = evidence.pid, + started = evidence.started, + version = evidence.version, + } + local closed, close_error = bound:close():await() + if not closed then + diagnostic(path, "cleanup_failed", close_error) + end + else + diagnostic(path, "probe_failed", err) + end + end + end + return result + end, { operation = "discover_servers", effect = "not_sent" }) +end + +---@class libtmux.DiscoveryOptions +---@field roots? string[] Socket directories; defaults to captured TMUX_TMPDIR and /tmp UID roots. +---@field paths? string[] Additional exact paths, at most 32. +---@field max_entries? integer Defaults to 256. +---@field max_probes? integer Defaults to 32. +---@field timeout? integer Milliseconds; checked between bounded 750 ms probes. +---@field binary? string +---@field client_env? table +---@field env? string[] Complete child environment; excludes client_env. + +---@class libtmux.DiscoveredServer +---@field socket_path string +---@field pid string +---@field started string +---@field version string + +---@class libtmux.DiscoveryResult +---@field servers libtmux.DiscoveredServer[] +---@field diagnostics table[] Per-root and per-path failures, exclusions and duplicate sockets. +---@field entries integer +---@field probes integer +---@field truncated boolean + +return M diff --git a/lua/libtmux/runtime/luv.lua b/lua/libtmux/runtime/luv.lua index f7e177dd..dad3ed5d 100644 --- a/lua/libtmux/runtime/luv.lua +++ b/lua/libtmux/runtime/luv.lua @@ -100,8 +100,16 @@ end function M._result(root, rt) local value, err = root:result() local cleanup = rt:errors() - if not err and #cleanup > 0 then - return nil, errors.new("cleanup_failed", "runtime cleanup failed", { errors = cleanup }) + if #cleanup > 0 then + if err and err.code == "cleanup_failed" then + err.runtime_errors = cleanup + return nil, err + end + return nil, + errors.new("cleanup_failed", "runtime cleanup failed", { + cause = err, + errors = cleanup, + }) end return value, err end diff --git a/rockspecs/libtmux-0.1.0alpha2-1.rockspec b/rockspecs/libtmux-0.1.0alpha2-1.rockspec index ad842143..ae3e0f7b 100644 --- a/rockspecs/libtmux-0.1.0alpha2-1.rockspec +++ b/rockspecs/libtmux-0.1.0alpha2-1.rockspec @@ -26,6 +26,7 @@ build = { ["libtmux._internal.control"] = "lua/libtmux/_internal/control.lua", ["libtmux._internal.control_io"] = "lua/libtmux/_internal/control_io.lua", ["libtmux._internal.control_parser"] = "lua/libtmux/_internal/control_parser.lua", + ["libtmux._internal.defaults"] = "lua/libtmux/_internal/defaults.lua", ["libtmux._internal.domain"] = "lua/libtmux/_internal/domain.lua", ["libtmux._internal.endpoint"] = "lua/libtmux/_internal/endpoint.lua", ["libtmux._internal.entity"] = "lua/libtmux/_internal/entity.lua", @@ -36,6 +37,7 @@ build = { ["libtmux._internal.fields"] = "lua/libtmux/_internal/fields.lua", ["libtmux._internal.graph"] = "lua/libtmux/_internal/graph.lua", ["libtmux._internal.identity"] = "lua/libtmux/_internal/identity.lua", + ["libtmux._internal.lifecycle"] = "lua/libtmux/_internal/lifecycle.lua", ["libtmux._internal.live_query"] = "lua/libtmux/_internal/live_query.lua", ["libtmux._internal.metadata"] = "lua/libtmux/_internal/metadata.lua", ["libtmux._internal.observation"] = "lua/libtmux/_internal/observation.lua", @@ -49,6 +51,7 @@ build = { ["libtmux._internal.runtime"] = "lua/libtmux/_internal/runtime.lua", ["libtmux._internal.scope"] = "lua/libtmux/_internal/scope.lua", ["libtmux._internal.server"] = "lua/libtmux/_internal/server.lua", + ["libtmux._internal.servers"] = "lua/libtmux/_internal/servers.lua", ["libtmux._internal.settings"] = "lua/libtmux/_internal/settings.lua", ["libtmux._internal.text"] = "lua/libtmux/_internal/text.lua", ["libtmux._internal.topology"] = "lua/libtmux/_internal/topology.lua", diff --git a/rockspecs/libtmux-scm-1.rockspec b/rockspecs/libtmux-scm-1.rockspec index 4baf1064..297d0aab 100644 --- a/rockspecs/libtmux-scm-1.rockspec +++ b/rockspecs/libtmux-scm-1.rockspec @@ -35,6 +35,9 @@ build = { ["libtmux._internal.control"] = "lua/libtmux/_internal/control.lua", ["libtmux._internal.observation"] = "lua/libtmux/_internal/observation.lua", ["libtmux._internal.control_io"] = "lua/libtmux/_internal/control_io.lua", + ["libtmux._internal.defaults"] = "lua/libtmux/_internal/defaults.lua", + ["libtmux._internal.servers"] = "lua/libtmux/_internal/servers.lua", + ["libtmux._internal.lifecycle"] = "lua/libtmux/_internal/lifecycle.lua", ["libtmux._internal.endpoint"] = "lua/libtmux/_internal/endpoint.lua", ["libtmux._internal.server"] = "lua/libtmux/_internal/server.lua", ["libtmux._internal.batch"] = "lua/libtmux/_internal/batch.lua", diff --git a/tests/integration/acquisition.lua b/tests/integration/acquisition.lua new file mode 100644 index 00000000..9ddcaedd --- /dev/null +++ b/tests/integration/acquisition.lua @@ -0,0 +1,123 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local entities = require("libtmux._internal.entity") +local codec = require("libtmux._internal.codec") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local checks = 0 +local function check(value, message) + assert(value, message) + checks = checks + 1 +end +local value, err = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local server = must(runtime:connect():await()) + local wrap = entities.from_reference + local marker = { code = "wrap_failure", message = "injected wrapping failure" } + -- Deliberate fault injection; the original implementation is restored below. + ---@diagnostic disable-next-line: duplicate-set-field + entities.from_reference = function() + return nil, marker + end + local missing, wrap_error = + server:owned_session({ name = "wrapping", argv = { "/bin/cat" } }):await() + entities.from_reference = wrap + check(not missing and wrap_error == marker) + check(marker.owner and marker.owner.closed, "complete receipt must survive wrapping failure") + local listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check(not listing.stdout:find("wrapping", 1, true), "wrapping failure must roll back") + + local decode, pending, cancelled = codec.decode, nil, false + -- Deliberate fault injection; the original implementation is restored below. + ---@diagnostic disable-next-line: duplicate-set-field + codec.decode = function(text, count, options) + local rows, cause = decode(text, count, options) + if count == 7 and rows and rows[1] and rows[1][4] ~= "" and pending and not cancelled then + -- The pre-creation server receipt names the existing fixture. Cancel + -- only the receipt emitted by the newly created session. + if rows[1][4] ~= "$0" then + cancelled = true + pending:cancel("receipt delivered before cancellation") + end + end + return rows, cause + end + pending = server:owned_session({ name = "receipt-cancel", argv = { "/bin/cat" } }) + local accepted, cancellation = pending:await() + codec.decode = decode + check(not accepted and cancellation.code == "cancelled" and cancelled) + listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check( + not listing.stdout:find("receipt-cancel", 1, true), + "accepted cancelled receipt must roll back" + ) + + local options = { name = "copied-scope", argv = { "/bin/cat" } } + local scoped = server:with_session(options, function(session) + local snapshot = must(session:snapshot():await()) + check(snapshot.name == "copied-scope") + return true + end) + options.name, options.argv[1] = "changed-after-call", "/not-a-command" + must(scoped:await()) + options = { socket_path = root .. "/captured-server" } + local startup = runtime:with_server(options, function(owned) + check(uv.fs_lstat(root .. "/captured-server").type == "socket") + return owned:command({ "display-message", "-p", "captured" }):await() + end) + options.socket_path = root .. "/changed-after-call" + must(startup:await()) + check(uv.fs_lstat(root .. "/captured-server").type == "socket") + check(uv.fs_lstat(root .. "/changed-after-call") == nil) + + local first_request = runtime:find_or_create_server({ socket_path = root .. "/race" }) + local second_request = runtime:find_or_create_server({ socket_path = root .. "/race" }) + local first, second = must(first_request:await()), must(second_request:await()) + check(first.created ~= second.created, "atomic publication must choose exactly one owner") + local created, reused = first.created and first or second, first.created and second or first + check(created.owner and reused.owner == nil) + must(created.owner:close():await()) + + local released = must(runtime:owned_server({ socket_path = root .. "/adopt-server" }):await()) + local borrowed = must(released:release()) + local adopted = must(borrowed:adopt():await()) + must(adopted:close():await()) + check(adopted.closed, "a borrowed daemon can be explicitly adopted") + -- A released startup directory is now the caller's responsibility. This + -- harness owns the original root and observes exits before removing it. + + local unowned = + must(server:new_session({ name = "borrowed-survives", argv = { "/bin/cat" } }):await()) + local operation = server:with_session( + { name = "lookup-scope", argv = { "/bin/cat" } }, + function() + local result = must(server:find_or_create_session("borrowed-survives"):await()) + check(not result.created and not result.owner) + return true + end + ) + must(operation:await()) + check(must(unowned.session:snapshot():await()).name == "borrowed-survives") + must(must(unowned.session:adopt():await()):close():await()) + print("acquisition checks PASS " .. checks) + return true +end) +if err then + local function describe(failure) + io.stderr:write(tostring(failure.code), ": ", tostring(failure), "\n") + if type(failure.cause) == "table" then + describe(failure.cause) + end + for _, child in ipairs(failure.errors or {}) do + describe(child) + end + end + describe(err) +end +assert(value, tostring(err)) diff --git a/tests/integration/discovery_environment.lua b/tests/integration/discovery_environment.lua new file mode 100644 index 00000000..de0949da --- /dev/null +++ b/tests/integration/discovery_environment.lua @@ -0,0 +1,52 @@ +local adapter = require("libtmux.runtime.luv") +local defaults = require("libtmux._internal.defaults") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local result, failure = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local binary = assert(os.getenv("LIBTMUX_TEST_BINARY")) + local cases = { + { root .. "/first", root .. "/second", root .. "/first" }, + { "", root .. "/second", "/tmp" }, + { root .. "/first", "", root .. "/first" }, + } + for _, case in ipairs(cases) do + for _, path_selector in ipairs({ false, true }) do + local env = { "TMUX_TMPDIR=" .. case[1], "TMUX_TMPDIR=" .. case[2] } + if path_selector then + env[#env + 1] = "LIBTMUX_SOCKET_PATH=" .. root .. "/socket" + end + local options = { binary = binary, env = env } + local selected = must(defaults.resolve(uv, { + binary = binary, + socket_name = "default", + env = env, + })) + local expected = case[3] .. "/tmux-" .. uv.getuid() + assert(selected.socket == expected .. "/default") + local inspected, lstat = {}, uv.fs_lstat + ---@diagnostic disable-next-line: duplicate-set-field + uv.fs_lstat = function(path, callback) + assert(not callback, "only synchronous root admission is expected") + inspected[#inspected + 1] = path + return nil, "ENOENT: test blocks root enumeration" + end + local discovery, err = runtime:discover_servers(options):await() + uv.fs_lstat = lstat + must(discovery, err) + assert(inspected[1] == expected, "discovery must share connection/getenv precedence") + assert(#inspected == (case[3] == "/tmp" and 1 or 2)) + print("first entry [" .. case[1] .. "] selects " .. expected) + end + end + print("discovery first/empty duplicate environment entries PASS 6 cases") + return true +end) +assert(result, tostring(failure)) diff --git a/tests/integration/legacy_environment.lua b/tests/integration/legacy_environment.lua new file mode 100644 index 00000000..9f2e1a70 --- /dev/null +++ b/tests/integration/legacy_environment.lua @@ -0,0 +1,55 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local value, err = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local socket = os.getenv("LIBTMUX_SOCKET_PATH") + or root .. "/tmux-" .. uv.getuid() .. "/" .. assert(os.getenv("LIBTMUX_SOCKET_NAME")) + local binary = assert(os.getenv("LIBTMUX_TEST_BINARY")) + local spawn, expected, observed = uv.spawn, "", 0 + -- The additive ConnectOptions.env supplies each native child's environment. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(program, options, callback) + assert(options.env and table.concat(options.env, "\n") == expected) + observed = observed + 1 + return spawn(program, options, callback) + end + local empty = must(runtime:connect({ binary = binary, socket_path = socket, env = {} }):await()) + assert( + must(empty:command({ "display-message", "-p", "empty env" }):await()).stdout + == "empty env\n" + ) + must(empty:close():await()) + local options = { + binary = binary, + socket_path = socket, + env = { "COMPAT=before", "TMUX=ignored", "TMUX_PANE=%99", "KEEP=value" }, + } + expected = "COMPAT=before\nKEEP=value" + local request = runtime:connect(options) + options.env[1] = "COMPAT=after" + local full = must(request:await()) + assert( + must(full:command({ "display-message", "-p", "full env" }):await()).stdout == "full env\n" + ) + must(full:close():await()) + expected = "" + local owned = must( + runtime + :owned_server({ binary = binary, socket_path = root .. "/legacy-start", env = {} }) + :await() + ) + must(owned:close():await()) + uv.spawn = spawn + assert(observed > 0 and uv.os_getenv("COMPAT") == nil) + print("ConnectOptions.env empty/full environment capture and startup PASS") + return true +end) +assert(value, tostring(err)) diff --git a/tests/integration/lifecycle.lua b/tests/integration/lifecycle.lua new file mode 100644 index 00000000..60e8bf1d --- /dev/null +++ b/tests/integration/lifecycle.lua @@ -0,0 +1,92 @@ +local host = rawget(_G, "vim") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = host and (host.uv or host.loop) or require("luv") +local adapter = require(host and "libtmux.runtime.nvim" or "libtmux.runtime.luv") +local mode = assert(os.getenv("LIBTMUX_LIFECYCLE_MODE")) + +local function must(value, err) + if err then + error(err, 0) + end + return value +end + +local launched, cleaned = 0, false +local spawn = uv.spawn +local function entries(sequence) + local result = {} + for _, entry in ipairs(sequence) do + local key, value = entry:match("^([^=]+)=(.*)$") + result[key] = value + end + return result +end + +local function work(runtime) + local request = runtime:connect() + must(uv.os_setenv("LIBTMUX_SOCKET_PATH", "/invalid-after-capture/socket")) + must(uv.os_setenv("LIBTMUX_SOCKET_NAME", "invalid/after/capture")) + must(uv.os_setenv("TMUX_TMPDIR", "/invalid-after-capture/root")) + must(uv.os_setenv("LIBTMUX_CLIENT_MARKER", "after")) + must(uv.os_setenv("PATH", "/invalid-after-capture/path")) + uv.spawn = function(binary, spec, callback) + local env = entries(assert(spec.env, "client inherited the live host environment")) + assert(env.LIBTMUX_CLIENT_MARKER == "before") + assert(not env.TMUX and not env.TMUX_PANE) + assert(env.PATH ~= "/invalid-after-capture/path") + launched = launched + 1 + return spawn(binary, spec, callback) + end + local server = must(request:await()) + local created = + must(server:new_session({ name = "captured-example", argv = { "/bin/cat" } }):await()) + must(runtime:defer(function() + must(created.session:kill():await()) + cleaned = true + end)) + must(server:command({ "display-message", "-p", "captured" }):await()) + local observer = must(server:observe(created.session):await()) + must(observer:close():await()) + if mode == "body" then + error("injected lifecycle body error", 0) + elseif mode == "cancel" then + local timer = uv.new_timer() + timer:start(0, 0, function() + timer:close() + if host then + host.schedule(function() + runtime:close("injected lifecycle cancellation") + end) + else + runtime:close("injected lifecycle cancellation") + end + end) + server:command({ "wait-for", "never-signalled" }):await() + end + return true +end + +local function finish(value, err) + uv.spawn = spawn + assert(cleaned, "deferred session cleanup did not run") + assert(launched >= 6, "binding, commands and observation were not exercised") + if mode == "normal" then + must(value, err) + else + assert(err and (err.code == "task_error" or err.code == "cancelled"), tostring(err)) + end + io.stdout:write("captured lifecycle " .. mode .. " PASS\n") +end + +if host then + adapter.start(work, function(value, err) + local ok, failure = pcall(finish, value, err) + if not ok then + io.stderr:write(tostring(failure), "\n") + end + host.cmd(ok and "qa!" or "cquit 1") + end) +else + finish(adapter.run(work)) +end diff --git a/tests/integration/ownership.lua b/tests/integration/ownership.lua new file mode 100644 index 00000000..aa91bfe8 --- /dev/null +++ b/tests/integration/ownership.lua @@ -0,0 +1,40 @@ +local adapter = require("libtmux.runtime.luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local value, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + local owner = must(server:owned_session({ name = "owned", argv = { "/bin/cat" } }):await()) + local session = owner.value + assert(must(session:snapshot():await()).name == "owned") + must(session:rename("renamed-owned"):await()) + local found = must(server:find_or_create_session("renamed-owned"):await()) + assert(not found.created and found.owner == nil) + local window = must(session:owned_window({ name = "window", argv = { "/bin/cat" } }):await()) + local window_snapshot = must(window.value:snapshot():await()) + local pane + -- Obtain the pane from the same snapshot used to bind it. + local snapshot = must(server:snapshot():await()) + for _, record in ipairs(snapshot.panes) do + if record.window_id == window_snapshot.id then + pane = must(server:handle(snapshot, record)) + end + end + local split = must(pane:owned_pane({ argv = { "/bin/cat" } }):await()) + must(split:close():await()) + must(split:close():await()) + local first = must(window.value:find_or_create_pane("work", { argv = { "/bin/cat" } }):await()) + assert(first.created and first.owner) + local second = must(window.value:find_or_create_pane("work"):await()) + assert(not second.created and not second.owner) + must(first.owner:close():await()) + must(window:close():await()) + must(owner:close():await()) + assert(owner.closed) + print("ownership smoke PASS") + return true +end) +assert(value, tostring(err)) diff --git a/tests/integration/ownership_edges.lua b/tests/integration/ownership_edges.lua new file mode 100644 index 00000000..3ee2a34d --- /dev/null +++ b/tests/integration/ownership_edges.lua @@ -0,0 +1,164 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local checks = 0 +local function check(value, message) + assert(value, message) + checks = checks + 1 +end +local function cmd(server, words) + return must(server:command(words):await()) +end +local value, err = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local server = must(runtime:connect():await()) + local raw = must(server:new_session({ name = "adopted", argv = { "/bin/cat" } }):await()) + local session_owner = must(raw.session:adopt():await()) + local child = + must(raw.session:new_window({ name = "adopt-window", argv = { "/bin/cat" } }):await()) + local window_owner = must(child.window:adopt():await()) + local split = must(child.pane:split({ argv = { "/bin/cat" } }):await()) + local pane_owner = must(split.pane:adopt():await()) + cmd( + server, + { "join-pane", "-d", "-s", split.pane:reference().id, "-t", raw.pane:reference().id } + ) + must(pane_owner:close():await()) + check(pane_owner.closed, "moved pane closes by ID") + local other = + must(server:owned_session({ name = "destination", argv = { "/bin/cat" } }):await()) + cmd(server, { + "move-window", + "-s", + child.window:reference().id, + "-t", + other.value:reference().id .. ":", + }) + must(window_owner:close():await()) + check(window_owner.closed, "moved window closes by ID") + must(raw.session:rename("adopt-renamed"):await()) + must(session_owner:close():await()) + check(session_owner.closed, "renamed session closes by ID") + + local one = must(other.value:find_or_create_window("same", { argv = { "/bin/cat" } }):await()) + local two = must(other.value:find_or_create_window("same"):await()) + check(one.created and not two.created and not two.owner) + local duplicate = + must(other.value:owned_window({ name = "same", argv = { "/bin/cat" } }):await()) + local ambiguous, ambiguity = other.value:find_or_create_window("same"):await() + check(not ambiguous and ambiguity.code == "ambiguous") + must(duplicate:close():await()) + must(one.owner:close():await()) + must(other:close():await()) + + local released = + must(server:owned_session({ name = "released", argv = { "/bin/cat" } }):await()) + local borrowed = must(released:release()) + must(released:close():await()) + check(must(borrowed:snapshot():await()).name == "released") + must(must(borrowed:adopt():await()):close():await()) + + local old = must(runtime:owned_server({ socket_path = root .. "/replace" }):await()) + must(uv.fs_rename(root .. "/replace", root .. "/original-link")) + local replacement = must(runtime:owned_server({ socket_path = root .. "/replace" }):await()) + local closed = must(old:close():await()) + check(closed and old.closed, "the original foreground child retires through its own handle") + check( + cmd(replacement.value, { "display-message", "-p", "replacement survives" }).stdout + == "replacement survives\n" + ) + local old_receipt, new_receipt = old:receipt(), replacement:receipt() + local collision = "#{&&:#{==:#{pid}," + .. new_receipt.pid + .. "},#{&&:#{==:#{start_time}," + .. new_receipt.started + .. "},#{==:#{@libtmux_owner_generation}," + .. old_receipt.token + .. "}}}" + local guarded = cmd( + replacement.value, + { "if-shell", "-F", collision, "kill-server", "display-message -p token-refused" } + ) + check(guarded.stdout == "token-refused\n", "token defeats simulated PID/start collision") + must(replacement:close():await()) + must(uv.fs_unlink(root .. "/original-link")) + check(must(old:close():await()), "repeat original-child cleanup is harmless") + + local fresh = + must(runtime:owned_server({ socket_path = root .. "/retry-path-cleanup" }):await()) + local rmdir, denied = uv.fs_rmdir, false + uv.fs_rmdir = function(path, callback) + if path:find("libtmux-lua-start-", 1, true) and not denied then + denied = true + return nil, "EACCES: injected" + end + return rmdir(path, callback) + end + local removed, remove_error = fresh:close():await() + uv.fs_rmdir = rmdir + check(not removed and remove_error and not fresh.closed) + must(fresh:close():await()) + check(fresh.closed, "local directory cleanup can be retried after daemon exit") + + local bad, bad_error = runtime + :owned_server({ + socket_name = "invalid", + client_env = { TMUX_TMPDIR = root .. "/missing/.." }, + }) + :await() + check(not bad and bad_error and bad_error.code == "invalid_endpoint") + must(uv.fs_mkdir(root .. "/branch", 448)) + must(uv.fs_mkdir(root .. "/branch/inner", 448)) + must(uv.fs_symlink(root .. "/branch/inner", root .. "/link")) + local traversed = must(runtime + :owned_server({ + socket_name = "traversed", + client_env = { TMUX_TMPDIR = root .. "/link/.." }, + }) + :await()) + check(uv.fs_stat(root .. "/branch/tmux-" .. uv.getuid() .. "/traversed").type == "socket") + must(traversed:close():await()) + + local stale_socket = uv.new_pipe(false) + must(stale_socket:bind(root .. "/stale")) + must(runtime:defer(function() + if not stale_socket:is_closing() then + stale_socket:close() + end + end)) + local discovered = + must(runtime:discover_servers({ roots = { root }, max_entries = 128 }):await()) + local failed_probe = false + for _, diagnostic in ipairs(discovered.diagnostics) do + if diagnostic.path == root .. "/stale" and diagnostic.code == "probe_failed" then + failed_probe = true + end + end + check(failed_probe, "stale sockets report failed no-start probes") + stale_socket:close() + local truncated = must( + runtime:discover_servers({ roots = { root }, max_entries = 1, max_probes = 1 }):await() + ) + check(truncated.truncated and truncated.entries == 1) + local occupied, occupied_error = runtime:owned_server():await() + check(not occupied and occupied_error and occupied_error.code == "already_exists") + print("ownership edge checks PASS " .. checks) + return true +end) +if not value and type(err) == "table" then + io.stderr:write("code: ", tostring(err.code), "\n") + if err.cause then + io.stderr:write("cause: ", tostring(err.cause), "\n") + end + for _, failure in ipairs(err.errors or {}) do + io.stderr:write("cleanup: ", tostring(failure), "\n") + end +end +assert(value, tostring(err)) diff --git a/tests/integration/ownership_failures.lua b/tests/integration/ownership_failures.lua new file mode 100644 index 00000000..aef5db49 --- /dev/null +++ b/tests/integration/ownership_failures.lua @@ -0,0 +1,158 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local checks = 0 +local function check(value, message) + assert(value, message) + checks = checks + 1 +end +local function has(spec, fragment) + for _, argument in ipairs(spec.args) do + if argument:find(fragment, 1, true) then + return true + end + end + return false +end + +local value, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + local body = { code = "body_failure", message = "body marker" } + local scoped, scope_error = server + :with_session({ name = "body-failure", argv = { "/bin/cat" } }, function() + error(body, 0) + end) + :await() + check(scoped == nil and scope_error == body, "body identity must survive successful cleanup") + local listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check(not listing.stdout:find("body-failure", 1, true)) + + local spawn = uv.spawn + local owner = must(server:owned_session({ name = "retry", argv = { "/bin/cat" } }):await()) + -- Deliberate fault injection; the original implementation is restored below. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, spec, callback) + if has(spec, "kill-session") then + return nil, "injected destruction failure" + end + return spawn(binary, spec, callback) + end + local cleaned, cleanup_error = owner:close():await() + uv.spawn = spawn + check( + not cleaned and cleanup_error and not owner.closed and owner.cleanup_error == cleanup_error + ) + must(owner:close():await()) + check(owner.closed) + + local survivor + -- Deliberate fault injection; the original implementation is restored below. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, spec, callback) + if has(spec, "kill-session") then + return nil, "injected cleanup failure" + end + return spawn(binary, spec, callback) + end + local combined, combined_error = server + :with_session({ name = "both-fail", argv = { "/bin/cat" } }, function(_, accepted) + survivor = accepted + error(body, 0) + end) + :await() + uv.spawn = spawn + check(combined == nil and combined_error.code == "cleanup_failed") + check(combined_error.cause == body and #combined_error.errors == 1) + must(survivor:close():await()) + + local rejected = false + -- Deliberate fault injection; the original implementation is restored below. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, spec, callback) + if has(spec, "new-session") and has(spec, "rollback") then + return spawn(binary, spec, function(_, signal) + rejected = true + callback(1, signal) + end) + end + return spawn(binary, spec, callback) + end + local created, creation_error = + server:owned_session({ name = "rollback", argv = { "/bin/cat" } }):await() + uv.spawn = spawn + check(not created and creation_error and rejected, "creation transport failure must be visible") + listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check(not listing.stdout:find("rollback", 1, true), "complete receipt must roll back creation") + + local cancelling + cancelling = server:with_session({ name = "cancelled-scope", argv = { "/bin/cat" } }, function() + local timer = uv.new_timer() + timer:start(0, 0, function() + timer:close() + cancelling:cancel("cancel marker") + end) + return server:command({ "wait-for", "never-released" }):await() + end) + local cancelled, cancel_error = cancelling:await() + check(cancelled == nil and cancel_error.code == "cancelled") + listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check(not listing.stdout:find("cancelled-scope", 1, true)) + + owner = must(server:owned_session({ name = "token-change", argv = { "/bin/cat" } }):await()) + local receipt = owner:receipt() + must( + server + :command({ "set-option", "-s", "@libtmux_owner_generation", string.rep("b", 32) }) + :await() + ) + cleaned, cleanup_error = owner:close():await() + check(not cleaned and cleanup_error.code == "stale_generation") + check(must(owner.value:snapshot():await()).name == "token-change") + must(server:command({ "set-option", "-s", "@libtmux_owner_generation", receipt.token }):await()) + must(owner:close():await()) + + must(server:command({ "set-option", "-s", "@libtmux_owner_generation", "bad" }):await()) + local malformed, malformed_error = + server:owned_session({ name = "malformed-token", argv = { "/bin/cat" } }):await() + check(not malformed and malformed_error.code == "invalid_receipt") + must(server:command({ "set-option", "-s", "@libtmux_owner_generation", receipt.token }):await()) + listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check( + not listing.stdout:find("malformed-token", 1, true), + "malformed token must fail before creation" + ) + + local borrowed = must(runtime:connect():await()) + local retained = + must(borrowed:owned_session({ name = "closed-client", argv = { "/bin/cat" } }):await()) + must(borrowed:close():await()) + must(retained:close():await()) + check(retained.closed, "owner pin must outlive borrowed client close") + + local first_request = server:find_or_create_session("concurrent", { argv = { "/bin/cat" } }) + local second_request = server:find_or_create_session("concurrent", { argv = { "/bin/cat" } }) + local first, second = must(first_request:await()), must(second_request:await()) + check(first.created and not second.created) + check(first.value:reference().id == second.value:reference().id) + must(first.owner:close():await()) + print("ownership failure checks PASS " .. checks) + return true +end) +if not value and type(err) == "table" and checks ~= 17 then + io.stderr:write("code: ", tostring(err.code), "\n") + if err.cause then + io.stderr:write("cause: ", tostring(err.cause), "\n") + end + for _, failure in ipairs(err.errors or {}) do + io.stderr:write("cleanup: ", tostring(failure), "\n") + end +end +assert(checks == 17 and not value and err and err.code == "cleanup_failed", tostring(err)) +assert(#err.errors == 1, "the runtime retains the handled deferred-cleanup diagnostic") diff --git a/tests/integration/ownership_nvim.lua b/tests/integration/ownership_nvim.lua new file mode 100644 index 00000000..43639ce5 --- /dev/null +++ b/tests/integration/ownership_nvim.lua @@ -0,0 +1,48 @@ +local host = assert(rawget(_G, "vim")) +local adapter = require("libtmux.runtime.nvim") +local uv = host.uv or host.loop +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local marker = { code = "body_failure", message = "Neovim body failure" } +local watchdog = uv.new_timer() +watchdog:start(2000, 0, function() + host.schedule(function() + host.cmd("cquit 1") + end) +end) +adapter.start(function(runtime) + local server = must(runtime:connect():await()) + local value, err = server + :with_session({ name = "nvim-body", argv = { "/bin/cat" } }, function() + error(marker, 0) + end) + :await() + assert(not value and err == marker) + local request + request = server:with_session({ name = "nvim-cancel", argv = { "/bin/cat" } }, function() + host.schedule(function() + request:cancel("host cancellation") + end) + return server:command({ "wait-for", "nvim-never" }):await() + end) + value, err = request:await() + assert(not value and err.code == "cancelled") + local listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + assert(listing.stdout == "fixture\n") + return true +end, function(value, err) + watchdog:stop() + watchdog:close() + assert(not host.in_fast_event()) + if not value then + io.stderr:write(tostring(err), "\n") + host.cmd("cquit 1") + return + end + print("Neovim ownership body and cancellation PASS") + host.cmd("qa!") +end) diff --git a/tests/integration/receipt_failures.lua b/tests/integration/receipt_failures.lua new file mode 100644 index 00000000..de89dd6e --- /dev/null +++ b/tests/integration/receipt_failures.lua @@ -0,0 +1,70 @@ +local adapter = require("libtmux.runtime.luv") +local entities = require("libtmux._internal.entity") +local codec = require("libtmux._internal.codec") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local checks = 0 +local function check(value, message) + assert(value, message) + checks = checks + 1 +end +local value, err = adapter.run(function(runtime) + local server = must(runtime:connect():await()) + local wrap, spawn = entities.from_reference, uv.spawn + local marker = { code = "wrap_failure", message = "receipt retained through wrapping failure" } + -- Deliberate fault injection; restored before recovery. + ---@diagnostic disable-next-line: duplicate-set-field + entities.from_reference = function() + return nil, marker + end + -- Deliberate fault injection; restored before recovery. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, options, callback) + for _, argument in ipairs(options.args) do + if argument:find("kill-session", 1, true) then + return nil, "rollback transport fault" + end + end + return spawn(binary, options, callback) + end + local accepted, failure = + server:owned_session({ name = "recoverable", argv = { "/bin/cat" } }):await() + entities.from_reference, uv.spawn = wrap, spawn + check(not accepted and failure.code == "cleanup_failed") + check(failure.cause == marker and marker.owner and not marker.owner.closed) + check(failure.errors[1].code == "rollback_failed" and failure.errors[1].owner == marker.owner) + must(marker.owner:close():await()) + check(marker.owner.closed, "complete receipt must retain a retryable recovery owner") + + local decode = codec.decode + -- Simulate a truncated native receipt only after the creation command ran. + ---@diagnostic disable-next-line: duplicate-set-field + codec.decode = function(text, count, options) + local rows, cause = decode(text, count, options) + if count == 7 and rows and rows[1] and rows[1][4] ~= "$0" then + return nil, { code = "truncated", message = "injected lost creation receipt" } + end + return rows, cause + end + accepted, failure = + server:owned_session({ name = "unknown-receipt", argv = { "/bin/cat" } }):await() + codec.decode = decode + check(not accepted and failure.code == "cleanup_failed") + check(failure.cause.code == "invalid_receipt" and failure.errors[1].code == "creation_unknown") + local listing = must(server:command({ "list-sessions", "-F", "#{session_name}" }):await()) + check( + listing.stdout:find("unknown-receipt", 1, true), + "unknown receipt must not guess a target" + ) + print("receipt failure checks PASS " .. checks) + return true +end) +assert(checks == 7 and not value and err and err.code == "cleanup_failed", tostring(err)) +assert(#err.errors == 2, "both deferred rollback diagnostics must survive") diff --git a/tests/integration/replacement_cleanup.lua b/tests/integration/replacement_cleanup.lua new file mode 100644 index 00000000..5af2aa3b --- /dev/null +++ b/tests/integration/replacement_cleanup.lua @@ -0,0 +1,140 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local servers = require("libtmux._internal.server") +local errors = require("libtmux._internal.error") + +local function must(value, err) + if err then + error(err, 0) + end + return value +end + +local function scenario(runtime, root, label, rollback) + local published, other = root .. "/" .. label, root .. "/" .. label .. "-other" + local replacement = must(runtime:owned_server({ socket_path = other }):await()) + local replacement_stat = must(uv.fs_lstat(other)) + local spawn, lstat, unlink, link, resolved = + uv.spawn, uv.fs_lstat, uv.fs_unlink, uv.fs_link, servers.resolved + local private, original_pid, original_stat, retired, injected, boundary + local public_unlinks, bind_failures = 0, 0 + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, options, callback) + local foreground = false + for index, arg in ipairs(options.args) do + if arg == "-D" then + foreground = true + end + if foreground and arg == "-S" then + private = options.args[index + 1] + end + end + if foreground then + local child, pid = spawn(binary, options, function(code, signal) + retired = true + callback(code, signal) + end) + original_pid = pid + return child, pid + end + return spawn(binary, options, callback) + end + ---@diagnostic disable-next-line: duplicate-set-field + uv.fs_link = function(from, to, callback) + local ok, err = link(from, to, callback) + if ok and to == published then + original_stat = must(lstat(to)) + end + return ok, err + end + ---@diagnostic disable-next-line: duplicate-set-field + uv.fs_lstat = function(path, callback) + local stat, err = lstat(path, callback) + if retired and not callback and not injected and (path == published or path == private) then + assert(not callback and original_stat) + -- Return the observed inode after a concurrent publisher replaces it. + -- If cleanup no longer inspects the public alias, interleave at its + -- private-path check instead and require zero public unlink attempts. + must(unlink(published)) + must(link(other, published)) + local installed = must(lstat(published)) + assert(installed.ino == replacement_stat.ino and installed.dev == replacement_stat.dev) + injected, boundary = + true, path == published and "public lstat/unlink" or "private cleanup" + end + return stat, err + end + ---@diagnostic disable-next-line: duplicate-set-field + uv.fs_unlink = function(path, callback) + if path == published then + public_unlinks = public_unlinks + 1 + end + return unlink(path, callback) + end + if rollback then + ---@diagnostic disable-next-line: duplicate-set-field + servers.resolved = function(rt, endpoint) + if endpoint.socket == published or endpoint.socket == private then + bind_failures = bind_failures + 1 + assert(original_stat, "failure must follow publication") + return rt:_operation(function() + return nil, errors.new("injected_bind", "fail after publication") + end) + end + return resolved(rt, endpoint) + end + end + local owner, failure = runtime:owned_server({ socket_path = published }):await() + local closed, close_error + if owner then + closed, close_error = owner:close():await() + end + uv.spawn, uv.fs_lstat, uv.fs_unlink, uv.fs_link, servers.resolved = + spawn, lstat, unlink, link, resolved + local current = lstat(published) + local public = runtime:connect({ socket_path = published }):await() + local response = public and public:command({ "display-message", "-p", "#{pid}" }):await() + local reachable = response and response.stdout == replacement:receipt().pid .. "\n" + print( + label + .. ": old PID " + .. tostring(original_pid) + .. ", replacement PID " + .. replacement:receipt().pid + ) + print(label .. ": boundary " .. tostring(boundary) .. ", public unlinks " .. public_unlinks) + print(label .. ": replacement public endpoint reachable " .. tostring(reachable == true)) + must(replacement:close():await()) + if rollback then + assert(not owner and failure.code == "injected_bind" and bind_failures == 1) + else + must(closed, close_error) + end + assert(retired and injected, "probe must retire original child and publish replacement") + assert( + current and current.ino == replacement_stat.ino and current.dev == replacement_stat.dev, + "cleanup removed the concurrent replacement endpoint" + ) + assert(reachable, "replacement must answer through the published endpoint") + assert(public_unlinks == 0, "cleanup must not unlink the shared publication") + assert(lstat(private) == nil, "original private startup path must retire") + assert(lstat(private:match("^(.*)/s$")) == nil, "original startup directory must retire") +end + +local result, failure = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + -- Run rollback first when requested so both paths fail on the old source. + local order = os.getenv("REPLACEMENT_ORDER") or "normal" + if order == "rollback" then + scenario(runtime, root, "rollback", true) + scenario(runtime, root, "normal", false) + else + scenario(runtime, root, "normal", false) + scenario(runtime, root, "rollback", true) + end + print("replacement cleanup normal + startup rollback PASS") + return true +end) +assert(result, tostring(failure)) diff --git a/tests/integration/server_lifecycle.lua b/tests/integration/server_lifecycle.lua new file mode 100644 index 00000000..6cb09807 --- /dev/null +++ b/tests/integration/server_lifecycle.lua @@ -0,0 +1,61 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local value, err = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local first = must(runtime:find_or_create_server({ socket_path = root .. "/fresh" }):await()) + assert(first.created and first.owner) + local second = must(runtime:find_or_create_server({ socket_path = root .. "/fresh" }):await()) + assert(not second.created and second.owner == nil) + local found = + must(first.value:find_or_create_session("session", { argv = { "/bin/cat" } }):await()) + assert(found.created) + local discovery = + must(runtime:discover_servers({ roots = { root }, paths = { root .. "/missing" } }):await()) + assert(#discovery.servers == 2, "expected fixture and newly created server") + assert(#discovery.diagnostics >= 1) + must(found.owner:close():await()) + must(first.owner:close():await()) + local stale = assert(uv.fs_lstat(root .. "/fresh")) + assert(stale.type == "socket", "the published alias remains after daemon exit") + local absent, failure = + runtime:find_or_create_server({ socket_path = root .. "/fresh" }):await() + assert(not absent and failure, "a stale publication must not start a replacement") + local retained = assert(uv.fs_lstat(root .. "/fresh")) + assert(retained.dev == stale.dev and retained.ino == stale.ino) + absent, failure = runtime:owned_server({ socket_path = root .. "/fresh" }):await() + assert(not absent and failure and failure.code == "already_exists") + -- This fixture owns the directory namespace and its old daemon has exited. + -- It can retire its stale publication before a new server uses that path. + must(uv.fs_unlink(root .. "/fresh")) + local restarted = + must(runtime:find_or_create_server({ socket_path = root .. "/fresh" }):await()) + assert(restarted.created and restarted.owner) + must(restarted.owner:close():await()) + local named = must(runtime + :owned_server({ + socket_name = "fresh-named", + client_env = { LIBTMUX_SOCKET_PATH = false, TMUX_TMPDIR = root }, + }) + :await()) + must(named:close():await()) + print("server lifecycle smoke PASS") + return true +end) +if not value and type(err) == "table" then + io.stderr:write("code: ", tostring(err.code), "\n") + if err.cause then + io.stderr:write("cause: ", tostring(err.cause), "\n") + end + for _, failure in ipairs(err.errors or {}) do + io.stderr:write("cleanup: ", tostring(failure), "\n") + end +end +assert(value, tostring(err)) diff --git a/tests/integration/startup_failures.lua b/tests/integration/startup_failures.lua new file mode 100644 index 00000000..70d94623 --- /dev/null +++ b/tests/integration/startup_failures.lua @@ -0,0 +1,94 @@ +local adapter = require("libtmux.runtime.luv") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local function contains(options, text) + for _, value in ipairs(options.args) do + if value == text then + return true + end + end + return false +end +local value, err = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + local spawn, denied = uv.spawn, 0 + -- A daemon socket can exist before it accepts its first no-start client. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, options, callback) + if not contains(options, "-D") and contains(options, "#{pid}") and denied == 0 then + denied = denied + 1 + return nil, "injected not-yet-ready listener" + end + return spawn(binary, options, callback) + end + local owner = must(runtime:owned_server({ socket_path = root .. "/readiness" }):await()) + uv.spawn = spawn + assert(denied == 1 and owner:receipt().pid) + must(owner:close():await()) + + -- Spawn failure must not publish a socket or strand its allocated directory. + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, options, callback) + if contains(options, "-D") then + return nil, "injected foreground spawn failure" + end + return spawn(binary, options, callback) + end + local absent, failure = runtime:owned_server({ socket_path = root .. "/spawn-fails" }):await() + uv.spawn = spawn + assert(not absent and failure and failure.code == "spawn_failed") + assert(uv.fs_lstat(root .. "/spawn-fails") == nil) + + local pending, scheduled + ---@diagnostic disable-next-line: duplicate-set-field + uv.spawn = function(binary, options, callback) + local child, pid = spawn(binary, options, callback) + if child and contains(options, "-D") and not scheduled then + scheduled = true + local timer = uv.new_timer() + timer:start(0, 0, function() + timer:close() + pending:cancel("cancel startup after accepting native child") + end) + end + return child, pid + end + pending = runtime:owned_server({ socket_path = root .. "/cancel-start" }) + absent, failure = pending:await() + uv.spawn = spawn + assert(not absent and failure and failure.code == "cancelled") + assert(uv.fs_lstat(root .. "/cancel-start") == nil) + local directory = must(uv.fs_scandir(root)) + while true do + local name = uv.fs_scandir_next(directory) + if not name then + break + end + assert( + not name:find("libtmux-lua-start-", 1, true), + "startup cleanup left an owned directory" + ) + end + print("startup readiness, failed spawn and cancelled startup PASS") + return true +end) +if err then + local function describe(failure) + io.stderr:write(tostring(failure.code), ": ", tostring(failure), "\n") + if type(failure.cause) == "table" then + describe(failure.cause) + end + for _, child in ipairs(failure.errors or {}) do + describe(child) + end + end + describe(err) +end +assert(value, tostring(err)) diff --git a/tests/integration/startup_handoff.lua b/tests/integration/startup_handoff.lua new file mode 100644 index 00000000..b7174531 --- /dev/null +++ b/tests/integration/startup_handoff.lua @@ -0,0 +1,93 @@ +local adapter = require("libtmux.runtime.luv") +local codec = require("libtmux._internal.codec") +local errors = require("libtmux._internal.error") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local function must(value, err) + if err then + error(err, 0) + end + return value +end +local result, failure = adapter.run(function(runtime) + local root = assert(os.getenv("LIBTMUX_TEST_ROOT")) + for _, mode in ipairs({ "success", "cancel", "rollback" }) do + if not os.getenv("HANDOFF_MODE") or os.getenv("HANDOFF_MODE") == mode then + local published, other = root .. "/handoff-" .. mode, root .. "/other-" .. mode + local replacement = must(runtime:owned_server({ socket_path = other }):await()) + local replacement_pid = replacement:receipt().pid + local link, decode = uv.fs_link, codec.decode + local installed, injected, private, pending, accepted_pid + ---@diagnostic disable-next-line: duplicate-set-field + uv.fs_link = function(from, to, callback) + local ok, err = link(from, to, callback) + if ok and to == published then + assert(not callback) + private = from + must(uv.fs_unlink(published)) + must(link(other, published)) + installed = true + end + return ok, err + end + ---@diagnostic disable-next-line: duplicate-set-field + codec.decode = function(text, count, options) + local rows, err = decode(text, count, options) + if installed and count == 7 and rows and rows[1] and not injected then + injected, accepted_pid = true, rows[1][1] + if mode == "cancel" then + pending:cancel("cancel during startup acceptance") + end + if mode == "rollback" then + return nil, errors.new("injected_receipt", "fail startup receipt parsing") + end + end + return rows, err + end + pending = runtime:find_or_create_server({ socket_path = published }) + local found, startup_error = pending:await() + uv.fs_link, codec.decode = link, decode + local public = runtime:connect({ socket_path = published }):await() + local response = public + and public:command({ "display-message", "-p", "#{pid}" }):await() + local reachable = response and response.stdout == replacement_pid .. "\n" + print( + mode + .. ": accepted PID " + .. tostring(accepted_pid) + .. ", replacement PID " + .. replacement_pid + ) + print(mode .. ": replacement public endpoint reachable " .. tostring(reachable == true)) + assert(installed and injected) + assert(reachable, "startup cleanup destroyed the replacement daemon") + assert(public) + assert(accepted_pid ~= replacement_pid, "startup accepted the replacement daemon") + if mode == "success" then + assert(found and found.created and found.owner, tostring(startup_error)) + assert(found.owner.value == found.value) + assert(found.owner:receipt().pid == accepted_pid) + local owned = + must(found.value:command({ "display-message", "-p", "#{pid}" }):await()) + assert( + owned.stdout == accepted_pid .. "\n", + "returned handle must retain the created daemon" + ) + must(found.owner:close():await()) + elseif mode == "cancel" then + assert(not found and startup_error and startup_error.code == "cancelled") + else + assert(not found and startup_error) + end + assert(uv.fs_lstat(private) == nil) + assert(uv.fs_lstat(private:match("^(.*)/s$")) == nil) + local again = must(public:command({ "display-message", "-p", "#{pid}" }):await()) + assert(again.stdout == replacement_pid .. "\n", "close must retain replacement") + must(replacement:close():await()) + end + end + print("private startup handoff success/cancellation/rollback PASS") + return true +end) +assert(result, tostring(failure)) diff --git a/tests/integration/test_environment.py b/tests/integration/test_environment.py index 91a8ec3a..b102696d 100644 --- a/tests/integration/test_environment.py +++ b/tests/integration/test_environment.py @@ -2,6 +2,7 @@ import os from pathlib import Path +import re import shutil import subprocess import unittest @@ -15,6 +16,9 @@ class EnvironmentTests(unittest.TestCase): def run_case(self, mode): for host in ("luv", "nvim"): fixture = TmuxFixture() + # The decoder rejects nonportable names; this test adds its own malformed name below. + fixture.env = {key: value for key, value in fixture.env.items() + if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key)} fixture.env.update(LC_ALL="C", LANG="C") with self.subTest(host=host), fixture: env = dict(fixture.env, TMUX_BIN=shutil.which(fixture.binary), diff --git a/tests/integration/test_fixture.py b/tests/integration/test_fixture.py index 0b9c936e..0fca7b3f 100644 --- a/tests/integration/test_fixture.py +++ b/tests/integration/test_fixture.py @@ -131,6 +131,18 @@ def fail_cleanup(*args, **kwargs): self.assertTrue(client.stderr.closed) self.assertEqual(borrowed.run("has-session", "-t", "fixture").returncode, 0) + def test_exit_observer_failure_retains_root_for_retry(self): + owned = TmuxFixture().__enter__() + self.addCleanup(owned.close) + with patch.object(owned, "_wait_exits", side_effect=RuntimeError("exit unproved")): + with self.assertRaisesRegex(RuntimeError, "exit unproved"): + owned.close() + self.assertTrue(owned.path.exists(), "unproved exit must retain the owned root") + self.assertFalse(owned._closed) + self.assertTrue(any(watch.fd is not None for watch in owned._exits.values())) + owned.close() + self.assertFalse(owned.path.exists()) + def test_reaped_client_pipes_close(self): with TmuxFixture() as owned: client = owned.spawn("display-message", "-p", "ready") diff --git a/tests/integration/test_lifecycle.py b/tests/integration/test_lifecycle.py new file mode 100644 index 00000000..6939a6c4 --- /dev/null +++ b/tests/integration/test_lifecycle.py @@ -0,0 +1,197 @@ +"""Run the exact ordinary example with captured defaults in owned tmux fixtures.""" + +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tests.support.tmux_fixture import TmuxFixture + +ROOT = Path(__file__).resolve().parents[2] +EXAMPLE = ROOT / "examples/ordinary.lua" + +# The wrapper changes the failure trigger, never the imported example file. +WRAPPER = r''' +local mode = os.getenv("LIBTMUX_EXAMPLE_MODE") +local adapter = require("libtmux.runtime.luv") +local run = adapter.run +local emit = print +adapter.run = function(body, options) + local value, failure = run(function(runtime) + print = function(...) + emit(...) + if mode == "cancel" then + runtime:close("injected cancellation") + elseif mode == "body" or mode == "cleanup" then + error("injected body failure", 0) + end + end + if mode == "cleanup" then + local uv = require("luv") + local spawn = uv.spawn + uv.spawn = function(binary, spec, callback) + for _, argument in ipairs(spec.args) do + if argument == "kill-session" then + return nil, "injected teardown failure" + end + end + return spawn(binary, spec, callback) + end + end + return body(runtime) + end, options) + if failure then error(failure, 0) end + return value +end +local ok, err = pcall(dofile, os.getenv("LIBTMUX_EXAMPLE_FILE")) +if not ok then + io.stderr:write(tostring(err), "\n") + if type(err) == "table" and err.cause then + io.stderr:write("body: ", tostring(err.cause), "\n") + end + if type(err) == "table" and err.errors then + for _, failure in ipairs(err.errors) do + io.stderr:write("cleanup: ", tostring(failure), "\n") + end + end + os.exit(1) +end +''' + + +class LifecycleTests(unittest.TestCase): + def child_env(self, fixture, *, named=False): + env = {key: value for key, value in fixture.env.items() + if key not in ("LIBTMUX_SOCKET_PATH", "LIBTMUX_SOCKET_NAME", "TMUX_TMPDIR")} + binary = shutil.which(fixture.binary) + env["PATH"] = os.pathsep.join((str(Path(binary).parent), env.get("PATH", ""))) + if named: + env.update(LIBTMUX_SOCKET_NAME=fixture.socket.name, TMUX_TMPDIR=str(fixture.path)) + else: + env["LIBTMUX_SOCKET_PATH"] = str(fixture.socket) + env.update(TMUX="invalid but lower precedence", TMUX_PANE="%999") + return env + + def run_example(self, fixture, *, named=False, mode=None): + env = self.child_env(fixture, named=named) + lua = env.get("LIBTMUX_TEST_LUA") or shutil.which("lua") + command = [lua, str(EXAMPLE)] + if mode: + env.update(LIBTMUX_EXAMPLE_MODE=mode, LIBTMUX_EXAMPLE_FILE=str(EXAMPLE)) + command = [lua, "-e", WRAPPER] + return subprocess.run(command, cwd=ROOT, env=env, capture_output=True, timeout=0.8) + + def test_exact_example_path_and_named_defaults(self): + before = EXAMPLE.read_bytes() + for named in (False, True): + with self.subTest(named=named): + with TmuxFixture(socket_name="ordinary" if named else None) as fixture: + result = self.run_example(fixture, named=named) + self.assertEqual(result.returncode, 0, result.stderr.decode()) + self.assertEqual(result.stdout, b"session: ordinary-example\n") + self.assertEqual(fixture.run("list-sessions", "-F", "#{session_name}").stdout, + "fixture\n") + self.assertEqual(list(fixture.path.rglob("libtmux-lua-pin-*")), []) + self.assertFalse(fixture.path.exists()) + self.assertEqual(EXAMPLE.read_bytes(), before) + + def test_body_error_and_cancellation_remove_created_session(self): + for mode in ("body", "cancel"): + with self.subTest(mode=mode): + with TmuxFixture() as fixture: + result = self.run_example(fixture, mode=mode) + self.assertEqual(result.returncode, 1) + self.assertIn(b"session: ordinary-example", result.stdout) + self.assertIn(b"injected", result.stderr) + self.assertEqual(fixture.run("list-sessions", "-F", "#{session_name}").stdout, + "fixture\n") + self.assertEqual(list(fixture.path.rglob("libtmux-lua-pin-*")), []) + self.assertFalse(fixture.path.exists()) + + def test_cleanup_failure_is_visible_and_harness_reaps_remaining_session(self): + with TmuxFixture() as fixture: + result = self.run_example(fixture, mode="cleanup") + self.assertEqual(result.returncode, 1) + self.assertIn(b"deferred cleanup failed", result.stderr) + self.assertIn(b"body: injected body failure", result.stderr) + self.assertIn(b"cleanup:", result.stderr) + self.assertIn("ordinary-example", fixture.run("list-sessions", "-F", "#{session_name}").stdout) + self.assertFalse(fixture.path.exists()) + + def test_captured_clients_and_deferred_cleanup_in_luv_and_neovim(self): + for host in ("luv", "nvim"): + for mode in ("normal", "body", "cancel"): + with self.subTest(host=host, mode=mode), TmuxFixture(socket_name="captured") as fixture: + env = self.child_env(fixture, named=True) + env.update(LIBTMUX_LIFECYCLE_MODE=mode, LIBTMUX_CLIENT_MARKER="before") + if host == "luv": + command = [env.get("LIBTMUX_TEST_LUA") or shutil.which("lua"), + "tests/integration/lifecycle.lua"] + else: + env.pop("LUA_CPATH", None) + command = [env.get("LIBTMUX_TEST_NVIM") or shutil.which("nvim"), + "--headless", "-u", "NONE", "-i", "NONE", "-c", + "lua dofile('tests/integration/lifecycle.lua')"] + result = subprocess.run(command, cwd=ROOT, env=env, + capture_output=True, timeout=0.8) + self.assertEqual(result.returncode, 0, result.stderr.decode()) + self.assertIn(f"captured lifecycle {mode} PASS".encode(), result.stdout) + self.assertEqual(fixture.run("list-sessions", "-F", "#{session_name}").stdout, + "fixture\n") + self.assertEqual(list(fixture.path.rglob("libtmux-lua-pin-*")), []) + + def test_named_root_checks_preserve_filesystem_semantics(self): + with TmuxFixture(socket_name="ordinary") as fixture: + env = self.child_env(fixture, named=True) + lua = env.get("LIBTMUX_TEST_LUA") or shutil.which("lua") + probe = r''' +local adapter = require("libtmux.runtime.luv") +local value, err = adapter.run(function(runtime) + return runtime:connect():await() +end) +if err then io.stderr:write(err.code, ": ", tostring(err), "\n"); os.exit(1) end +assert(value) +''' + directory = fixture.socket.parent + removed = fixture.path / "gone" + removed.mkdir() + removed.rmdir() + for root in (str(fixture.path / "missing" / ".."), str(fixture.path / "gone")): + with self.subTest(root=root): + env["TMUX_TMPDIR"] = root + result = subprocess.run([lua, "-e", probe], cwd=ROOT, env=env, + capture_output=True, timeout=0.8) + self.assertEqual(result.returncode, 1) + self.assertIn(b"invalid_endpoint", result.stderr) + branch = fixture.path / "branch" + branch.mkdir() + (branch / "inner").mkdir() + (fixture.path / "link").symlink_to(branch / "inner", target_is_directory=True) + directory.rename(branch / directory.name) + fixture.socket = branch / directory.name / fixture.socket.name + env["TMUX_TMPDIR"] = str(fixture.path / "link") + "/.." + result = subprocess.run([lua, "-e", probe], cwd=ROOT, env=env, + capture_output=True, timeout=0.8) + self.assertEqual(result.returncode, 0, result.stderr.decode()) + self.assertFalse(directory.exists(), "root was normalized as a string") + + def test_named_directory_permissions_and_fresh_root_without_daemon(self): + with TmuxFixture(socket_name="ordinary") as fixture: + env = self.child_env(fixture, named=True) + for mode, succeeds in ((0o700, True), (0o770, True), (0o701, False)): + fixture.socket.parent.chmod(mode) + result = self.run_example(fixture, named=True) + self.assertEqual(result.returncode == 0, succeeds, result.stderr.decode()) + fixture.socket.parent.chmod(0o700) + with tempfile.TemporaryDirectory(prefix="libtmux-lua-fresh-", dir="/tmp") as fresh: + env["TMUX_TMPDIR"] = fresh + lua = env.get("LIBTMUX_TEST_LUA") or shutil.which("lua") + result = subprocess.run([lua, str(EXAMPLE)], cwd=ROOT, env=env, + capture_output=True, timeout=0.8) + self.assertNotEqual(result.returncode, 0) + directory = Path(fresh) / f"tmux-{os.getuid()}" + self.assertEqual(directory.stat().st_mode & 0o777, 0o700) + self.assertEqual(list(directory.iterdir()), []) + self.assertIn(b"not an accessible socket", result.stderr) diff --git a/tests/integration/test_ownership.py b/tests/integration/test_ownership.py new file mode 100644 index 00000000..566d8bde --- /dev/null +++ b/tests/integration/test_ownership.py @@ -0,0 +1,62 @@ +"""Collect native lifecycle programs and unchanged examples with outer cleanup.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class OwnershipTests(unittest.TestCase): + def run_case(self, name, source, *arguments): + original = (ROOT / source).read_bytes() + with tempfile.TemporaryDirectory(prefix="libtmux-lua-evidence-") as directory: + command = [sys.executable, "tests/support/ownership_fixture.py", name, source, + "--evidence", directory, *arguments] + result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, timeout=12) + receipt = json.loads((Path(directory) / name / "receipt.json").read_text()) + logs = "\n".join(path.read_text() for path in (Path(directory) / name).glob("*.log")) + self.assertEqual(result.returncode, 0, result.stderr + logs) + self.assertTrue(receipt["root_removed"]) + self.assertTrue(receipt["parent_environment_unchanged"]) + events = receipt["events"] + self.assertEqual(events[-1]["event"], "removed_root") + accepted = {event["pid"] for event in events if event["event"] == "accepted"} + exited = {event["pid"] for event in events + if event["event"] == "observed_exit" and event["exited"]} + self.assertEqual(accepted, exited) + self.assertEqual((ROOT / source).read_bytes(), original) + return receipt + + def test_native_ownership_and_failure_programs(self): + for name in ("ownership", "ownership_failures", "ownership_edges", "acquisition", + "receipt_failures", "server_lifecycle", "startup_failures", "legacy_environment", + "replacement_cleanup", "discovery_environment", "startup_handoff"): + with self.subTest(program=name): + receipt = self.run_case(name, f"tests/integration/{name}.lua") + expected = "fixture\nunknown-receipt\n" if name == "receipt_failures" else "fixture\n" + self.assertEqual(receipt["remaining_sessions"], expected) + + def test_exact_owned_example_for_both_selectors(self): + for named in (False, True): + with self.subTest(named=named): + receipt = self.run_case("example", "examples/owned_session.lua", + *(["--named"] if named else [])) + self.assertEqual(receipt["remaining_sessions"], "fixture\n") + + def test_unchanged_example_body_failure_timeout_and_worker_death(self): + for mode in ("body-fail", "timeout", "crash"): + with self.subTest(mode=mode): + self.run_case(mode, "examples/owned_session.lua", "--worker-mode", mode, + "--timeout", "0.8") + + def test_neovim_ownership_and_cancellation(self): + nvim = os.environ.get("LIBTMUX_TEST_NVIM") + if not nvim: + self.skipTest("pass LIBTMUX_TEST_NVIM for the installed Neovim host lane") + receipt = self.run_case("nvim", "tests/integration/ownership_nvim.lua", "--nvim", nvim) + self.assertEqual(receipt["remaining_sessions"], "fixture\n") diff --git a/tests/support/ownership_fixture.py b/tests/support/ownership_fixture.py new file mode 100644 index 00000000..8f6c0a5b --- /dev/null +++ b/tests/support/ownership_fixture.py @@ -0,0 +1,208 @@ +"""Run lifecycle programs inside a Linux fixture with observed process retirement. + +The example is read from disk unchanged. Configuration and failure injection are +external; cleanup addresses accepted child identities, never the default socket. +""" + +import argparse +import ctypes +import hashlib +import json +import os +from pathlib import Path +import select +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time + +ROOT = Path(__file__).resolve().parents[2] +OBSERVER = Path(__file__).with_name('ownership_observer.lua') +sys.path.insert(0, str(ROOT / 'scripts')) +from runtime_config import identify, clean_environment + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('label') + parser.add_argument('source') + parser.add_argument('--evidence', type=Path, required=True) + parser.add_argument('--lua', default=os.environ.get('LIBTMUX_TEST_LUA') or shutil.which('lua')) + parser.add_argument('--tmux', default=os.environ.get('TMUX_BIN') or shutil.which('tmux')) + parser.add_argument('--named', action='store_true') + parser.add_argument('--module-root', type=Path, default=ROOT) + parser.add_argument('--worker-mode', choices=('body-fail', 'timeout', 'crash')) + parser.add_argument('--nvim') + parser.add_argument('--timeout', type=float, default=10) + args = parser.parse_args() + output = args.evidence / args.label + output.mkdir(parents=True, exist_ok=False) + assert ctypes.CDLL(None).prctl(36, 1, 0, 0, 0) == 0 + runtime = identify(args.lua) + env = {key: value for key, value in clean_environment().items() if key not in ('TMUX', 'TMUX_PANE', 'LIBTMUX_SOCKET_NAME', 'LIBTMUX_SOCKET_PATH', 'TMUX_TMPDIR')} + rocks = ROOT / '.cache/rocks' / runtime.cache_label + env['LUA_PATH'] = f'{args.module_root}/lua/?.lua;{args.module_root}/lua/?/init.lua;{ROOT}/?.lua;{rocks}/share/lua/{runtime.version}/?.lua;{rocks}/share/lua/{runtime.version}/?/init.lua' + env['LUA_CPATH'] = f'{rocks}/lib/lua/{runtime.version}/?.so' + env['PATH'] = str(Path(args.tmux).parent) + ':' + env.get('PATH', '') + env['SHELL'] = '/bin/sh' + root = Path(tempfile.mkdtemp(prefix='libtmux-lua-', dir='/dev/shm')) + socket = root / 'socket' + if args.named: + directory = root / f'tmux-{os.getuid()}' + directory.mkdir(mode=0o700) + socket = directory / 'named' + env.update(LIBTMUX_SOCKET_NAME='named', TMUX_TMPDIR=str(root)) + else: + env['LIBTMUX_SOCKET_PATH'] = str(socket) + env.update(LIBTMUX_TEST_ROOT=str(root), LIBTMUX_TEST_BINARY=args.tmux, EXAMPLE_UNUSED_SOCKET=str(root / 'documentation-server')) + observer = root / 'observer' + observer.mkdir() + env['LIBTMUX_OBSERVER'] = str(observer) + env['LUA_INIT'] = '@' + str(OBSERVER) + if args.worker_mode: + env['LIBTMUX_WORKER_MODE'] = args.worker_mode + events, watches, children = [], {}, [] + def accept(pid, role): + if pid in watches: + return + try: + fd = os.pidfd_open(pid) + stat = Path(f'/proc/{pid}/stat').read_text() + start = stat.rsplit(') ', 1)[1].split()[19] + watches[pid] = fd + events.append({'event': 'accepted', 'pid': pid, 'start': start, 'role': role, 'time': time.monotonic()}) + except ProcessLookupError: + events.append({'event': 'already_exited', 'pid': pid, 'role': role}) + def collect(pid): + path = Path(f'/proc/{pid}/task/{pid}/children') + try: + pids = [int(item) for item in path.read_text().split()] + except FileNotFoundError: + return + for child in pids: + accept(child, 'owned descendant') + collect(child) + observer_stop = threading.Event() + def observe(): + handled = set() + while not observer_stop.is_set(): + for notice in observer.glob('spawn-*'): + if notice.name in handled: + continue + try: + pid = int(notice.read_text()) + cmdline = Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0') + stat = Path(f'/proc/{pid}/stat').read_text().rsplit(') ', 1)[1].split() + assert int(stat[1]) == worker.pid, (pid, stat[1], worker.pid) + assert b'-D' in cmdline and any(item.startswith(str(root).encode()+b'/') for item in cmdline), cmdline + accept(pid, 'library foreground daemon') + events.append({'event': 'spawn_route', 'pid': pid, 'argv': [item.decode(errors='replace') for item in cmdline if item]}) + notice.with_name('ack-' + notice.name).write_text('accepted') + handled.add(notice.name) + except (FileNotFoundError, ValueError): + pass + except BaseException as error: + errors.append('observer: ' + repr(error)) + notice.with_name('ack-' + notice.name).write_text('rejected') + handled.add(notice.name) + observer_stop.wait(0.001) + def cmd(*words): + return subprocess.run([args.tmux, '-N', '-S', str(socket), *words], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1) + host_environment = dict(os.environ) + report = {'label': args.label, 'source': str(Path(args.source).resolve()), 'source_sha256': hashlib.sha256(Path(args.source).read_bytes()).hexdigest(), 'lua': runtime.executable, 'nvim': args.nvim, 'tmux': args.tmux, 'root': str(root), 'named': args.named, 'module_root': str(args.module_root), 'worker_mode': args.worker_mode, 'events': events} + report['source_module_hashes'] = {str(path.relative_to(args.module_root)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted((args.module_root / 'lua').rglob('*.lua'))} + daemon = worker = None + errors = [] + began = time.monotonic() + try: + daemon = subprocess.Popen([args.tmux, '-D', '-f', '/dev/null', '-S', str(socket)], env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + accept(daemon.pid, 'foreground daemon') + limit = time.monotonic() + 0.8 + while True: + if daemon.poll() is not None or time.monotonic() >= limit: + raise RuntimeError('foreground daemon did not confirm its owned endpoint') + if socket.exists(): + probe = cmd('display-message', '-p', '#{pid}') + if probe.returncode == 0 and probe.stdout == f'{daemon.pid}\n'.encode(): + break + select.select([watches[daemon.pid]], [], [], 0.005) + result = cmd('new-session', '-d', '-s', 'fixture', '-P', '-F', '#{pane_pid}', 'exec /bin/cat') + assert result.returncode == 0, result.stderr + accept(int(result.stdout), 'fixture pane') + with (output / 'stdout.log').open('wb') as stdout, (output / 'stderr.log').open('wb') as stderr: + command = [runtime.executable, args.source] + if args.nvim: + command = [args.nvim, '--headless', '-u', 'NONE', '-i', 'NONE', '-n', '-c', 'luafile ' + str(OBSERVER), '-c', 'luafile ' + args.source] + report['command'] = command + worker = subprocess.Popen(command, cwd=ROOT, env=env, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr) + accept(worker.pid, 'Lua worker') + observer_thread = threading.Thread(target=observe) + observer_thread.start() + try: + report['returncode'] = worker.wait(timeout=args.timeout) + except subprocess.TimeoutExpired: + report['timed_out'] = True + collect(worker.pid) + signal.pidfd_send_signal(watches[worker.pid], signal.SIGKILL) + worker.wait(timeout=1) + report['returncode'] = worker.returncode + report['remaining_sessions'] = cmd('list-sessions', '-F', '#{session_name}').stdout.decode(errors='replace') + except BaseException as error: + errors.append(repr(error)) + finally: + observer_stop.set() + if 'observer_thread' in locals(): + observer_thread.join(timeout=1) + collect(os.getpid()) + for pid, fd in list(watches.items()): + if not select.select([fd], [], [], 0)[0]: + signal.pidfd_send_signal(fd, signal.SIGTERM) + deadline = time.monotonic() + 1 + pending = set(watches.values()) + while pending and time.monotonic() < deadline: + ready = select.select(list(pending), [], [], 0.05)[0] + pending.difference_update(ready) + for fd in pending: + signal.pidfd_send_signal(fd, signal.SIGKILL) + if pending: + deadline = time.monotonic() + 1 + while pending and time.monotonic() < deadline: + pending.difference_update(select.select(list(pending), [], [], 0.05)[0]) + for pid, fd in watches.items(): + exited = bool(select.select([fd], [], [], 0)[0]) + events.append({'event': 'observed_exit', 'pid': pid, 'exited': exited, 'time': time.monotonic()}) + os.close(fd) + if daemon is not None: + daemon.wait(timeout=1) + if worker is not None: + worker.wait(timeout=1) + while True: + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + if not pid: + break + except ChildProcessError: + break + if not pending: + shutil.rmtree(root) + events.append({'event': 'removed_root', 'time': time.monotonic()}) + else: + errors.append('owned process exit unproved; retaining root') + report.update(errors=errors, elapsed_seconds=time.monotonic()-began, root_removed=not root.exists(), parent_environment_unchanged=dict(os.environ) == host_environment) + (output / 'receipt.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps({key: report.get(key) for key in ('label', 'returncode', 'root_removed', 'elapsed_seconds', 'errors')})) + expected = report.get('returncode') == 0 + if args.worker_mode == 'body-fail': + expected = report.get('returncode') == 1 and report.get('remaining_sessions') == 'fixture\n' + elif args.worker_mode == 'timeout': + expected = report.get('timed_out') is True and report.get('returncode') == -signal.SIGKILL + elif args.worker_mode == 'crash': + expected = report.get('returncode') == -signal.SIGKILL and not report.get('timed_out') + return int(bool(errors) or not expected or not report['parent_environment_unchanged']) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/support/ownership_observer.lua b/tests/support/ownership_observer.lua new file mode 100644 index 00000000..0bcae902 --- /dev/null +++ b/tests/support/ownership_observer.lua @@ -0,0 +1,56 @@ +local host = rawget(_G, "vim") +-- luv is the native host module, distinct from libtmux.runtime.luv. +---@diagnostic disable-next-line: different-requires +local uv = host and (host.uv or host.loop) or require("luv") +local spawn = uv.spawn +uv.spawn = function(binary, options, callback) + local handle, pid = spawn(binary, options, callback) + local daemon = false + for _, argument in ipairs(options.args or {}) do + if argument == "-D" then + daemon = true + end + end + if handle and daemon then + local directory = assert(os.getenv("LIBTMUX_OBSERVER")) + local file = assert(io.open(directory .. "/spawn-" .. pid, "w")) + file:write(tostring(pid)) + file:close() + local started = uv.hrtime() + while true do + local ack = io.open(directory .. "/ack-spawn-" .. pid, "r") + if ack then + assert(ack:read("*a") == "accepted") + ack:close() + break + end + assert( + (uv.hrtime() - started) / 1000000 < 750, + "external daemon identity acceptance timed out" + ) + uv.sleep(1) + end + end + return handle, pid +end + +local mode = os.getenv("LIBTMUX_WORKER_MODE") +if mode then + local original_print = print + -- The worker-local hook injects failure without editing the example file. + -- luacheck: push globals print + print = function(...) + original_print(...) + io.stdout:flush() + if mode == "body-fail" then + error("outer harness injected body failure after example output", 0) + elseif mode == "crash" then + uv.kill(uv.os_getpid(), "sigkill") + elseif mode == "timeout" then + while true do + uv.sleep(100) + end + end + end + -- luacheck: pop +end diff --git a/tests/support/tmux_fixture.py b/tests/support/tmux_fixture.py index 9e84d9f2..df718df6 100644 --- a/tests/support/tmux_fixture.py +++ b/tests/support/tmux_fixture.py @@ -58,8 +58,9 @@ class TmuxFixture: this context can close before that runner exits. """ - def __init__(self, binary=None): + def __init__(self, binary=None, *, socket_name=None): self.binary = binary or os.environ.get("TMUX_BIN", "tmux") + self.socket_name = socket_name self.env = {key: value for key, value in os.environ.items() if key not in ("TMUX", "TMUX_PANE")} self.path = None @@ -77,6 +78,12 @@ def __enter__(self): self.path = Path(tempfile.mkdtemp(prefix="libtmux-lua-", dir="/tmp")) self.socket = self.path / "tmux.sock" try: + if self.socket_name is not None: + if not self.socket_name or self.socket_name in (".", "..") or "/" in self.socket_name: + raise ValueError("fixture socket_name must be a nonempty leaf") + directory = self.path / f"tmux-{os.getuid()}" + directory.mkdir(mode=0o700) + self.socket = directory / self.socket_name result = self.run( "new-session", "-d", "-s", "fixture", "-P", "-F", "#{pid} #{pane_pid}", "exec /bin/cat", @@ -151,11 +158,16 @@ def attempt(operation, action): attempt(f"terminate process {watch.pid}", watch.terminate) for client in self._clients: attempt(f"close client {client.pid}", lambda: self._finish_client(client)) + before_wait = len(errors) attempt("wait for owned process exit", self._wait_exits) - for watch in self._exits.values(): - attempt(f"close process observer {watch.pid}", watch.close) - attempt("remove fixture directory", lambda: shutil.rmtree(self.path)) - self._closed = True + exits_proved = len(errors) == before_wait + if exits_proved: + for watch in self._exits.values(): + attempt(f"close process observer {watch.pid}", watch.close) + if exits_proved: + attempt("remove fixture directory", lambda: shutil.rmtree(self.path)) + # A failed exit observation must retain the exact root for investigation. + self._closed = not self.path.exists() for _, error in errors: if not isinstance(error, Exception): raise error diff --git a/tests/unit/command.lua b/tests/unit/command.lua index 40ccff17..56039a93 100644 --- a/tests/unit/command.lua +++ b/tests/unit/command.lua @@ -101,6 +101,8 @@ function M.test_invalid_group_member_rejects_whole_submission_without_effects() {}, { socket = "nul\000" }, { socket = "valid", extra = true }, + { socket = "valid", env = false }, + { socket = "valid", env = { "KEY=nul\000" } }, }) do local encoded, err = command.prepare(invalid, { { "valid" } }) t.assertNil(encoded) diff --git a/tests/unit/control_io.lua b/tests/unit/control_io.lua index ccb95c8d..f319d39b 100644 --- a/tests/unit/control_io.lua +++ b/tests/unit/control_io.lua @@ -44,6 +44,7 @@ local function fixture() binary = "/actual/tmux", socket = "/owned/pin/socket", config = "/dev/null", + env = { "KEEP=captured" }, }, { session_id = "$0" }, function(data) f.data[#f.data + 1] = data end, function(err) @@ -61,6 +62,7 @@ end function M.test_literal_control_spawn_keeps_reader_alive_until_exit_and_both_eofs() local f = fixture() t.assertEquals(f.uv.program, "/actual/tmux") + t.assertEquals(f.uv.options.env, { "KEEP=captured" }) t.assertEquals(f.uv.options.args, { "-N", "-S", diff --git a/tests/unit/defaults.lua b/tests/unit/defaults.lua new file mode 100644 index 00000000..c1b46403 --- /dev/null +++ b/tests/unit/defaults.lua @@ -0,0 +1,242 @@ +local t = require("luaunit") +local defaults = require("libtmux._internal.defaults") +local M = {} + +local function host(env) + return { + os_environ = function() + return env or {} + end, + getuid = function() + return 1000 + end, + cwd = function() + return "/cwd" + end, + fs_stat = function(path) + if path == "/usr/bin/tmux" or path == "/cwd/bin/tmux" then + return { type = "file" } + end + end, + fs_access = function() + return true + end, + } +end + +local function resolve(env, options) + return assert(defaults.resolve(host(env), options)) +end + +function M.test_default_selection_is_pure_and_does_not_connect_to_ambient_server() + local value = resolve({}) + t.assertEquals(value.socket, "/tmp/tmux-1000/default") + t.assertEquals(value.binary, "/usr/bin/tmux") + t.assertEquals(value.config, "/dev/null") + t.assertEquals(value.env, {}) +end + +function M.test_precedence_ignores_weaker_invalid_values() + local env = { + LIBTMUX_SOCKET_PATH = "/chosen", + LIBTMUX_SOCKET_NAME = "../bad", + TMUX = "invalid", + TMUX_TMPDIR = "relative", + } + t.assertEquals(resolve(env).socket, "/chosen") + t.assertEquals(resolve(env, { socket_path = "/explicit" }).socket, "/explicit") + env.TMUX_TMPDIR = "/root" + t.assertEquals(resolve(env, { socket_name = "explicit" }).socket, "/root/tmux-1000/explicit") + env.LIBTMUX_SOCKET_PATH = "" + env.LIBTMUX_SOCKET_NAME = "selected" + t.assertEquals(resolve(env).socket, "/root/tmux-1000/selected") + env.LIBTMUX_SOCKET_NAME = "" + env.TMUX = "/path,with,commas,123,$4" + t.assertEquals(resolve(env).socket, "/path,with,commas") + env.TMUX = "" + t.assertEquals(resolve(env).socket, "/root/tmux-1000/default") +end + +function M.test_selected_values_fail_without_fallback() + for _, options in ipairs({ + { socket_name = "" }, + { socket_name = "." }, + { socket_name = ".." }, + { socket_name = "a/b" }, + { socket_name = "a\\b" }, + { socket_name = "a\000b" }, + { socket_path = "relative" }, + { socket_path = "" }, + { socket_path = "/bad/" }, + { socket_path = "/ok", socket_name = "name" }, + { binary = "tmux" }, + { config_path = "relative" }, + { unknown = true }, + }) do + local value, err = defaults.resolve(host(), options) + t.assertNil(value) + assert(err) + t.assertEquals(err.code, "invalid_endpoint") + t.assertEquals(err.effect, "not_sent") + end + for _, env in ipairs({ + { LIBTMUX_SOCKET_PATH = "relative", LIBTMUX_SOCKET_NAME = "valid" }, + { LIBTMUX_SOCKET_NAME = "../invalid", TMUX = "/path,1,0" }, + { TMUX_TMPDIR = "relative" }, + }) do + local value, err = defaults.resolve(host(env)) + t.assertNil(value) + assert(err) + t.assertEquals(err.code, "invalid_endpoint") + end +end + +function M.test_tmux_context_parses_last_two_commas_and_preserves_path_bytes() + for _, session in ipairs({ "0", "$0", "0002", "$42", "-1" }) do + local path = "/tmp/ a,b " + local value = resolve({ TMUX = path .. ",0001," .. session, TMUX_PANE = "%9" }) + t.assertEquals(value.socket, path) + t.assertEquals( + value.context, + { socket = path, pid = "0001", session = session, pane = "%9" } + ) + t.assertEquals(value.env, {}) + end +end + +function M.test_malformed_tmux_context_is_an_error() + for _, value in ipairs({ + "invalid", + "/tmp/one,1", + ",1,0", + "relative,1,0", + "/path,0,0", + "/path,000,0", + "/path,-1,0", + "/path,+1,0", + "/path,1 ,0", + "/path,,0", + "/path,1,", + "/path,1,-2", + "/path,1,+1", + "/path,1, 1", + "/path,1,$-1", + "/path,1,$$1", + "/path,1,1x", + "/path,1,0,extra", + "/path\000,1,0", + }) do + local resolved, err = defaults.resolve(host({ TMUX = value })) + t.assertNil(resolved, value) + assert(err) + t.assertEquals(err.code, "invalid_endpoint", value) + end +end + +function M.test_names_and_roots_preserve_filesystem_components() + for _, root in ipairs({ "/root/missing/../selected", "/root/symlink/..", "/root/space " }) do + t.assertEquals( + resolve({ TMUX_TMPDIR = root }, { socket_name = " a,b " }).socket, + root .. "/tmux-1000/ a,b " + ) + end +end + +function M.test_environment_and_overrides_are_copied_without_host_mutation() + local env = { + KEEP = "before", + DELETE = "yes", + TMUX = "invalid", + TMUX_PANE = "%1", + LIBTMUX_SOCKET_PATH = "/from-host", + } + local options = { + client_env = { + KEEP = "override", + DELETE = false, + LIBTMUX_SOCKET_PATH = "/from-child", + }, + } + local value = resolve(env, options) + env.KEEP = "after" + options.client_env.KEEP = "after" + t.assertEquals(value.socket, "/from-child") + t.assertEquals(value.env, { "KEEP=override", "LIBTMUX_SOCKET_PATH=/from-child" }) + t.assertEquals(env.DELETE, "yes") + t.assertEquals(env.TMUX, "invalid") + t.assertEquals(env.TMUX_PANE, "%1") +end + +function M.test_captured_executable_search_and_validation() + t.assertEquals(resolve({ PATH = "missing:bin:/usr/bin" }).binary, "/cwd/bin/tmux") + local value, err = defaults.resolve(host({ PATH = "/missing" })) + t.assertNil(value) + assert(err) + t.assertEquals(err.code, "invalid_endpoint") + for _, overrides in ipairs({ { ["a=b"] = "x" }, { A = 1 }, { A = "x\000" }, false }) do + value, err = defaults.resolve(host(), { client_env = overrides }) + t.assertNil(value) + assert(err) + t.assertEquals(err.code, "invalid_endpoint") + end +end + +function M.test_connection_full_environment_sequence_and_empty_environment() + local ambient = { LEAK = "ambient", LIBTMUX_SOCKET_PATH = "/wrong", PATH = "/missing" } + local options = { binary = "/usr/bin/tmux", socket_path = "/selected", env = {} } + local value = resolve(ambient, options) + t.assertEquals(value.env, {}) + t.assertEquals(value.socket, "/selected") + options.env = { + "KEY=first", + "KEY=second", + "PATH=/usr/bin", + "LIBTMUX_SOCKET_PATH=/sequence", + "TMUX=/ignored,1,0", + "TMUX_PANE=%1", + "", + "bare-entry", + } + options.socket_path = nil + value = resolve(ambient, options) + options.env[1] = "KEY=changed" + t.assertEquals(value.socket, "/sequence") + t.assertEquals(value.env, { + "KEY=first", + "KEY=second", + "PATH=/usr/bin", + "LIBTMUX_SOCKET_PATH=/sequence", + "", + "bare-entry", + }) + t.assertEquals(ambient.LEAK, "ambient") +end + +function M.test_full_environment_and_override_map_are_mutually_exclusive() + for _, options in ipairs({ + { env = {}, client_env = {} }, + { env = { [2] = "PATH=/usr/bin" } }, + { env = { "BAD=\000" } }, + { env = false }, + }) do + local value, err = defaults.resolve(host(), options) + t.assertNil(value) + t.assertEquals(assert(err).code, "invalid_endpoint") + end +end + +function M.test_discovery_and_connection_share_first_tmpdir_value() + for _, case in ipairs({ + { "/first", "/second", "/first" }, + { "", "/second", "/tmp" }, + { "/first", "", "/first" }, + }) do + local entries = { "TMUX_TMPDIR=" .. case[1], "TMUX_TMPDIR=" .. case[2] } + local endpoint = resolve({}, { binary = "/usr/bin/tmux", env = entries }) + t.assertEquals(defaults.socket_root(endpoint.env), case[3]) + t.assertEquals(endpoint.socket, case[3] .. "/tmux-1000/default") + t.assertEquals(endpoint.env, entries) + end +end + +return M diff --git a/tests/unit/endpoint.lua b/tests/unit/endpoint.lua index 3cae1051..34499134 100644 --- a/tests/unit/endpoint.lua +++ b/tests/unit/endpoint.lua @@ -67,7 +67,7 @@ local function fixture() return pipe end function uv.spawn(program, spec, on_exit) - uv.spawned[#uv.spawned + 1] = { program = program, args = spec.args } + uv.spawned[#uv.spawned + 1] = { program = program, args = spec.args, env = spec.env } local metadata = spec.args[#spec.args]:find("#{q:pid}", 1, true) local function finish() if not metadata or not uv.dead_listener then @@ -516,4 +516,71 @@ function M.test_returned_endpoint_preserves_state_without_rooting_its_result_cyc t.assertNil(next(watched)) end +function M.test_captured_environment_reaches_evidence_commands_and_observers() + local f = fixture() + local env = { "KEEP=before", "TMUX=must-be-removed", "TMUX_PANE=%4" } + f:start(function(rt) + local request = + endpoints.bind(rt, { binary = "/tmux", socket = "/owned/tmux.sock", env = env }) + env[1] = "KEEP=after" + local bound = assert(request:await()) + assert(bound:execute({ "display-message", "-p", "done" }):await()) + assert(bound + :execute({ "display-message", "-p", "done" }, { + env = { "CHILD=override", "TMUX=ignored", "TMUX_PANE=%5" }, + }) + :await()) + local connection = assert(bound + :_client(function(_, endpoint) + t.assertEquals(endpoint.env, { "KEEP=before" }) + return true + end, function(done) + done() + end) + :await()) + t.assertTrue(connection) + assert(bound:close():await()) + end) + for index, launch in ipairs(f.uv.spawned) do + t.assertEquals(launch.env, index == 5 and { "CHILD=override" } or { "KEEP=before" }) + end +end + +function M.test_named_uid_directory_rejects_foreign_owner_or_symlink() + for _, stat in ipairs({ + { type = "directory", uid = 999, mode = 448 }, + { type = "link", uid = 1000, mode = 448 }, + { type = "directory", uid = 1000, mode = 449 }, + }) do + local f = fixture() + f.uv.fs_stat = function(_, callback) + f.driver.defer(function() + callback(nil, { type = "directory" }) + end) + return true + end + f.uv.fs_mkdir = function(_, mode, callback) + t.assertEquals(mode, 448) + f.driver.defer(function() + callback("EEXIST") + end) + return true + end + f.uv.files["/owned/tmux-1000"] = stat + f:start(function(rt) + local value, err = endpoints + .bind(rt, { + binary = "/tmux", + socket = "/owned/tmux.sock", + root = "/owned", + uid = 1000, + }) + :await() + t.assertNil(value) + t.assertEquals(err.code, "invalid_endpoint") + end) + t.assertEquals(f.uv.spawned, {}) + end +end + return M diff --git a/tests/unit/lifecycle.lua b/tests/unit/lifecycle.lua new file mode 100644 index 00000000..84cd66a8 --- /dev/null +++ b/tests/unit/lifecycle.lua @@ -0,0 +1,39 @@ +local luaunit = require("luaunit") +local lifecycle = require("libtmux._internal.lifecycle") +local M = {} + +local function row(token) + return "LQ1\r$a;123;456;" .. (token or string.rep("a", 32)) .. ";\\$1;@2;\\%3;0;.\n" +end + +function M.test_receipt_requires_one_complete_identity() + local generation = {} + local receipt = assert(lifecycle.parse({ stdout = row() }, "session", "$1", generation)) + luaunit.assertEquals(receipt.id, "$1") + luaunit.assertIs(receipt.generation, generation) + for _, output in ipairs({ + "", + row() .. row(), + row():sub(1, -2), + row(""), + row("bad"), + row() .. "garbage\n", + }) do + local value, err = lifecycle.parse({ stdout = output }, "session", "$1", generation) + luaunit.assertNil(value) + luaunit.assertEquals(assert(err).code, "invalid_receipt") + end + luaunit.assertNil(lifecycle.parse({ stdout = row() }, "session", "$9", generation)) +end + +function M.test_randomness_failure_does_not_fall_back_to_time_or_pid() + local value, err = lifecycle.nonce({ + random = function() + return nil, "unavailable" + end, + }) + luaunit.assertNil(value) + luaunit.assertEquals(assert(err).code, "unsupported") +end + +return M diff --git a/tests/unit/runtime.lua b/tests/unit/runtime.lua index 31584bdd..735ca523 100644 --- a/tests/unit/runtime.lua +++ b/tests/unit/runtime.lua @@ -1649,4 +1649,134 @@ function tests.test_host_dispatch_failure_still_releases_resource_budget_and_log lu.assertEquals(rt:stats().resources, 0) end +function tests.test_deferred_cleanup_awaits_before_resources_close() + local rt, driver = fixture() + local order = {} + local root = rt:start(function() + assert(rt:_resource(function(done) + order[#order + 1] = "transport" + done() + end)) + assert(rt:defer(function() + assert(rt:_operation(function() + order[#order + 1] = "first" + return true + end):await()) + end)) + assert(rt:defer(function() + order[#order + 1] = "second" + end)) + return "body" + end) + driver:drain() + lu.assertEquals(root:result(), "body") + lu.assertEquals(order, { "second", "first", "transport" }) + lu.assertTrue(root:is_retired()) +end + +function tests.test_deferred_cleanup_preserves_body_and_teardown_errors() + local rt, driver = fixture() + local body = { code = "body_failed" } + local teardown = { code = "teardown_failed" } + local root = rt:start(function() + assert(rt:defer(function() + error(teardown, 0) + end)) + error(body, 0) + end) + driver:drain() + local value, err = root:result() + lu.assertNil(value) + lu.assertEquals(err.code, "cleanup_failed") + lu.assertIs(err.cause, body) + lu.assertIs(err.errors[1], teardown) + lu.assertTrue(root:is_retired()) +end + +function tests.test_deferred_cleanup_runs_after_runtime_cancellation() + local rt, driver = fixture({ max_active = 1 }) + local waiting, cleaned + local root = rt:start(function() + assert(rt:defer(function() + cleaned = assert(rt:_request({ + start = function(settle, retire) + driver.defer(function() + settle(true) + retire() + end) + end, + }):await()) + end)) + waiting = rt:_request({ + start = function(_, retire) + return function() + retire() + end + end, + }) + waiting:await() + end) + driver:drain() + rt:close("stop body") + lu.assertFalse(root:is_settled()) + driver:drain() + lu.assertTrue(cleaned) + local _, err = root:result() + lu.assertEquals(err.code, "cancelled") + lu.assertTrue(root:is_retired()) + lu.assertEquals(rt:stats().resources, 0) +end + +function tests.test_repeated_close_keeps_async_cleanup_running_once() + local rt, driver = fixture() + ---@type any + local cleanup + local calls = 0 + local root = rt:start(function() + assert(rt:defer(function() + calls = calls + 1 + cleanup = operation(rt) + assert(cleanup.request:await()) + end)) + return "body" + end) + driver:drain() + rt:close("cancel during cleanup") + rt:close("repeat") + lu.assertEquals(calls, 1) + lu.assertEquals(cleanup.stopped, 0) + cleanup.settle(true) + cleanup.retire() + driver:drain() + local _, err = root:result() + lu.assertEquals(err.code, "cancelled") + lu.assertTrue(root:is_retired()) + lu.assertEquals(rt:stats().deferred, 0) +end + +function tests.test_deferred_failures_keep_later_cleanup_and_transport_errors() + local rt, driver = fixture() + local remaining + local root = rt:start(function() + assert(rt:_resource(function(done) + done({ code = "transport_cleanup" }) + end)) + assert(rt:defer(function() + remaining = true + end)) + assert(rt:defer(function() + return nil, { code = "deferred_cleanup" } + end)) + error({ code = "body_failure" }, 0) + end) + driver:drain() + local _, err = require("libtmux.runtime.luv")._result(root, rt) + lu.assertTrue(remaining) + lu.assertEquals(err.code, "cleanup_failed") + lu.assertEquals(err.cause.code, "body_failure") + lu.assertEquals(err.errors[1].code, "deferred_cleanup") + lu.assertEquals(err.runtime_errors[2].cause.code, "transport_cleanup") + lu.assertEquals(rt:stats().deferred, 0) +end + return tests diff --git a/tests/unit/server.lua b/tests/unit/server.lua index 5b2d5000..b1f5be2d 100644 --- a/tests/unit/server.lua +++ b/tests/unit/server.lua @@ -6,8 +6,25 @@ local identity = require("libtmux._internal.identity") local fields = require("libtmux._internal.fields") local M = {} -local function fixture(body) +local function fixture(body, client_environment) local driver = drivers.new() + client_environment = client_environment or {} + driver.uv = { + os_environ = function() + return client_environment + end, + getuid = function() + return 1000 + end, + fs_stat = function(path) + if path == "/usr/bin/tmux" then + return { type = "file" } + end + end, + fs_access = function(path) + return path == "/usr/bin/tmux" + end, + } local rt = runtimes.new(driver, { max_active = 1 }) local state = { calls = {}, binds = 0 } local generation = assert(identity.generation({ @@ -129,6 +146,52 @@ local function connect(rt) return assert(rt:connect({ binary = "/bin/tmux", socket_path = "/owned/socket" }):await()) end +function M.test_ordinary_connect_selects_and_captures_environment_path() + local environment = { + PATH = "/usr/local/bin:/usr/bin:/bin", + LIBTMUX_SOCKET_PATH = "/owned/selected.sock", + LIBTMUX_SOCKET_NAME = "../ignored", + TMUX = "malformed-but-ignored", + TMUX_PANE = "%9", + KEEP = "before", + } + fixture(function(rt, state) + local request = rt:connect() + environment.LIBTMUX_SOCKET_PATH = "/owned/changed.sock" + environment.KEEP = "after" + local server, err = request:await() + t.assertNil(err) + t.assertNotNil(server) + t.assertEquals(state.options.socket, "/owned/selected.sock") + t.assertEquals(state.options.binary, "/usr/bin/tmux") + t.assertNotNil(table.concat(state.options.env, "\n"):find("KEEP=before", 1, true)) + for _, entry in ipairs(state.options.env) do + t.assertFalse(entry:match("^TMUX=") or entry:match("^TMUX_PANE=") or false) + end + t.assertEquals(environment.TMUX, "malformed-but-ignored") + t.assertEquals(environment.TMUX_PANE, "%9") + assert(server:close():await()) + end, environment) +end + +function M.test_explicit_path_ignores_invalid_environment_selectors() + fixture(function(rt, state) + local server, err = rt:connect({ + binary = "/bin/tmux", + socket_path = "/owned/explicit.sock", + }):await() + t.assertNil(err) + t.assertNotNil(server) + t.assertEquals(state.options.socket, "/owned/explicit.sock") + assert(server:close():await()) + end, { + LIBTMUX_SOCKET_PATH = "relative", + LIBTMUX_SOCKET_NAME = "../invalid", + TMUX = "invalid", + TMUX_TMPDIR = "relative", + }) +end + function M.test_connection_copies_options_and_invalid_snapshot_dispatches_nothing() fixture(function(rt, state) t.assertEquals(type(rt.connect), "function", "public connection is missing")