Skip to content
Merged
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased

### Fixed

- An agent another app had just started, or a busy one, keeps its address
files: the SDK no longer removes them when its hello fails, so apps reach it.

## 0.16.1 (2026-11-19)

### Added
Expand Down
78 changes: 65 additions & 13 deletions tracepanel-core/src/main/java/dev/tracepanel/core/Agent.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package dev.tracepanel.core;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -15,6 +21,8 @@
*/
public final class Agent {
private static final long START_WAIT_MS = 1500;
// A bare connect to the address: an agent on this machine accepts at once.
private static final int PROBE_TIMEOUT_MS = 250;
// An agent that exited (idle, killed, a new build) is started again at once; one that couldn't start, after this.
private static final long RESTART_MS = 30_000;
private static final String IDLE_EXIT_S = "1800";
Expand Down Expand Up @@ -64,25 +72,64 @@ private boolean autoStart() {

/**
* Whether an agent runs for the project: one already does, or this starts it (RESTART_MS after a failure).
* `gone`: the one at its address didn't answer, and its addresses go before a new one starts.
* `gone`: the one at its address didn't take the app's hello, so whether it answers at all is asked first.
* Its addresses stay either way: they may be another process's agent's, starting or busy this very moment, and
* an agent that didn't exit cleanly leaves its own to the next one, which removes them while it holds the store's
* lock.
*/
public synchronized boolean ensure(boolean gone) {
if (!gone && !address().isEmpty()) return true;
if (gone && answers(address())) return true;
if (!autoStart() || System.currentTimeMillis() - failedAt < RESTART_MS) return false;
if (gone) {
for (String name : List.of("agent.addr", "console.addr")) {
try {
Files.deleteIfExists(store.resolve(name));
} catch (IOException ignored) {
// Another process's: it starts the new one.
}
}
}
boolean started = start();
if (!started) failedAt = System.currentTimeMillis();
return started;
}

/**
* A socket connected to the agent's address, `unix:/path` or `tcp:host:port` (a channel for the former); null for
* an address of neither kind.
*/
static Closeable connect(String address, int timeoutMs) throws IOException {
if (address.startsWith("unix:")) {
SocketChannel socket = SocketChannel.open(StandardProtocolFamily.UNIX);
try {
socket.connect(UnixDomainSocketAddress.of(Path.of(address.substring("unix:".length()))));
} catch (IOException | RuntimeException e) {
socket.close();
throw e;
}
return socket;
}
if (address.startsWith("tcp:")) {
String hostPort = address.substring("tcp:".length());
int at = hostPort.lastIndexOf(':');
Socket socket = new Socket();
try {
socket.connect(
new InetSocketAddress(hostPort.substring(0, at).replaceAll("^\\[|]$", ""), Integer.parseInt(hostPort.substring(at + 1))),
timeoutMs);
} catch (IOException | RuntimeException e) {
socket.close();
throw e;
}
return socket;
}
return null;
}

/** Whether an agent listens at the address: an address file alone may be a stopped agent's. */
static boolean answers(String address) {
try {
Closeable socket = connect(address, PROBE_TIMEOUT_MS);
if (socket == null) return false;
socket.close();
return true;
} catch (IOException | RuntimeException e) {
return false;
}
}

private boolean start() {
String binary = binary();
if (binary == null) {
Expand All @@ -108,17 +155,22 @@ private boolean start() {
warn("the agent didn't start: " + e.getMessage());
return false;
}
// Until its address answers: the file may still be a stopped agent's (a unix socket's is the same path each
// time). Another process's agent may win the race (one per store): then that one's answers.
long deadline = System.currentTimeMillis() + START_WAIT_MS;
while (System.currentTimeMillis() < deadline && address().isEmpty()) {
while (!answers(address())) {
if (System.currentTimeMillis() >= deadline) {
warn("the agent didn't start (see " + store.resolve("agent.log") + ")");
return false;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
if (address().isEmpty()) warn("the agent didn't start (see " + store.resolve("agent.log") + ")");
return !address().isEmpty();
return true;
}

/**
Expand Down
21 changes: 4 additions & 17 deletions tracepanel-core/src/main/java/dev/tracepanel/core/Sender.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
package dev.tracepanel.core;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -226,24 +223,14 @@ static List<String> capabilities(Config config, Set<String> sends, boolean datab
/** A connection the agent accepted after the hello line, or null. */
private Connection handshake(String address) {
try {
AutoCloseable channel;
Closeable channel = Agent.connect(address, CONNECT_TIMEOUT_MS);
OutputStream out;
InputStream in;
if (address.startsWith("unix:")) {
SocketChannel socket = SocketChannel.open(StandardProtocolFamily.UNIX);
socket.connect(UnixDomainSocketAddress.of(Path.of(address.substring("unix:".length()))));
channel = socket;
if (channel instanceof SocketChannel socket) {
out = Channels.newOutputStream(socket);
in = Channels.newInputStream(socket);
} else if (address.startsWith("tcp:")) {
String hostPort = address.substring("tcp:".length());
int at = hostPort.lastIndexOf(':');
Socket socket = new Socket();
socket.connect(
new InetSocketAddress(hostPort.substring(0, at).replaceAll("^\\[|]$", ""), Integer.parseInt(hostPort.substring(at + 1))),
CONNECT_TIMEOUT_MS);
} else if (channel instanceof Socket socket) {
socket.setSoTimeout(CONNECT_TIMEOUT_MS);
channel = socket;
out = socket.getOutputStream();
in = socket.getInputStream();
} else {
Expand Down
81 changes: 81 additions & 0 deletions tracepanel-core/src/test/java/dev/tracepanel/core/AgentTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package dev.tracepanel.core;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;

class AgentTest {
@Test
@DisabledOnOs(OS.WINDOWS)
void an_agent_that_does_not_take_the_hello_yet_keeps_its_addresses(@TempDir Path root) throws Exception {
Path store = root.resolve(".tracepanel");
Files.createDirectories(store);
Path started = root.resolve("started");
Path binary = script(root, "touch '" + started + "'");
Map<String, String> env = Map.of(
"TRACEPANEL_ROOT", root.toString(), "TRACEPANEL_DIR", store.toString(), "TRACEPANEL_AGENT_BIN", binary.toString());
// Another process's agent, starting: it listens, and answers no hello yet.
try (ServerSocket starting = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) {
String address = "tcp:127.0.0.1:" + starting.getLocalPort();
Files.writeString(store.resolve("agent.addr"), address + "\n");
Files.writeString(store.resolve("console.addr"), "http://127.0.0.1:1/\n");
Agent agent = new Agent(store, env);

assertFalse(new Sender(Config.load(env, "shop"), agent).connected());

assertEquals(address, agent.address());
assertEquals("http://127.0.0.1:1/", agent.console());

assertFalse(Files.exists(started), "no second agent started");
}
}

@Test
@DisabledOnOs(OS.WINDOWS)
void an_address_nothing_listens_at_is_a_stopped_agents_and_a_new_one_starts(@TempDir Path root) throws Exception {
Path store = root.resolve(".tracepanel");
Files.createDirectories(store);
try (ServerSocket fresh = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) {
String address = "tcp:127.0.0.1:" + fresh.getLocalPort();
// The new agent: it writes its address a moment after it starts, in the store it is given (--dir).
Path binary = script(root, "sleep 0.2; printf '%s\\n' '" + address + "' > \"$2/agent.addr\"");
Map<String, String> env = Map.of(
"TRACEPANEL_ROOT", root.toString(), "TRACEPANEL_DIR", store.toString(), "TRACEPANEL_AGENT_BIN", binary.toString());
Files.writeString(store.resolve("agent.addr"), "unix:" + root.resolve("gone.sock") + "\n");
Agent agent = new Agent(store, env);

assertTrue(agent.ensure(true));

assertEquals(address, agent.address());
}
}

@Test
void whether_an_agent_answers_is_a_bare_connect(@TempDir Path root) throws Exception {
try (ServerSocket listening = new ServerSocket(0, 5, InetAddress.getLoopbackAddress())) {
assertTrue(Agent.answers("tcp:127.0.0.1:" + listening.getLocalPort()));
}

assertFalse(Agent.answers("unix:" + root.resolve("gone.sock")));
assertFalse(Agent.answers(""));
assertFalse(Agent.answers("tcp:nonsense"));
}

private static Path script(Path root, String body) throws Exception {
Path binary = root.resolve("tracepanel-agent");
Files.writeString(binary, "#!/bin/sh\n" + body + "\n");
Files.setPosixFilePermissions(binary, PosixFilePermissions.fromString("rwx------"));
return binary;
}
}