fix(http): keep snapshot names in one path segment and report odd server responses clearly (#54)

* fix(http): keep snapshot names in one path segment and report odd server responses clearly

Snapshot names are URL-encoded and names that would change the path are refused; every trailing slash is stripped from the endpoint; a non-JSON body or a redirect gets a message that says so instead of a parser error; requests use HTTP/1.1. snapshot delete reports a missing snapshot API like save and load, save warns that --message is not sent yet, and export/import no longer cite a server version that does not exist.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(http): tell a missing snapshot API from its status, not from the error text

The error message carries the request path, so a snapshot named nightly404 turned a real server error into 'not available'. FlociException now carries the HTTP status and the snapshot commands ask that.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-10 21:39:43 -05:00
1 parent 1a7e84cd23
commit 24b4280f69
10 files changed
+289 -22

No files matched your search

@@ -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) {
@@ -172,11 +177,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 {
@@ -184,7 +189,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 {
@@ -215,10 +220,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) {
@@ -246,11 +249,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) {
@@ -268,9 +269,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) {
@@ -285,4 +284,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");
}
}