Merge remote-tracking branch 'origin/main' into feat/reset

Reset asks the exception for the HTTP status, as the snapshot commands now do.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-10-10 21:40:50 -05:00
commit c95d2ffb16
15 files changed
+330 -31

No files matched your search

-1
View File
@@ -664,7 +664,6 @@ floci wait -o json # machine-readable output
```sh
floci doctor # run all checks
floci doctor --check docker.installed # run a single check by name
floci doctor --fix # auto-fix fixable issues
floci doctor -o json # structured output for scripts
floci gcp doctor # GCP-specific checks
@@ -50,9 +50,6 @@ public class DoctorCommand implements Callable<Integer> {
@Option(names = {"--check"}, description = "Run only a specific check by name", paramLabel = "<name>")
String checkName;
@Option(names = {"--fix"}, description = "Attempt to auto-fix fixable issues")
boolean fix;
/** The base environment checks every product runs, in order: Docker first, then server. */
public static List<Check> dockerChecks(ProductProfile profile) {
return dockerChecks(profile, new CachingDockerClient());
@@ -182,7 +179,7 @@ public class DoctorCommand implements Callable<Integer> {
printer.println(Ansi.green("No failures") + ", " + warns + " warning(s) to review.");
} else {
printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)."
+ (fix ? "" : " Run with --fix to auto-resolve fixable issues."));
+ " Follow the Fix line under each one.");
}
return fails > 0 ? 1 : 0;
@@ -140,7 +140,7 @@ public class ResetCommand implements Callable<Integer> {
try {
new FlociHttpClient(effectiveEndpoint, profile).resetState();
} catch (FlociException e) {
if (e.getMessage().contains("HTTP 404") || e.getMessage().contains("HTTP 501")) {
if (e.endpointMissing()) {
printer.error("Resetting state is not available on this " + profile.displayName() + " server version.\n"
+ "Restart it without --persist for a clean state, or track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -35,9 +35,6 @@ public class ServicesCommand implements Callable<Integer> {
this.global = new GlobalOptions(profile);
}
@Option(names = {"--mode"}, description = "Filter mode: docker, in-process, all (default: all)", defaultValue = "all", paramLabel = "docker|in-process|all")
String mode;
@Override
public Integer call() {
Printer printer = global.printer();
@@ -47,7 +47,12 @@ public class SnapshotDeleteCommand implements Callable<Integer> {
printer.println(Ansi.green("Snapshot deleted:") + " " + name);
return 0;
} catch (FlociException e) {
printer.error("Failed to delete snapshot: " + e.getMessage());
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
printer.error("Failed to delete snapshot: " + e.getMessage());
}
return 1;
}
}
@@ -38,7 +38,7 @@ public class SnapshotExportCommand implements Callable<Integer> {
public Integer call() {
Printer printer = global.printer();
// TODO: implement GET /_floci/snapshots/<name>/export streaming to file
printer.error("snapshot export requires floci-server >= 1.6.0\n" +
printer.error("snapshot export is not available yet: the emulator has no snapshot export API.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
return 1;
}
@@ -38,7 +38,7 @@ public class SnapshotImportCommand implements Callable<Integer> {
public Integer call() {
Printer printer = global.printer();
// TODO: implement POST /_floci/snapshots/import with multipart upload
printer.error("snapshot import requires floci-server >= 1.6.0\n" +
printer.error("snapshot import is not available yet: the emulator has no snapshot import API.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
return 1;
}
@@ -54,7 +54,7 @@ public class SnapshotListCommand implements Callable<Integer> {
node.forEach(s -> printer.println(" " + s.asText()));
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -47,7 +47,7 @@ public class SnapshotLoadCommand implements Callable<Integer> {
printer.println(Ansi.green("Snapshot loaded:") + " " + name);
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -45,12 +45,16 @@ public class SnapshotSaveCommand implements Callable<Integer> {
// so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
if (message != null && !message.isBlank()) {
// The snapshot API contract has no description field yet; say so rather than drop it.
printer.warn("--message is not sent: the snapshot API does not take a description yet.");
}
try {
client.postSnapshot(name);
printer.println(Ansi.green("Snapshot saved:") + " " + name);
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -1,7 +1,29 @@
package io.floci.cli.http;
public class FlociException extends Exception {
private final int status;
public FlociException(String message) {
this(message, 0);
}
/** An error the server answered with HTTP {@code status}. */
public FlociException(String message, int status) {
super(message);
this.status = status;
}
/** The HTTP status the server answered with, or 0 when the failure was not an HTTP response. */
public int status() {
return status;
}
/**
* The server has no such endpoint (404) or does not implement it (501). Asked of the status,
* never of the message: the message carries the request path, and a path can contain "404".
*/
public boolean endpointMissing() {
return status == 404 || status == 501;
}
}
@@ -6,10 +6,12 @@ import io.floci.cli.ProductProfile;
import java.net.ConnectException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -59,11 +61,14 @@ public class FlociHttpClient {
int query = base.indexOf('?');
this.query = query >= 0 ? base.substring(query) : "";
base = query >= 0 ? base.substring(0, query) : base;
this.endpoint = base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
this.endpoint = base.replaceAll("/+$", "");
this.controlPrefix = controlPrefix.endsWith("/")
? controlPrefix.substring(0, controlPrefix.length() - 1)
: controlPrefix;
// HTTP/1.1: the emulators speak it, and the default (HTTP/2) first tries an h2c upgrade on
// every plain-http request. Redirects are not followed; see checkStatus.
this.http = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(5))
.build();
}
@@ -159,7 +164,7 @@ public class FlociHttpClient {
message.contains("not available yet"));
}
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path, resp.statusCode());
}
return resp.body();
} catch (FlociException e) {
@@ -177,11 +182,11 @@ public class FlociHttpClient {
}
public Map<String, Object> postSnapshot(String name) throws FlociException {
return postJson(controlPrefix + "/snapshots/" + name, "{}");
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}");
}
public Map<String, Object> loadSnapshot(String name) throws FlociException {
return postJson(controlPrefix + "/snapshots/" + name + "/load", "{}");
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name) + "/load", "{}");
}
public JsonNode listSnapshots() throws FlociException {
@@ -189,7 +194,7 @@ public class FlociHttpClient {
}
public void deleteSnapshot(String name) throws FlociException {
deleteRequest(controlPrefix + "/snapshots/" + name);
deleteRequest(controlPrefix + "/snapshots/" + snapshotSegment(name));
}
private JsonNode getJson(String path) throws FlociException {
@@ -220,10 +225,8 @@ public class FlociHttpClient {
if (e.getCause() instanceof HttpTimeoutException) throw timedOut(path, timeout);
throw new FlociException("Request failed: " + e.getCause().getMessage());
}
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
return MAPPER.readTree(resp.body());
checkStatus(resp, path);
return readJson(resp.body(), path);
} catch (FlociException e) {
throw e;
} catch (InterruptedException e) {
@@ -251,11 +254,9 @@ public class FlociHttpClient {
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
checkStatus(resp, path);
if (resp.body() == null || resp.body().isBlank()) return Map.of();
return MAPPER.readValue(resp.body(), Map.class);
return MAPPER.convertValue(readJson(resp.body(), path), Map.class);
} catch (FlociException e) {
throw e;
} catch (ConnectException e) {
@@ -273,9 +274,7 @@ public class FlociHttpClient {
.DELETE()
.build();
HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
checkStatus(resp, path);
} catch (FlociException e) {
throw e;
} catch (Exception e) {
@@ -290,4 +289,36 @@ public class FlociHttpClient {
private URI url(String path) {
return URI.create(endpoint + path + query);
}
// A redirect usually means --endpoint names a proxy or the wrong address; following it
// silently could send requests elsewhere, so it is reported instead.
private void checkStatus(HttpResponse<?> resp, String path) throws FlociException {
int status = resp.statusCode();
if (status >= 300 && status < 400) {
String location = resp.headers().firstValue("Location").orElse("another address");
throw new FlociException("Server redirected " + path + " to " + location + ".\n"
+ "Point --endpoint at the address Floci listens on.");
}
if (status >= 400) {
throw new FlociException("Server returned HTTP " + status + " for " + path, status);
}
}
private JsonNode readJson(String body, String path) throws FlociException {
try {
return MAPPER.readTree(body);
} catch (Exception e) {
throw new FlociException("The response from " + endpoint + path + " is not JSON, so this may not be a Floci server.\n"
+ "Run '" + commandPrefix + " status' to see the endpoint the emulator answers on.");
}
}
/** A snapshot name as one URL path segment; names that could change the path are refused. */
static String snapshotSegment(String name) throws FlociException {
if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) {
throw new FlociException("Invalid snapshot name '" + name + "'.\n"
+ "Use a name that is not '.' or '..' and has no '/'.");
}
return URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20");
}
}
@@ -0,0 +1,99 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.http.FlociException;
import io.floci.cli.http.FlociHttpClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** BL-047: what FlociHttpClient sends, and how it reports responses that are not what it expects. */
class FlociHttpClientRobustnessTest {
private HttpServer server;
private final AtomicReference<String> lastPath = new AtomicReference<>();
private final AtomicInteger status = new AtomicInteger(200);
private final AtomicReference<String> body = new AtomicReference<>("{\"version\":\"1.0\",\"services\":[]}");
private final AtomicReference<String> location = new AtomicReference<>();
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
lastPath.set(exchange.getRequestURI().getRawPath());
if (location.get() != null) exchange.getResponseHeaders().add("Location", location.get());
byte[] bytes = body.get().getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status.get(), bytes.length == 0 ? -1 : bytes.length);
if (bytes.length > 0) {
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
server.stop(0);
}
private String endpoint() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
@Test
void everyTrailingSlashIsStripped() throws Exception {
new FlociHttpClient(endpoint() + "///", "/_floci").health();
assertEquals("/_floci/health", lastPath.get());
}
@Test
void aBodyThatIsNotJsonIsReportedAsSuch() {
body.set("OK");
FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health());
assertTrue(e.getMessage().contains("is not JSON"), e.getMessage());
}
@Test
void aRedirectIsReportedNotFollowed() {
status.set(302);
body.set("");
location.set("http://elsewhere.example/_floci/health");
FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health());
assertTrue(e.getMessage().contains("redirected"), e.getMessage());
assertTrue(e.getMessage().contains("elsewhere.example"), e.getMessage());
}
@Test
void snapshotNamesAreOnePathSegment() throws Exception {
status.set(204);
body.set("");
new FlociHttpClient(endpoint(), "/_floci").deleteSnapshot("my snap?x");
assertEquals("/_floci/snapshots/my%20snap%3Fx", lastPath.get());
}
@Test
void snapshotNamesThatWouldChangeThePathAreRefused() {
FlociHttpClient client = new FlociHttpClient(endpoint(), "/_floci");
for (String bad : new String[]{"..", ".", "a/b", "../escape"}) {
FlociException e = assertThrows(FlociException.class, () -> client.deleteSnapshot(bad), bad);
assertTrue(e.getMessage().contains("Invalid snapshot name"), e.getMessage());
}
assertNull(lastPath.get(), "nothing reached the server");
}
}
@@ -0,0 +1,39 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine;
import picocli.CommandLine.UnmatchedArgumentException;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/**
* BL-051, BL-052: doctor --fix fixed nothing and services --mode filtered nothing, so both were
* removed rather than kept as promises. They stay rejected in every product tree.
*/
class RemovedFlagsTest {
@TempDir
Path tempDir;
private CommandLine cli() {
return FlociCli.buildCommandLine(new ProfileStore(tempDir));
}
@ParameterizedTest
@ValueSource(strings = {"aws", "gcp", "az", "oci"})
void doctorHasNoFixFlag(String product) {
assertThrows(UnmatchedArgumentException.class, () -> cli().parseArgs(product, "doctor", "--fix"));
}
@ParameterizedTest
@ValueSource(strings = {"aws", "gcp", "az", "oci"})
void servicesHasNoModeFlag(String product) {
assertThrows(UnmatchedArgumentException.class, () -> cli().parseArgs(product, "services", "--mode", "docker"));
}
}
@@ -0,0 +1,106 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.FlociCli;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
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.CsvSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/** BL-048: the snapshot commands against a server that has no snapshot API (404). */
class SnapshotCommandsTest {
@TempDir
Path tempDir;
private HttpServer server;
private volatile int status = 404;
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(status, -1);
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
server.stop(0);
}
private String[] run(String... args) {
String[] all = new String[args.length + 4];
System.arraycopy(args, 0, all, 0, args.length);
all[args.length] = "--endpoint";
all[args.length + 1] = "http://127.0.0.1:" + server.getAddress().getPort();
all[args.length + 2] = "--container";
all[args.length + 3] = "floci-snapshot-test-none";
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(all);
return new String[]{String.valueOf(exit), outBuf.toString(), errBuf.toString()};
} finally {
System.setOut(out);
System.setErr(err);
}
}
@Test
void deleteSaysTheApiIsMissingLikeSaveAndLoad() {
String[] r = run("snapshot", "delete", "nightly");
assertEquals("1", r[0]);
assertTrue(r[2].contains("Snapshot API not available"), r[2]);
}
@Test
void aMessageIsNotDroppedSilently() {
String[] r = run("snapshot", "save", "nightly", "-m", "before upgrade");
assertTrue(r[2].contains("--message is not sent"), r[2]);
}
/**
* Only the status says the API is missing. A name that happens to contain "404" or "501" must
* not turn a real server error into "not available".
*/
@ParameterizedTest
@CsvSource({"delete, nightly404", "save, build-501", "load, 404"})
void aStatusLookingNameDoesNotHideARealError(String command, String name) {
status = 500;
String[] r = run("snapshot", command, name);
assertEquals("1", r[0]);
assertFalse(r[2].contains("Snapshot API not available"), r[2]);
assertTrue(r[2].contains("HTTP 500"), r[2]);
}
@ParameterizedTest
@CsvSource({"404", "501"})
void bothMissingEndpointStatusesReadAsNotAvailable(int missing) {
status = missing;
String[] r = run("snapshot", "delete", "nightly");
assertTrue(r[2].contains("Snapshot API not available"), r[2]);
}
}