perf: restart without a fixed pause and wait no longer than --timeout (#36)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 22:41:35 -05:00
1 parent fc67e72a62
commit 01d6133548
9 files changed
+407 -34

No files matched your search

@@ -0,0 +1,65 @@
package io.floci.cli.unit;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
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;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/** An abandoned docker call must not leave its process running after the CLI moves on. */
class DockerClientProcessTest {
@TempDir
Path tempDir;
@Test
@DisabledOnOs(OS.WINDOWS)
void anInterruptedCallKillsItsDockerProcess() throws Exception {
Path pidFile = tempDir.resolve("pid");
Path fakeDocker = tempDir.resolve("docker");
Files.writeString(fakeDocker, "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 30\n");
assertTrue(fakeDocker.toFile().setExecutable(true));
DockerClient docker = new DockerClient(fakeDocker.toString());
Thread call = Thread.ofVirtual().start(() -> {
try {
docker.inspectContainer("floci");
} catch (DockerException expected) {
// "Interrupted"
}
});
long pid = awaitPid(pidFile);
call.interrupt();
call.join(5_000);
assertFalse(call.isAlive(), "the call should return once interrupted");
long deadline = System.currentTimeMillis() + 3_000;
while (isAlive(pid) && System.currentTimeMillis() < deadline) {
Thread.sleep(50);
}
assertFalse(isAlive(pid), "docker process " + pid + " outlived the interrupted call");
}
private static long awaitPid(Path pidFile) throws Exception {
long deadline = System.currentTimeMillis() + 5_000;
while (System.currentTimeMillis() < deadline) {
if (Files.exists(pidFile)) {
String text = Files.readString(pidFile).trim();
if (!text.isEmpty()) return Long.parseLong(text);
}
Thread.sleep(20);
}
throw new AssertionError("fake docker never started");
}
private static boolean isAlive(long pid) {
return ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false);
}
}
@@ -6,6 +6,7 @@ import io.floci.cli.commands.RestartCommand;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import picocli.CommandLine;
import picocli.CommandLine.ParseResult;
import java.io.ByteArrayOutputStream;
@@ -149,4 +150,12 @@ class RestartCommandTest {
Files.delete(tempDir.resolve("snap.yaml"));
assertTrue(restart.buildStartCommand().dockerRunArgs(SOCKET).contains("/from-the-parse:/app/data"));
}
/** BL-029: the stop removes the container, so start needs no pause and no second removal. */
@Test
void theStopItRunsRemovesTheContainer() {
var stop = parse(ProductProfile.AWS).buildStopCommand();
assertEquals(Boolean.TRUE, new CommandLine(stop).getCommandSpec().findOption("--remove").getValue());
}
}
@@ -0,0 +1,152 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.WaitCommand;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.docker.DockerClient;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
/** BL-030: wait polls soon after a start and never runs past --timeout. */
class WaitCommandTimingTest {
@TempDir
Path tempDir;
@Test
void pollingBacksOffFromTwentyFiveMillisToHalfASecond() {
assertEquals(50, WaitCommand.nextDelay(25));
assertEquals(100, WaitCommand.nextDelay(50));
assertEquals(200, WaitCommand.nextDelay(100));
assertEquals(400, WaitCommand.nextDelay(200));
assertEquals(500, WaitCommand.nextDelay(400));
assertEquals(500, WaitCommand.nextDelay(500));
}
@Test
void aRequestNeverOutlivesTheDeadline() {
assertEquals(Duration.ofSeconds(10), WaitCommand.requestTimeout(Duration.ofMinutes(2)));
assertEquals(Duration.ofMillis(800), WaitCommand.requestTimeout(Duration.ofMillis(800)));
assertEquals(Duration.ofMillis(1), WaitCommand.requestTimeout(Duration.ZERO));
assertEquals(Duration.ofMillis(1), WaitCommand.requestTimeout(Duration.ofMillis(-5)));
}
@Test
void aServerThatNeverAnswersStillTimesOutOnTime() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
try {
Thread.sleep(5_000); // longer than the timeout below
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
server.start();
PrintStream err = System.err;
PrintStream out = System.out;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
String endpoint = "http://127.0.0.1:" + server.getAddress().getPort();
long start = System.nanoTime();
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(
"wait", "--timeout", "1s", "--endpoint", endpoint, "--container", "floci-wait-timing-none");
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
assertEquals(1, exit);
// The old loop could block for a full 10 s request; allow docker's inspect on top.
assertTrue(elapsedMs < 2_500, "took " + elapsedMs + " ms");
} finally {
System.setErr(err);
System.setOut(out);
server.stop(0);
}
}
/** A stalled Docker daemon must not hold wait past --timeout either. */
@Test
void aHungContainerLookupStillTimesOutOnTime() {
DockerClient hung = new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return Optional.empty();
}
};
PrintStream err = System.err;
PrintStream out = System.out;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
long start = System.nanoTime();
// Port 9 (discard) refuses connections quickly, so only the lookup could stall.
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, hung))
.execute("--timeout", "1s", "--endpoint", "http://127.0.0.1:9");
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
assertEquals(1, exit);
assertTrue(elapsedMs < 1_800, "took " + elapsedMs + " ms");
} finally {
System.setErr(err);
System.setOut(out);
}
}
/** Headers arrive at once, then the body stalls: HttpRequest.timeout alone would not cover it. */
@Test
void aServerThatStallsMidBodyStillTimesOutOnTime() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(200, 0); // chunked: the body never completes
exchange.getResponseBody().write("{\"version\":".getBytes());
exchange.getResponseBody().flush();
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
server.start();
DockerClient noContainer = new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String name) {
return Optional.empty();
}
};
PrintStream err = System.err;
PrintStream out = System.out;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
try {
long start = System.nanoTime();
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, noContainer)).execute(
"--timeout", "1s", "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort());
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
assertEquals(1, exit);
assertTrue(elapsedMs < 1_800, "took " + elapsedMs + " ms");
} finally {
System.setErr(err);
System.setOut(out);
server.stop(0);
}
}
}