diff --git a/CHANGES.md b/CHANGES.md index 460ce19..7982dde 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -61,6 +61,8 @@ Notable changes to `libtmux`. A named slot no longer blocks reads of numeric entries. (#139) - Control: When a layout change closes a pane watch, the diagnostic tells callers to open a fresh watch on the live observation. (#148) +- `Observation:watch_pane_lines` reads complete lines with an optional reply + prefix and a single deadline across intervening output. ## 0.1.1-1 (2026-11-01) diff --git a/README.md b/README.md index e6cfba5..e00839a 100644 --- a/README.md +++ b/README.md @@ -701,6 +701,10 @@ Each event carries the pane's bytes and a sequence number. A slow reader loses events: the watch ends with `observation_gap` instead of dropping them silently. +For a program that answers in lines, open `observation:watch_pane_lines(pane)`. +The [calculator example](docs/control.md#wait-for-a-result-line) waits five +seconds for a line starting with `result=`, even while the pane prints progress. + More: [observing a session](docs/control.md). ## Use it from Neovim diff --git a/docs/control.md b/docs/control.md index e9c9a22..305a6e4 100644 --- a/docs/control.md +++ b/docs/control.md @@ -24,6 +24,8 @@ endpoint owns at most eight observation clients. The observation offers: - `watch_pane(pane, options)`: a ready pane-output watch. +- `watch_pane_lines(pane, options)`: a ready watch for complete lines from a + pane. - `watch_notifications(options)`: a ready notification watch that keeps unknown events and raw lines. - `subscribe_format(pane, field_names, options)`: a typed format watch over @@ -104,6 +106,55 @@ Event fields: other field behavior show in the values. Closing a format watch unregisters it. +## Wait for a result line + +Open a line watch before sending the request. Give the read a literal reply +prefix and a timeout in milliseconds. + + + +```lua + local lines = must(observation:watch_pane_lines(pane):await()) + must(pane:send_text("sum 19 23"):await()) + must(pane:send_keys({ "Enter" }):await()) + local line, err = lines:next({ prefix = "result=", timeout = 5000 }):await() +``` + +The [example](../examples/api/read_pane_line.lua) runs a calculator in a +private server and prints `result=42`. The terminal may echo the request +and the app may print progress lines. Choose a prefix the app reserves for +replies. + +```console +$ lua examples/api/read_pane_line.lua +``` + +- `lines:next()` returns a Request for the next line in order. It joins + output across events and removes the LF and one preceding CR, if present. + Empty lines return an empty string. Other bytes remain as received. +- The first line starts at the first byte received by the watch. If it + opens while a line is being printed, that line can start mid-record. +- With `prefix`, a read consumes earlier lines until it finds a match. + Chatter uses the same deadline. Use `timeout` from submission or an + absolute monotonic `deadline`. With neither option it waits until a + matching line or a closed watch. +- A read that times out returns `deadline_exceeded`. A timeout or + cancellation keeps the current partial line and any unread lines for + the next call. Lines already skipped by a prefix stay consumed. +- One read may be pending per line watch. A second returns + `concurrent_read`. A separate `watch_pane` on the same pane has its own + queue. Closing the line watch normally returns `nil, nil` to its reader. + +Line watches allow 64 KiB before each LF, including a CR +(`max_line_bytes`). They queue at most 1,024 framed lines (`max_lines`) +and 1 MiB total (`max_bytes`), including input chunks held during framing, +partial lines and buffer overhead. + +The runtime dispatches framing and prefix searches in slices. A long line +gets a fresh slice when its fragments must be joined into one Lua string. +Exceeding a watch's buffer limit or losing coverage closes it with +`observation_gap` and discards its buffered output. + ## Bounds and ownership Defaults: @@ -118,10 +169,10 @@ Defaults: - Each claim, shared attachment and public watch takes one runtime resource slot. The runtime allows 128 in total. Runtime byte and logical-request limits also apply, and watch bytes include event metadata. -- Overflow closes the affected watch with `observation_gap`, and the partial - result reports the discarded event count and decoded pane bytes. Other - watches and the shared reader continue. tmux's `%pause` also breaks pane - continuity. +- Overflow closes the affected watch with `observation_gap`. On an event + watch, the partial result reports the discarded event count and decoded + pane bytes. Other watches and the shared reader continue. tmux's `%pause` + also breaks pane continuity. - There is no silent drop, no output coalescing, and no claim that tmux pause is lossless backpressure. - The reader parses bounded slices whether or not watches are consumed. diff --git a/examples/api/README.md b/examples/api/README.md index 8fb7f91..c28dda0 100644 --- a/examples/api/README.md +++ b/examples/api/README.md @@ -41,6 +41,7 @@ to select a different build. | [query.lua](query.lua) | Select sessions by name | `matched: demo` | | [explain.lua](explain.lua) | Show what a pane query runs in tmux and what stays local | Two plans, `never` and `auto` | | [group.lua](group.lua) | Create a session and two windows in one tmux call | `windows: main, build, test` | +| [read_pane_line.lua](read_pane_line.lua) | Wait for a complete `result=` line (tmux 3.7 or newer) | `result=42` | | [send_keys.lua](send_keys.lua) | Send text and press Enter | `lua input ready` | | [capture.lua](capture.lua) | Read a completed command's output | `lua capture ready` | | [wait_for_text.lua](wait_for_text.lua) | Wait for text on the visible screen | `lua wait ready` | diff --git a/examples/api/manifest.json b/examples/api/manifest.json index 60d3660..2533fcf 100644 --- a/examples/api/manifest.json +++ b/examples/api/manifest.json @@ -123,6 +123,17 @@ "description": "Find sessions by name with a live query and inspect its captured rows.", "stdout": "matched: demo\n" }, + { + "id": "read_pane_line", + "symbols": [ + "libtmux.Observation:watch_pane_lines", + "libtmux.LineWatch:next" + ], + "file": "examples/api/read_pane_line.lua", + "description": "Send a request to a pane and wait five seconds for a complete result line.", + "min_tmux": "3.7", + "stdout": "result=42\n" + }, { "id": "send_keys", "symbols": [ diff --git a/examples/api/read_pane_line.lua b/examples/api/read_pane_line.lua new file mode 100644 index 0000000..93be718 --- /dev/null +++ b/examples/api/read_pane_line.lua @@ -0,0 +1,45 @@ +local adapter = require("libtmux.runtime.luv") +---@diagnostic disable-next-line: different-requires +local uv = require("luv") + +if arg[1] == "--worker" then + io.stdout:setvbuf("no") + local a, b = assert(io.read("*l")):match("^sum (%d+) (%d+)$") + assert(a and b, "expected sum and two integers") + local sum = assert(tonumber(a)) + assert(tonumber(b)) + io.write("working\n") + io.write("result=", tostring(sum), "\n") + for _ in io.lines() do + end + return +end + +local function must(value, err) + if err ~= nil then + error(tostring(err), 0) + end + return assert(value) +end + +local binary = os.getenv("TMUX_BIN") +local script = assert(uv.fs_realpath(arg[0])) +local reply = must(adapter.run(function(runtime) + local owned = must(runtime:start_server({ binary = binary }):await()) + local created = must(owned.server + :new_session({ + name = "calc", + argv = { assert(uv.exepath()), script, "--worker" }, + }) + :await()) + local pane = created.pane + local observation = must(owned.server:observe(created.session):await()) + local lines = must(observation:watch_pane_lines(pane):await()) + must(pane:send_text("sum 19 23"):await()) + must(pane:send_keys({ "Enter" }):await()) + local line, err = lines:next({ prefix = "result=", timeout = 5000 }):await() + must(observation:close():await()) + must(owned:stop():await()) + return line, err +end)) +assert(reply == "result=42", reply) +print(reply) diff --git a/lua/libtmux/_internal/control.lua b/lua/libtmux/_internal/control.lua index 049db9e..d4d48d6 100644 --- a/lua/libtmux/_internal/control.lua +++ b/lua/libtmux/_internal/control.lua @@ -9,6 +9,9 @@ local connections, watches = local pane_projection = assert(metadata.projection("pane", "3.3a", { "id", "window_id" })) local defaults = { max_bytes = 4194304, max_pending = 128, max_watches = 128, timeout = 750 } local watch_defaults = { max_bytes = 1048576, max_events = 1024 } +local line_defaults = { max_bytes = 1048576, max_lines = 1024, max_line_bytes = 65536 } +local fragment_overhead = 8 +local line_work_items, line_work_bytes = 64, 65536 local terminate, pump, housekeeping local function failure(code, message, effect, cause, partial) @@ -104,6 +107,24 @@ local function release(state, amount) end end +local function enqueue(queue, item) + if queue.last then + queue.last.next = item + else + queue.first = item + end + queue.last, queue.count = item, queue.count + 1 +end + +local function dequeue(queue) + local item = queue.first + queue.first, queue.count = item.next, queue.count - 1 + if not queue.first then + queue.last = nil + end + return item +end + local function drop_watch(watch, err) if watch.closed then return @@ -111,7 +132,8 @@ local function drop_watch(watch, err) watch.closed, watch.error = true, err watch.owner.watches[watch] = nil watch.owner.watch_count = watch.owner.watch_count - 1 - watch.queue = {} + watch.owner.runtime:_cancel_work(watch.line_work) + watch.line_work, watch.queue, watch.input, watch.fragments = nil, nil, nil, nil release(watch.owner, watch.bytes) watch.bytes, watch.data_bytes = 0, 0 if watch.projection_bytes then @@ -157,43 +179,191 @@ local function drop_watch(watch, err) end end -local function deliver(watch, event) - if watch.closed then - return - end - local pending = watch.waiter - if pending and pending.request:_expire_if_due() then - pending = nil - end - local state, bytes = watch.owner, cost(event) - local data_bytes = #(event.data or "") +local function retain_output(watch, bytes, data_bytes, complete) + local limits = watch.limits + local items = watch.queue.count + (complete and 1 or 0) local retained, err - if watch.bytes + bytes <= watch.limits.max_bytes and #watch.queue < watch.limits.max_events then - retained, err = state.budget:retain(bytes) + if + watch.bytes + bytes <= limits.max_bytes + and items <= (limits.max_lines or limits.max_events) + then + retained, err = watch.owner.budget:retain(bytes) end if not retained then + local partial = { dropped_bytes = watch.data_bytes + data_bytes } + partial[limits.max_lines and "dropped_lines" or "dropped_events"] = items drop_watch( watch, - failure("observation_gap", "observation buffer limit reached", "unknown", err, { - dropped_bytes = watch.data_bytes + data_bytes, - dropped_events = #watch.queue + 1, - }) + failure("observation_gap", "observation buffer limit reached", "unknown", err, partial) ) + end + return retained +end + +local function settle_read(watch, pending, value, bytes) + local state = watch.owner + local transferred, err = state.budget:transfer(pending.request, bytes) + if transferred then + pending.settle(value) + else + release(state, bytes) + pending.settle(nil, err) + end + pending.retire() +end + +local function pending_read(watch) + local pending = watch.waiter + if pending and not pending.request:_expire_if_due() then + return pending + end +end + +local function matches(line, prefix) + return prefix == nil or line:sub(1, #prefix) == prefix +end + +local function deliver(watch, value, bytes, data_bytes) + if watch.closed then + return + end + local pending = pending_read(watch) + if pending and not matches(value, pending.prefix) then + return + end + if not retain_output(watch, bytes, data_bytes, true) then return end if pending then watch.waiter = nil - local transferred, transfer_error = state.budget:transfer(pending.request, bytes) - if transferred then - pending.settle(event) + settle_read(watch, pending, value, bytes) + else + enqueue(watch.queue, { value = value, bytes = bytes, data_bytes = data_bytes }) + watch.bytes, watch.data_bytes = watch.bytes + bytes, watch.data_bytes + data_bytes + end +end + +local function read_output(watch, pending) + local item = dequeue(watch.queue) + watch.bytes, watch.data_bytes = watch.bytes - item.bytes, watch.data_bytes - item.data_bytes + if matches(item.value, pending.prefix) then + watch.waiter = nil + settle_read(watch, pending, item.value, item.bytes) + else + release(watch.owner, item.bytes) + end + return item.bytes +end + +local function slice_full(spent, bytes) + return spent > 0 and spent + bytes > line_work_bytes +end + +local function frame_line(watch, input, spent) + local data, start = input.value, input.offset + local newline = data:find("\n", start, true) + local last = newline and newline - 1 or #data + local size = last - start + 1 + if watch.line_size + size > watch.limits.max_line_bytes then + drop_watch(watch, failure("observation_gap", "pane line exceeds max_line_bytes", "unknown")) + return 0 + end + + local consumed = (newline or last) - start + 1 + local work = consumed + (newline and watch.line_size + size or 0) + -- Joining a long line returns one Lua string, so give it a fresh slice. + if slice_full(spent, work) then + return nil + end + input.offset = start + consumed + watch.data_bytes = watch.data_bytes - consumed + -- Keep the whole chunk charged until the watch can release its string. + if input.offset > #data then + dequeue(watch.input) + watch.bytes = watch.bytes - input.bytes + release(watch.owner, input.bytes) + end + + local fragments = watch.fragments + if newline then + local line = data:sub(start, last) + if #fragments > 0 then + local retained = watch.line_size + fragment_overhead * #fragments + fragments[#fragments + 1] = line + line = table.concat(fragments) + watch.bytes = watch.bytes - retained + watch.data_bytes = watch.data_bytes - watch.line_size + watch.fragments, watch.line_size = {}, 0 + release(watch.owner, retained) + end + if line:sub(-1) == "\r" then + line = line:sub(1, -2) + end + deliver(watch, line, #line + 32, #line) + elseif retain_output(watch, size + fragment_overhead, size, false) then + fragments[#fragments + 1] = data:sub(start, last) + watch.line_size = watch.line_size + size + watch.bytes = watch.bytes + size + fragment_overhead + watch.data_bytes = watch.data_bytes + size + end + return work +end + +local function drain_line_watch(watch) + local bytes = 0 + for _ = 1, line_work_items do + if watch.closed or bytes >= line_work_bytes then + return + end + local pending = watch.queue.first and pending_read(watch) + if pending then + if slice_full(bytes, watch.queue.first.bytes) then + return + end + bytes = bytes + read_output(watch, pending) + elseif watch.input.first then + local work = frame_line(watch, watch.input.first, bytes) + if not work then + return + end + bytes = bytes + work else - release(state, bytes) - pending.settle(nil, transfer_error) + return end - pending.retire() + end +end + +-- A line watch owns its input and at most one queued slice of framing or filtering. +local function schedule_line_watch(watch) + if + watch.closed + or watch.line_work + or not (watch.input.first or (watch.waiter and watch.queue.first)) + then + return + end + local runtime = watch.owner.runtime + local ok, work = pcall(runtime._enqueue, runtime, function() + watch.line_work = nil + drain_line_watch(watch) + schedule_line_watch(watch) + end) + if ok then + watch.line_work = work else - watch.queue[#watch.queue + 1] = { event = event, bytes = bytes, data_bytes = data_bytes } - watch.bytes, watch.data_bytes = watch.bytes + bytes, watch.data_bytes + data_bytes + drop_watch( + watch, + failure("observation_gap", "could not schedule pane line work", "unknown", work) + ) + end +end + +local function receive_line_data(watch, data) + local bytes = #data + 32 + if #data > 0 and retain_output(watch, bytes, #data, false) then + enqueue(watch.input, { value = data, bytes = bytes, offset = 1 }) + watch.bytes, watch.data_bytes = watch.bytes + bytes, watch.data_bytes + #data + schedule_line_watch(watch) end end @@ -518,7 +688,7 @@ local function event(state, item) ) ) else - deliver(watch, { + local value_event = { kind = "format", generation = state.generation, server_generation = state.server_generation, @@ -528,12 +698,15 @@ local function event(state, item) window_id = window, index = numeric_index, value = rows[1], - }) + } + deliver(watch, value_event, cost(value_event), 0) end end end for watch in pairs(state.watches) do - if + if watch.input and item.pane == watch.pane and item.data then + receive_line_data(watch, item.data) + elseif (watch.pane and not watch.projection and item.pane == watch.pane and item.data) or watch.notifications then @@ -550,7 +723,7 @@ local function event(state, item) copy[key] = value end end - deliver(watch, copy) + deliver(watch, copy, cost(copy), #(copy.data or "")) end end end @@ -677,8 +850,8 @@ function Connection:coverage() } end -local function open_watch(state, pane, options, notifications, projection) - local limits, err = options_copy(options, watch_defaults) +local function open_watch(state, pane, options, notifications, projection, lines) + local limits, err = M.prepare_watch(options, lines) if not limits then return rejected(state.runtime, err) end @@ -710,9 +883,12 @@ local function open_watch(state, pane, options, notifications, projection) limits = limits, pane = pane, notifications = notifications, - queue = {}, + queue = { count = 0 }, + input = lines and { count = 0 } or nil, bytes = 0, data_bytes = 0, + fragments = lines and {} or nil, + line_size = 0, projection = projection, projection_bytes = projection_bytes, } @@ -771,6 +947,17 @@ function Connection:watch_pane(pane, options) return open_watch(assert(connections[self], "invalid control connection"), pane, options, false) end +function Connection:watch_pane_lines(pane, options) + return open_watch( + assert(connections[self], "invalid control connection"), + pane, + options, + false, + nil, + true + ) +end + function Connection:watch_notifications(options) return open_watch(assert(connections[self], "invalid control connection"), nil, options, true) end @@ -792,55 +979,64 @@ end function Watch:next(options) local watch = assert(watches[self], "invalid watch") + local runtime = watch.owner.runtime + local lines = watch.limits.max_line_bytes ~= nil if options == nil then options = {} end if type(options) ~= "table" or getmetatable(options) ~= nil then return rejected( - watch.owner.runtime, + runtime, failure("invalid_argument", "watch read options must be a plain table") ) end for key in next, options do - if key ~= "timeout" and key ~= "deadline" then - return rejected( - watch.owner.runtime, - failure("invalid_argument", "unknown watch read option") - ) + if key ~= "timeout" and key ~= "deadline" and not (lines and key == "prefix") then + return rejected(runtime, failure("invalid_argument", "unknown watch read option")) end end - return watch.owner.runtime:_logical_request({ - timeout = rawget(options, "timeout"), - deadline = rawget(options, "deadline"), - operation = "watch.next", + local prefix = options.prefix + if prefix ~= nil and (type(prefix) ~= "string" or #prefix > watch.limits.max_line_bytes) then + return rejected( + runtime, + failure("invalid_argument", "line prefix must be a bounded string") + ) + end + return runtime:_logical_request({ + timeout = options.timeout, + deadline = options.deadline, + bytes = prefix and #prefix or 0, + operation = lines and "line_watch.next" or "watch.next", effect = "not_sent", start = function(settle, retire, request) if watch.waiter then settle(nil, failure("concurrent_read", "watch already has a pending read")) retire() - elseif #watch.queue > 0 then - local item = table.remove(watch.queue, 1) - watch.bytes, watch.data_bytes = - watch.bytes - item.bytes, watch.data_bytes - item.data_bytes - local transferred, err = watch.owner.budget:transfer(request, item.bytes) - if transferred then - settle(item.event) - else - release(watch.owner, item.bytes) - settle(nil, err) - end - retire() - elseif watch.closed then + return + end + if watch.closed then settle(nil, watch.error) retire() - else - watch.waiter = { settle = settle, retire = retire, request = request } - return function() - if watch.waiter and watch.waiter.request == request then - watch.waiter = nil - end - retire() + return + end + local pending = { + settle = settle, + retire = retire, + request = request, + prefix = prefix, + } + watch.waiter = pending + if lines then + schedule_line_watch(watch) + elseif watch.queue.first then + read_output(watch, pending) + return + end + return function() + if watch.waiter == pending then + watch.waiter = nil end + retire() end end, }) @@ -869,8 +1065,8 @@ function M.prepare(options) return options_copy(options, defaults) end -function M.prepare_watch(options) - return options_copy(options, watch_defaults) +function M.prepare_watch(options, lines) + return options_copy(options, lines and line_defaults or watch_defaults) end function M.open(runtime, bound, options) diff --git a/lua/libtmux/_internal/observation.lua b/lua/libtmux/_internal/observation.lua index 8815304..0925049 100644 --- a/lua/libtmux/_internal/observation.lua +++ b/lua/libtmux/_internal/observation.lua @@ -213,7 +213,7 @@ function M.open(state, session, options) return request end -local function watch_result(claim, native) +local function watch_result(claim, native, lines) local state = { native = native, owner = claim } local err state.lease, err = claim.server.runtime:_resource(function(done) @@ -228,7 +228,8 @@ local function watch_result(claim, native) if not state.lease then return nil, err end - return opaque(watches, state, Watch, "libtmux.Watch"), nil, state + local label = lines and "libtmux.LineWatch" or "libtmux.Watch" + return opaque(watches, state, Watch, label), nil, state end local function open_watch(claim, method, pane, names, options) @@ -245,7 +246,8 @@ local function open_watch(claim, method, pane, names, options) elseif method ~= "watch_notifications" then return rejected(rt, failure("invalid_target", "pane observation requires a pane handle")) end - options, err = control.prepare_watch(options) + local lines = method == "watch_pane_lines" + options, err = control.prepare_watch(options, lines) if not options then return rejected(rt, err) end @@ -273,6 +275,8 @@ local function open_watch(claim, method, pane, names, options) opening = connection:watch_notifications(options) elseif method == "subscribe_format" then opening = connection:subscribe_format(ref.id, names, options) + elseif lines then + opening = connection:watch_pane_lines(ref.id, options) else opening = connection:watch_pane(ref.id, options) end @@ -289,7 +293,7 @@ local function open_watch(claim, method, pane, names, options) return nil, cause end local object - object, cause, item.watch = watch_result(claim, native) + object, cause, item.watch = watch_result(claim, native, lines) operation:_set_effect("completed") return object, cause end, { operation = "observe.watch", effect = "not_sent" }) @@ -337,6 +341,10 @@ function Observation:watch_pane(pane, options) return open_watch(assert(observations[self]), "watch_pane", pane, nil, options) end +function Observation:watch_pane_lines(pane, options) + return open_watch(assert(observations[self]), "watch_pane_lines", pane, nil, options) +end + function Observation:watch_notifications(options) return open_watch(assert(observations[self]), "watch_notifications", nil, nil, options) end @@ -375,6 +383,16 @@ end ---@field max_bytes? integer Retained event bytes; default 1048576. ---@field max_events? integer Retained events; default 1024. +---@class libtmux.LineWatchOptions +---@field max_line_bytes? integer Bytes before LF, including CR; default 65536. +---@field max_bytes? integer Retained input, line and fragment bytes with overhead; default 1048576. +---@field max_lines? integer Queued framed lines; default 1024. + +---@class libtmux.LineReadOptions +---@field prefix? string Literal byte prefix. Earlier lines are discarded. +---@field timeout? number Milliseconds from submission. +---@field deadline? number Absolute monotonic milliseconds, used when timeout is absent. + ---@class libtmux.ObservationCoverage ---@field session_id string ---@field panes string[] @@ -384,6 +402,8 @@ end ---@class libtmux.Observation ---@field watch_pane fun(self:libtmux.Observation,pane:libtmux.Pane, --- options?:libtmux.WatchOptions):libtmux.Request +---@field watch_pane_lines fun(self:libtmux.Observation,pane:libtmux.Pane, +--- options?:libtmux.LineWatchOptions):libtmux.Request ---@field watch_notifications fun(self:libtmux.Observation, --- options?:libtmux.WatchOptions):libtmux.Request ---@field subscribe_format fun(self:libtmux.Observation,pane:libtmux.Pane, @@ -413,4 +433,8 @@ end --- libtmux.Request ---@field close fun(self:libtmux.Watch):libtmux.Request +---@class libtmux.LineWatch +---@field next fun(self:libtmux.LineWatch,options?:libtmux.LineReadOptions):libtmux.Request +---@field close fun(self:libtmux.LineWatch):libtmux.Request + return M diff --git a/scripts/docs/tests/test_api_examples.lua b/scripts/docs/tests/test_api_examples.lua index b254ba9..681ef83 100644 --- a/scripts/docs/tests/test_api_examples.lua +++ b/scripts/docs/tests/test_api_examples.lua @@ -15,6 +15,7 @@ for symbol in libtmux.Entity:snapshot libtmux.Window:rename libtmux.Server:explain_panes libtmux.Server:group libtmux.Server:observe libtmux.Observation:watch_pane libtmux.Watch:next libtmux.Observation:close + libtmux.Observation:watch_pane_lines libtmux.LineWatch:next libtmux.Pane:resize libtmux.Window:resize libtmux.Runtime:start_server libtmux.Runtime:with_server libtmux.OwnedServer.server libtmux.OwnedServer.socket_path libtmux.OwnedServer:stop libtmux.SnapshotSession.window_links @@ -68,7 +69,7 @@ end function M.test_complete_programs_cover_their_existing_targets() local loaded = api.load_examples(repo.root, TARGETS) - test.assertEquals(#loaded.examples, 20) + test.assertEquals(#loaded.examples, 21) local seen = {} for _, example in ipairs(loaded.examples) do for _, symbol in ipairs(example.symbols) do diff --git a/tests/integration/observation.lua b/tests/integration/observation.lua index 731c6ba..5e61ef9 100644 --- a/tests/integration/observation.lua +++ b/tests/integration/observation.lua @@ -42,7 +42,7 @@ local function check_deadlines(watch) end end -local function work(runtime) +local function handles(runtime) local server = assert(runtime :connect({ binary = assert(os.getenv("TMUX_BIN")), @@ -63,6 +63,11 @@ local function work(runtime) :await()) local session = assert(server:handle(snapshot, assert(snapshot.sessions:first()))) local pane = assert(server:handle(snapshot, assert(snapshot.panes:first()))) + return server, session, pane +end + +local function work(runtime) + local server, session, pane = handles(runtime) local first, second = server:observe(session), server:observe(session) local a, b = assert(first:await()), assert(second:await()) local generation = assert(a:coverage()).generation @@ -115,6 +120,43 @@ local function work(runtime) return "shared observation passed" end +local function read_reply(runtime) + local server, session, pane = handles(runtime) + assert(pane:respawn({ + kill = true, + argv = { + assert(os.getenv("LIBTMUX_TEST_LUA")), + assert(os.getenv("LIBTMUX_OUTPUT_SCRIPT")), + "reply", + }, + }):await()) + assert(pane:wait_for_text("READY", { timeout = 1500 }):await()) + local observation = assert(server:observe(session):await()) + local raw = assert(observation:watch_pane(pane, { max_bytes = 1024 }):await()) + local lines = assert(observation:watch_pane_lines(pane):await()) + assert(pane:send_text("sum 19 23"):await()) + assert(pane:send_keys({ "Enter" }):await()) + local deadline = now() + 1500 + local bytes = "" + repeat + bytes = bytes .. assert(raw:next({ deadline = deadline }):await()).data + until bytes:find("result=\195", 1, true) + assert(bytes:find("sum 19 23\r\n", 1, true), "expected terminal echo") + local reply, err = lines:next({ prefix = "result=", timeout = 50 }):await() + assert(reply == nil and err and err.code == "deadline_exceeded", tostring(err or reply)) + assert(pane:send_text("continue"):await()) + assert(pane:send_keys({ "Enter" }):await()) + reply = assert(lines:next({ prefix = "result=", timeout = 1500 }):await()) + assert(reply == "result=\195\169=42", reply) + assert(assert(lines:next({ timeout = 1500 }):await()) == "next line") + assert(observation:close():await()) + return "complete reply passed" +end + +if os.getenv("LIBTMUX_OBSERVATION_CASE") == "reply" then + work = read_reply +end + if host then adapter.start(work, function(value, err) if err then diff --git a/tests/integration/test_observation.lua b/tests/integration/test_observation.lua index ef11185..ba93ab6 100644 --- a/tests/integration/test_observation.lua +++ b/tests/integration/test_observation.lua @@ -1,5 +1,6 @@ -- Public session leases share a native client and preserve borrowed topology. local test = require("luaunit") +local child = require("tests.support.child") local fixture = require("tests.support.fixture") local repo = require("support.repo") local M = {} @@ -28,4 +29,38 @@ fixture.each_host(M, "watch_reads_validate_both_limits_and_remain_readable", fun run_case(host, "deadlines") end) +fixture.each_host(M, "read_complete_reply_after_a_partial_timeout", function(host) + fixture.with(function(f) + fixture.require_control(f) + local result = f:program(host, "observation", { + LIBTMUX_OBSERVATION_CASE = "reply", + LIBTMUX_OUTPUT_SCRIPT = repo.root .. "/tests/support/programs/output.lua", + }) + test.assertStrContains(result.stdout, "complete reply passed") + test.assertEquals(f:out("list-clients"), "") + end) +end) + +function M.test_result_example_reports_the_reply_or_required_tmux_release() + fixture.with(function(f) + local version = f:version() + local env = fixture.environment({ + TMUX_BIN = f.binary, + TMPDIR = assert(os.getenv("TMUX_TMPDIR")), + }) + local result = child.run({ fixture.lua(), "examples/api/read_pane_line.lua" }, { + cwd = repo.root, + env = env, + timeout = 6, + }) + if fixture.at_least(version, 3, 7) then + test.assertEquals(result.code, 0, result.stderr) + test.assertEquals(result.stdout, "result=42\n") + else + test.assertNotEquals(result.code, 0) + test.assertStrContains(result.stderr, "control observation requires tmux 3.7") + end + end) +end + return M diff --git a/tests/support/programs/output.lua b/tests/support/programs/output.lua index b14642f..7c123a2 100644 --- a/tests/support/programs/output.lua +++ b/tests/support/programs/output.lua @@ -6,6 +6,7 @@ -- decoder passes: NUL, 1, LF, CR, backslash, 255, "DONE" -- output.lua rows COUNT ROW TEXT prints COUNT lines of ROW, then TEXT, then stays -- output.lua wait TEXT TMUX SOCKET NAME prints TEXT, waits until NAME is signalled, exits 0 +-- output.lua reply reads two inputs and splits a reply between them local mode = ... local common = dofile(debug.getinfo(1, "S").source:match("^@(.*)/[^/]*$") .. "/common.lua") @@ -32,6 +33,15 @@ elseif mode == "wait" then local _, text, binary, socket, name = ... common.write(text) assert(common.run(binary, { "-N", "-S", socket, "wait-for", name }) == 0, "wait-for failed") +elseif mode == "reply" then + common.write("READY\n") + local a, b = assert(io.read("*l")):match("^sum (%d+) (%d+)$") + assert(a and b, "expected sum and two integers") + common.binary() + common.write("working\r\nresult=\195") + assert(common.read_until("\r") == "continue\r", "expected reply acknowledgement") + common.write(("\169=%d\r\nnext line\r\n"):format(tonumber(a) + tonumber(b))) + common.idle() else error("unknown mode " .. tostring(mode)) end diff --git a/tests/unit/control.lua b/tests/unit/control.lua index e78d887..16c0dfd 100644 --- a/tests/unit/control.lua +++ b/tests/unit/control.lua @@ -313,6 +313,316 @@ function M.test_pending_raw_read_expires_before_late_output_overflows_the_watch( t.assertEquals(f.runtime:stats().bytes, 0) end +local function watch_lines(state, options) + t.assertNotNil(state.observer.watch_pane_lines, "public pane line watch is missing") + return assert(state.observer:watch_pane_lines(state.pane, options):await()) +end + +function M.test_pane_lines_span_events_and_leave_the_raw_watch_in_order() + local f = fixture(function(state) + local raw = assert(state.observer:watch_pane(state.pane):await()) + local lines = watch_lines(state, { max_line_bytes = 24 }) + local read = lines:next({ prefix = "result=", timeout = 100 }) + state.uv.pipes[2].read( + nil, + "%output %0 request\\015\\012working\\012result=\\303\n" + .. "%output %1 result=other\\012\n" + .. "%extended-output %0 4 future : \\251\\015\\012next\\015row\\012\\012\n" + ) + t.assertEquals(assert(read:await()), "result=\195\169") + t.assertEquals(assert(lines:next():await()), "next\rrow") + t.assertEquals(assert(lines:next():await()), "") + local first, second = assert(raw:next():await()), assert(raw:next():await()) + t.assertEquals(first.data, "request\r\nworking\nresult=\195") + t.assertEquals(second.data, "\169\r\nnext\rrow\n\n") + t.assertTrue(first.sequence < second.sequence) + end, { max_logical = 1 }, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_deadline_spans_chatter_and_retains_a_partial_reply() + local f = fixture(function(state) + local lines = watch_lines(state) + state.read = lines:next({ prefix = "result=", timeout = 40 }) + local value, err = state.read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "deadline_exceeded") + state.retry = lines:next({ prefix = "result=", deadline = 60 }) + t.assertEquals(assert(state.retry:await()), "result=\195\169") + end, nil, true) + t.assertNotNil(f.read, tostring(select(2, f.root:result()))) + for _ = 1, 3 do + f.driver:advance(10) + f.uv.pipes[2].read(nil, "%output %0 still working\\012\n") + f.driver:drain() + t.assertFalse(f.read:is_settled()) + end + f.uv.pipes[2].read(nil, "%output %0 result=\\303\n") + f.driver:advance(10) + t.assertTrue(f.read:is_settled()) + t.assertFalse(assert(f.retry):is_settled()) + f.uv.pipes[2].read(nil, "%output %0 \\251\\015\\012\n") + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_completed_after_deadline_is_available_to_a_retry() + local f = fixture(function(state) + local lines = watch_lines(state) + state.read = lines:next({ deadline = 5 }) + local value, err = state.read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "deadline_exceeded") + t.assertEquals(assert(lines:next():await()), "late") + end, nil, true) + t.assertFalse(assert(f.read):is_settled()) + -- The pipe callback runs before the ready timer callback. + f.driver.time = 5 + f.uv.pipes[2].read(nil, "%output %0 late\\012\n") + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_read_checks_deadline_before_installing_a_waiter() + local f = fixture(function(state) + local lines = watch_lines(state) + local read = lines:next({ timeout = 5 }) + -- Dispatch starts this read before the host fires its due timer. + state.driver.time = 5 + local value, err = read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "deadline_exceeded") + state.uv.pipes[2].read(nil, "%output %0 next\\012\n") + t.assertEquals(assert(lines:next():await()), "next") + end, nil, true) + t.assertTrue(f.root:is_retired(), "expired line read installed a waiter") + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_already_queued_at_expiry_remains_available_to_retry() + local f = fixture(function(state) + local lines = watch_lines(state) + state.uv.pipes[2].read(nil, "%output %0 result=42\\012\n") + local read = lines:next({ prefix = "result=", deadline = 5 }) + state.driver.time = 5 + local value, err = read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "deadline_exceeded") + t.assertEquals(assert(lines:next():await()), "result=42") + end, { dispatch_budget = 1 }, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_waiter_checks_expiry_after_one_dispatch_turn() + local f = fixture(function(state) + local lines = watch_lines(state) + t.assertEquals(assert(lines:next():await()), "warmup") + state.read = lines:next({ prefix = "result=", deadline = 5 }) + local value, err = state.read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "deadline_exceeded") + t.assertEquals(assert(lines:next():await()), "result=42") + end, { dispatch_budget = 1 }, true) + f.uv.pipes[2].read(nil, "%output %0 warmup\\012result=42\\012\n") + t.assertTrue(f.driver:step()) + t.assertTrue(f.driver:step()) + t.assertFalse(assert(f.read):is_settled()) + t.assertTrue(f.driver:step()) -- The read starts and queues its scan. + f.driver.time = 5 -- The host has not dispatched the timer yet. + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_cancellation_leaves_the_partial_and_next_line_available() + local f = fixture(function(state) + local lines = watch_lines(state) + local pending = lines:next() + local value, err = lines:next():await() + t.assertNil(value) + t.assertEquals(assert(err).code, "concurrent_read") + + state.uv.pipes[2].read(nil, "%output %0 fir\n") + t.assertTrue(pending:cancel()) + value, err = pending:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "cancelled") + state.uv.pipes[2].read(nil, "%output %0 st\\012second\\012\n") + t.assertEquals(assert(lines:next():await()), "first") + t.assertEquals(assert(lines:next():await()), "second") + local ending = lines:next() + assert(lines:close():await()) + value, err = ending:await() + t.assertNil(value) + t.assertNil(err) + end, nil, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_overflow_closes_only_its_own_watch() + local f = fixture(function(state) + local raw = assert(state.observer:watch_pane(state.pane):await()) + local lines = watch_lines(state, { max_line_bytes = 4 }) + local read = lines:next() + state.uv.pipes[2].read(nil, "%output %0 1234\n") + state.uv.pipes[2].read(nil, "%output %0 5\\012\n") + local value, err = read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "observation_gap") + value, err = lines:next():await() + t.assertNil(value) + t.assertEquals(assert(err).code, "observation_gap") + t.assertEquals(assert(raw:next():await()).data, "1234") + t.assertEquals(assert(raw:next():await()).data, "5\n") + end, nil, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_watch_yields_before_joining_a_configured_long_line() + local part = ("x"):rep(20 * 1024) + local f = fixture(function(state) + local lines = watch_lines(state, { max_line_bytes = 96 * 1024 }) + state.read = lines:next({ prefix = "result=", timeout = 100 }) + local line = assert(state.read:await()) + t.assertTrue(line == "result=" .. part:rep(4), "long reply changed during framing") + end, { dispatch_budget = 1 }, true) + t.assertNotNil(f.read, tostring(select(2, f.root:result()))) + f.uv.pipes[2].read(nil, "%output %0 result=" .. part .. "\n") + f.uv.pipes[2].read(nil, "%output %0 " .. part .. "\n") + f.uv.pipes[2].read(nil, "%output %0 " .. part:rep(2) .. "\\012\n") + + local callback_ran + f.driver.defer(function() + callback_ran = true + end) + t.assertTrue(f.driver:step()) + t.assertFalse(f.read:is_settled(), "one slice joined a long line after framing its partials") + t.assertTrue(f.driver:step()) + t.assertTrue(callback_ran) + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_buffer_bounds_complete_lines_and_unterminated_bytes() + local f = fixture(function(state) + local queued = watch_lines(state, { max_lines = 1 }) + local partial = watch_lines(state, { max_bytes = 80 }) + state.uv.pipes[2].read(nil, "%output %0 a\\012b\\012\n") + local value, err = queued:next():await() + t.assertNil(value) + t.assertEquals(assert(err).code, "observation_gap") + t.assertEquals(err.partial.dropped_lines, 2) + t.assertEquals(assert(partial:next():await()), "a") + t.assertEquals(assert(partial:next():await()), "b") + state.uv.pipes[2].read(nil, "%output %0 " .. string.rep("x", 81) .. "\n") + value, err = partial:next():await() + t.assertNil(value) + t.assertEquals(assert(err).code, "observation_gap") + t.assertEquals(err.partial.dropped_bytes, 81) + end, nil, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_gap_discards_the_unterminated_suffix() + local f = fixture(function(state) + local lines = watch_lines(state) + local read = lines:next() + state.uv.pipes[2].read(nil, "%output %0 old:\n%pause %0\n") + local value, err = read:await() + t.assertNil(value) + t.assertEquals(assert(err).code, "observation_gap") + local reopened = watch_lines(state) + state.uv.pipes[2].read(nil, "%output %0 fresh\\012\n") + t.assertEquals(assert(reopened:next():await()), "fresh") + end, nil, true) + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_framing_yields_during_one_noisy_output_event() + local f = fixture(function(state) + local lines = watch_lines(state) + state.read = lines:next({ prefix = "result=", timeout = 100 }) + t.assertEquals(assert(state.read:await()), "result=42") + end, { dispatch_budget = 1 }, true) + f.uv.pipes[2].read(nil, "%output %0 " .. ("working\\012"):rep(512) .. "result=42\\012\n") + t.assertFalse(f.read:is_settled(), "the pipe callback processed the entire output event") + local callback_ran + f.driver.defer(function() + callback_ran = true + end) + t.assertTrue(f.driver:step()) + t.assertFalse(f.read:is_settled(), "one dispatch framed the entire output event") + t.assertTrue(f.driver:step()) + t.assertTrue(callback_ran) + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + +function M.test_pane_line_prefix_scan_yields_and_can_be_cancelled() + local f = fixture(function(state) + state.lines = watch_lines(state) + state.hold = state.runtime:_logical_request({ + start = function(_, retire) + return function() + retire() + end + end, + }) + state.hold:await() + end, { dispatch_budget = 1 }, true) + f.uv.pipes[2].read( + nil, + "%output %0 " .. ("working\\012"):rep(512) .. "result=42\\012following\\012\n" + ) + f.driver:drain() + local first = f.lines:next({ prefix = "result=", timeout = 100 }) + local callback_ran + f.driver.defer(function() + callback_ran = true + end) + t.assertTrue(f.driver:step()) + t.assertFalse(first:is_settled(), "one dispatch scanned all buffered lines") + t.assertTrue(f.driver:step()) + t.assertTrue(callback_ran) + t.assertTrue(f.driver:step()) + t.assertFalse(first:is_settled(), "one scan slice consumed all buffered lines") + t.assertTrue(first:cancel()) + local retry = f.lines:next({ prefix = "result=", timeout = 100 }) + f.driver:drain() + t.assertEquals(assert(retry:result()), "result=42") + local following = f.lines:next() + f.driver:drain() + t.assertEquals(assert(following:result()), "following") + f.hold:cancel() + f.driver:drain() + local _, err = f.root:result() + t.assertNil(err) + t.assertEquals(f.runtime:stats().resource_bytes, 0) +end + function M.test_live_opaque_results_keep_their_closed_state_after_collection() local function returned() local f = fixture(function(state)