mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-23 22:11:37 -05:00
fix(cli): reject durations that overflow and pin the spinner rule on a terminal
A duration is checked for sign before it is converted and the conversion is overflow-checked, so -9223372036854775807s no longer wraps to a positive timeout. wait takes its terminal check through a seam, with tests for json, yaml and text output on a terminal.
This commit is contained in:
4 files changed
+82
-14
No files matched your search
@@ -20,6 +20,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
@Command(
|
||||
name = "wait",
|
||||
@@ -43,12 +44,19 @@ public class WaitCommand implements Callable<Integer> {
|
||||
|
||||
/** Test seam: {@code docker} answers the container lookup that finds the endpoint. */
|
||||
public WaitCommand(ProductProfile profile, DockerClient docker) {
|
||||
this(profile, docker, WaitCommand::interactive);
|
||||
}
|
||||
|
||||
/** Test seam: {@code terminal} stands in for "stdout is a terminal", which a test run is not. */
|
||||
public WaitCommand(ProductProfile profile, DockerClient docker, BooleanSupplier terminal) {
|
||||
this.profile = profile;
|
||||
this.global = new GlobalOptions(profile);
|
||||
this.docker = docker;
|
||||
this.terminal = terminal;
|
||||
}
|
||||
|
||||
private final DockerClient docker;
|
||||
private final BooleanSupplier terminal;
|
||||
|
||||
@Option(names = {"--timeout"}, description = "Maximum time to wait (e.g. 30s, 2m)", defaultValue = "30s", paramLabel = "<duration>")
|
||||
String timeout;
|
||||
@@ -78,7 +86,7 @@ public class WaitCommand implements Callable<Integer> {
|
||||
}
|
||||
// Only a person at a terminal watching text output gets the spinner: in -o json/yaml or
|
||||
// in a pipe its frames would land in the data.
|
||||
boolean spinner = printer.format() == OutputFormat.text && interactive();
|
||||
boolean spinner = printer.format() == OutputFormat.text && terminal.getAsBoolean();
|
||||
// The deadline starts now, so the container lookup below counts against --timeout too.
|
||||
Instant deadline = Instant.now().plusMillis(timeoutMillis);
|
||||
String effectiveEndpoint = knownEndpoint != null ? knownEndpoint : endpointWithin(deadline);
|
||||
|
||||
@@ -12,23 +12,36 @@ public final class Durations {
|
||||
public static long parseDuration(String s) {
|
||||
if (s == null || s.isBlank()) return 30_000;
|
||||
String value = s.trim().toLowerCase();
|
||||
long millis;
|
||||
long amount;
|
||||
long unitMillis;
|
||||
try {
|
||||
if (value.endsWith("ms")) millis = Long.parseLong(value.substring(0, value.length() - 2));
|
||||
else if (value.endsWith("s")) millis = Long.parseLong(value.substring(0, value.length() - 1)) * 1000;
|
||||
else if (value.endsWith("m")) millis = Long.parseLong(value.substring(0, value.length() - 1)) * 60_000;
|
||||
else if (value.endsWith("h")) millis = Long.parseLong(value.substring(0, value.length() - 1)) * 3_600_000;
|
||||
else millis = Long.parseLong(value) * 1000;
|
||||
if (value.endsWith("ms")) { amount = number(value, 2); unitMillis = 1; }
|
||||
else if (value.endsWith("s")) { amount = number(value, 1); unitMillis = 1000; }
|
||||
else if (value.endsWith("m")) { amount = number(value, 1); unitMillis = 60_000; }
|
||||
else if (value.endsWith("h")) { amount = number(value, 1); unitMillis = 3_600_000; }
|
||||
else { amount = number(value, 0); unitMillis = 1000; }
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("Invalid duration '" + s + "'.\n"
|
||||
+ "Use a number with ms, s, m or h, for example 30s or 2m.");
|
||||
}
|
||||
if (millis <= 0) {
|
||||
// Checked before the conversion: a product that overflows can come back positive.
|
||||
if (amount <= 0) {
|
||||
throw new IllegalArgumentException("Duration '" + s + "' must be greater than zero.\n"
|
||||
+ "Use a positive value, for example 30s.");
|
||||
}
|
||||
long millis;
|
||||
try {
|
||||
millis = Math.multiplyExact(amount, unitMillis);
|
||||
} catch (ArithmeticException e) {
|
||||
throw new IllegalArgumentException("Duration '" + s + "' is too long.\n"
|
||||
+ "Use a smaller value, for example 30s or 2m.");
|
||||
}
|
||||
return millis;
|
||||
}
|
||||
|
||||
private static long number(String value, int suffixLength) {
|
||||
return Long.parseLong(value.substring(0, value.length() - suffixLength));
|
||||
}
|
||||
|
||||
private Durations() {}
|
||||
}
|
||||
@@ -28,9 +28,22 @@ class DurationsTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"0s", "0", "-1s", "-5"})
|
||||
// The last one overflows to +1000 ms when multiplied before the check.
|
||||
@ValueSource(strings = {"0s", "0", "-1s", "-5", "-9223372036854775807s"})
|
||||
void rejectsDurationsThatAreNotPositive(String value) {
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Durations.parseDuration(value));
|
||||
assertTrue(e.getMessage().contains("greater than zero"), e.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"9223372036854775807s", "9223372036854775807", "9223372036854775m", "2562047788016h"})
|
||||
void rejectsDurationsTooLongToRepresent(String value) {
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Durations.parseDuration(value));
|
||||
assertTrue(e.getMessage().contains("too long"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLargestMillisecondValueStillParses() {
|
||||
assertEquals(Long.MAX_VALUE, Durations.parseDuration("9223372036854775807ms"));
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,15 @@ 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 org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
@@ -153,6 +157,10 @@ class WaitCommandTimingTest {
|
||||
private record Out(int exit, String out, String err) {}
|
||||
|
||||
private static Out waitWith(String... args) {
|
||||
return waitWith(false, args);
|
||||
}
|
||||
|
||||
private static Out waitWith(boolean terminal, String... args) {
|
||||
DockerClient noContainer = new DockerClient() {
|
||||
@Override
|
||||
public Optional<ContainerInfo> inspectContainer(String name) {
|
||||
@@ -166,7 +174,7 @@ class WaitCommandTimingTest {
|
||||
System.setOut(new PrintStream(outBuf));
|
||||
System.setErr(new PrintStream(errBuf));
|
||||
try {
|
||||
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, noContainer)).execute(args);
|
||||
int exit = new CommandLine(new WaitCommand(ProductProfile.AWS, noContainer, () -> terminal)).execute(args);
|
||||
return new Out(exit, outBuf.toString(), errBuf.toString());
|
||||
} finally {
|
||||
System.setErr(err);
|
||||
@@ -174,13 +182,39 @@ class WaitCommandTimingTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** BL-039: -o json output carries no spinner frames, whatever happens while waiting. */
|
||||
@Test
|
||||
void structuredOutputHasNoSpinner() {
|
||||
Out r = waitWith("--timeout", "1s", "--endpoint", "http://127.0.0.1:9", "-o", "json");
|
||||
/** BL-039: on a terminal, -o json and -o yaml still carry no spinner frames while polling. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"json", "yaml"})
|
||||
void structuredOutputHasNoSpinnerEvenOnATerminal(String format) throws Exception {
|
||||
Out r = waitWith(true, "--timeout", "300ms", "--endpoint", closedEndpoint(), "-o", format);
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
assertFalse(r.out().contains("Waiting"), r.out());
|
||||
assertFalse(r.out().contains("\r"), r.out());
|
||||
}
|
||||
|
||||
/** The other half: text output on a terminal does draw it, so the test above can fail. */
|
||||
@Test
|
||||
void textOutputOnATerminalShowsTheSpinner() throws Exception {
|
||||
Out r = waitWith(true, "--timeout", "300ms", "--endpoint", closedEndpoint());
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
assertTrue(r.out().contains("Waiting"), r.out());
|
||||
}
|
||||
|
||||
@Test
|
||||
void textOutputInAPipeHasNoSpinner() throws Exception {
|
||||
Out r = waitWith(false, "--timeout", "300ms", "--endpoint", closedEndpoint());
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
assertFalse(r.out().contains("Waiting"), r.out());
|
||||
}
|
||||
|
||||
// A port that was just bound and released: nothing is listening, so polls are refused at once.
|
||||
private static String closedEndpoint() throws Exception {
|
||||
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
|
||||
return "http://127.0.0.1:" + socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
/** BL-040: a bad --timeout is a usage error with a hint, not a stack trace. */
|
||||
|
||||
Reference in new issue
Block a user