Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ release that first shipped the module.

### Documented

- **`WaitAndCancel` shows what survives a `Pane.run` timeout.** The example
verifies a late completion receipt and a separate cooperative shutdown
receipt from a worker that reaps its detached helper. (#129, #265)


- **The Kotlin and Scala quick starts now run as standalone programs.** Each
includes its build file and starts a private tmux session using the
published libraries. (#203)
Expand Down
37 changes: 37 additions & 0 deletions docs/guide/concurrency.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,43 @@ blindly. [Failures, telemetry, and pane input](operating-a-service.md) has the w
rule, and the observer that reports every call's certainty on the thread that
made it.

## A wait deadline and a worker shutdown

[`WaitAndCancel`](../../examples/src/main/java/io/github/libtmux/examples/api/java/WaitAndCancel.java)
runs two workers on a private server and checks their receipts. Use JDK 25 or
newer, tmux 3.3a or newer, and Python 3 on `PATH`.

```console
$ ./gradlew :libtmux:jar
```

Run the complete source file from the repository root. Replace `<version>` with
the version in the JAR filename built by Gradle.

```console
$ java -cp libtmux/build/libs/libtmux-<version>.jar \
examples/src/main/java/io/github/libtmux/examples/api/java/WaitAndCancel.java
```

1. A shell command writes a start receipt and waits for a release file.
`Pane.run` reaches its deadline with `TIMED_OUT` and an empty exit status.
The example checks that the completion receipt is still absent.
2. The caller creates the release file and the same command writes its
completion receipt. The caller can keep working with the pane.
3. A separate worker starts a helper in its own process session, records the
helper's PID, and waits for a stop request. The caller checks that the
helper is alive before sending the request. The worker terminates and
reaps the helper before writing its PID to the shutdown receipt. The
caller also checks that the exact helper process exited.

The caller registers cleanup before starting the worker. The worker installs
signal handlers and records that it started before it can detach the helper.
A stop request that arrives during startup is therefore still handled.

Use a worker-owned shutdown request and a bounded wait for its receipt before
tearing down the pane or server. Closing either ends the terminal. A helper in
a separate process session can continue until its worker stops it.

## One writer per pane

Typing, pasting, and a shell run share one screen. `sendKeys`, `sendLiteral`,
Expand Down
6 changes: 6 additions & 0 deletions examples/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ Run the executable contract tests from the repository root:
$ ./gradlew :examples:test --tests '*ApiProgramsTest'
```

[WaitAndCancel](../src/main/java/io/github/libtmux/examples/api/java/WaitAndCancel.java)
shows a Java command that continues after its wait deadline and a worker that
reaps a detached helper. It requires Python 3 on PATH. See
[the concurrency guide](../../docs/guide/concurrency.md#a-wait-deadline-and-a-worker-shutdown)
for the standalone command and what each receipt proves.

## Server ownership

Each program starts its own private tmux server with `Server.start`, in a
Expand Down
14 changes: 14 additions & 0 deletions examples/api/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,20 @@
"expectedOutput": "api-keys\napi-line\n",
"path": "src/main/java/Capture.java"
},
{
"id": "java-WaitAndCancel",
"variant": "java",
"language": "java",
"description": "Observe a command timeout and verify a worker reaped its detached helper.",
"sourceFile": "examples/src/main/java/io/github/libtmux/examples/api/java/WaitAndCancel.java",
"mainClass": "io.github.libtmux.examples.api.java.WaitAndCancel",
"targets": [
"io.github.libtmux.Pane.run",
"io.github.libtmux.Server.start"
],
"expectedOutput": "timed out with no exit status while the worker waited\nthe same worker completed after release\nthe worker reaped its detached helper\n",
"path": "src/main/java/WaitAndCancel.java"
},
{
"id": "kotlin-Connect",
"variant": "kotlin",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package io.github.libtmux.examples.api.java;

import io.github.libtmux.PaneRun;
import io.github.libtmux.Server;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/** Observe a timeout, then request cooperative shutdown of a detached helper. */
public final class WaitAndCancel {
private static final Duration DEADLINE = Duration.ofSeconds(10);

private WaitAndCancel() {}

public static void main(String[] args) throws Exception {
Path root = Path.of("/tmp/libtmux-java-dev");
Files.createDirectories(root);
Path gates = Files.createTempDirectory(root, "cancel-");
try {
Server server = Server.start();
try (AutoCloseable _ = () -> finish(server)) {
observeTimeout(server, gates);
stopDetachedHelper(server, gates);
}
} finally {
for (String marker :
new String[] {"started", "release", "complete", "worker", "helper", "stop", "reaped"}) {
Files.deleteIfExists(gates.resolve(marker));
}
Files.deleteIfExists(gates);
}
}

private static void observeTimeout(Server server, Path gates) throws Exception {
var pane = server.newSession(spec -> spec.running("/bin/sh").env("GATES", gates.toString()))
.activePane()
.orElseThrow();
PaneRun result = pane.run(
"printf 'started\\n' > \"$GATES/started\"; "
+ "while [ ! -f \"$GATES/release\" ]; do sleep 0.02; done; "
+ "printf 'complete\\n' > \"$GATES/complete\"",
Duration.ofSeconds(1));
Path completion = gates.resolve("complete");
if (result.outcome() != PaneRun.Outcome.TIMED_OUT
|| result.exitStatus().isPresent()
|| !Files.exists(gates.resolve("started"))
|| Files.exists(completion)) {
throw new IllegalStateException("expected a timeout while the worker was still at its gate: " + result);
}
System.out.println("timed out with no exit status while the worker waited");

Files.createFile(gates.resolve("release"));
awaitFile(completion, "complete\n");
System.out.println("the same worker completed after release");
}

private static void stopDetachedHelper(Server server, Path gates) throws Exception {
var worker = """
from pathlib import Path
import os, signal, subprocess, sys, time

stopping = False

def request_stop(signum, frame):
global stopping
stopping = True

for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM):
signal.signal(sig, request_stop)

gates = Path(sys.argv[1])
(gates / 'worker').touch()
child = None
try:
if not stopping and not (gates / 'stop').exists():
child = subprocess.Popen([sys.executable, '-c',
'import time; time.sleep(20)'],
start_new_session=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
assert os.getsid(child.pid) == child.pid
(gates / 'helper').write_text(f'{child.pid}\\n')
deadline = time.monotonic() + 12
while not stopping and not (gates / 'stop').exists():
if time.monotonic() >= deadline:
raise TimeoutError('no stop request')
time.sleep(.02)
finally:
if child is not None:
child.terminate()
try:
child.wait(timeout=2)
except subprocess.TimeoutExpired:
child.kill()
child.wait(timeout=2)
(gates / 'reaped').write_text(f'{child.pid if child else 0}\\n')
""";
Path stop = gates.resolve("stop");
Path reaped = gates.resolve("reaped");
try (AutoCloseable _ = () -> finish(() -> {
Files.writeString(stop, "");
if (Files.exists(gates.resolve("worker"))) awaitFile(reaped, "");
})) {
server.newSession(spec -> spec.running("python3", "-c", worker, gates.toString()));
long pid = Long.parseLong(awaitFile(gates.resolve("helper"), "").strip());
ProcessHandle helper =
ProcessHandle.of(pid).filter(ProcessHandle::isAlive).orElseThrow();
Files.writeString(stop, "");
awaitFile(reaped, pid + "\n");
helper.onExit().get(DEADLINE.toSeconds(), TimeUnit.SECONDS);
System.out.println("the worker reaped its detached helper");
}
}

private static void finish(AutoCloseable cleanup) throws Exception {
boolean interrupted = Thread.interrupted();
try {
cleanup.close();
} finally {
if (interrupted) Thread.currentThread().interrupt();
}
}

private static String awaitFile(Path path, String expected) throws Exception {
long expires = System.nanoTime() + DEADLINE.toNanos();
while (System.nanoTime() < expires) {
if (Files.exists(path)) {
String contents = Files.readString(path);
if (expected.isEmpty() ? contents.endsWith("\n") : expected.equals(contents)) return contents;
}
Thread.sleep(20);
}
throw new IllegalStateException("missing receipt " + path.getFileName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ void manifestCoversEveryWholeProgramAndSetupFile() throws Exception {
expected.add(variant + "-" + program);
}
}
expected.add("java-WaitAndCancel");
Set<String> actual = new HashSet<>();
Set<String> paths = new HashSet<>();
for (JsonNode program : programs().toList()) {
Expand Down
Loading