From a9edb57aa6d720aae1dddcd4e3987e231b37b47d Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 22:08:57 -0500 Subject: [PATCH] fix(update): follow symlinked installs, pick arm64 under Rosetta and tell a failed check from a pending update (#56) * fix(update): follow symlinked installs, pick arm64 under Rosetta and tell a failed check from a pending update floci update replaces the real binary behind a symlink, moves an x86_64 build on Apple Silicon to the arm64 build, refuses a --version that is not a release version, and accepts upper-case checksums. --check now exits 2 when the check itself fails (1 still means an update is available) and on Windows points at the installer instead of 'floci update'. A failed background update check is recorded too, so the next command does not retry it and wait at exit. Signed-off-by: Hector Ventura * fix(update): record a check attempt before the request and bound the Rosetta probe The update check marks its attempt before asking GitHub, so a command that exits while the request is still waiting does not start it again on every run; an attempt is retried after an hour rather than a day and never overwrites a result another process just stored. The sysctl probe waits with its limit before reading. Adds a test for updating through a symlink. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- README.md | 4 +- .../io/floci/cli/commands/UpdateCommand.java | 95 +++++++++-- .../io/floci/cli/update/UpdateNotifier.java | 51 +++++- .../io/floci/cli/unit/UpdatePlatformTest.java | 114 +++++++++++++ .../floci/cli/update/UpdateNotifierTest.java | 154 ++++++++++++++++++ 5 files changed, 396 insertions(+), 22 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/UpdatePlatformTest.java create mode 100644 src/test/java/io/floci/cli/update/UpdateNotifierTest.java diff --git a/README.md b/README.md index ea8e0f7..9f1d2d4 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ java -jar floci.jar version Native-binary installs (install script, direct download) can self-update: ```sh -floci update --check # exit 0: up to date, exit 1: update available +floci update --check # exit 0: up to date, 1: update available, 2: the check failed floci update # download, verify checksum, replace the binary ``` @@ -851,7 +851,7 @@ sha256 against the release's `sha256sums.txt`, and atomically replaces the runni ```sh floci update # update to the latest release -floci update --check # exit 0: up to date, exit 1: update available +floci update --check # exit 0: up to date, 1: update available, 2: the check failed floci update --version 0.1.7 # install a specific version floci update --check || floci update # script-friendly: update only when stale ``` diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index a6d2c72..20bf338 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -26,6 +26,8 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.HexFormat; import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; /** * Self-update: downloads the target release binary from the public GitHub repository @@ -46,7 +48,7 @@ import java.util.concurrent.Callable; public class UpdateCommand implements Callable { @Option(names = "--check", - description = "Only report whether an update is available (exit 0: up to date, 1: update available)") + description = "Only report whether an update is available (exit 0: up to date, 1: update available, 2: the check failed)") boolean check; // No mixinStandardHelpOptions here: its -V/--version would collide with this option. @@ -84,6 +86,10 @@ public class UpdateCommand implements Callable { try { String current = CliVersion.CLI_VERSION; boolean pinned = to != null && !to.isBlank(); + if (pinned && !Version.isValid(to.trim())) { + // It goes into the download URL; refuse anything that is not a release version. + throw new UpdateException("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + } String target = pinned ? to.trim() : fetchLatestVersion(); // Unpinned updates are semantic, not string-equal: a pre-release/snapshot build @@ -96,7 +102,7 @@ public class UpdateCommand implements Callable { printer.println("update available: " + current + " → " + Ansi.bold(target)); if (check) { - printer.println(Ansi.gray("run 'floci update' to install it")); + printer.println(Ansi.gray(installHint())); // Non-zero so scripts can gate on staleness: floci update --check || floci update return 1; } @@ -124,10 +130,10 @@ public class UpdateCommand implements Callable { return 0; } catch (UpdateException e) { printer.error(e.getMessage()); - return 1; + return check ? 2 : 1; // --check keeps 1 for "update available" } catch (Exception e) { - printer.error("update failed: " + e.getMessage()); - return 1; + printer.error("update failed: " + e.getMessage() + "\nCheck your network connection and re-run 'floci update'."); + return check ? 2 : 1; } } @@ -158,7 +164,7 @@ public class UpdateCommand implements Callable { private Path resolveSelf() { if (selfPath != null) { - return selfPath; + return realExecutable(selfPath); } String cmd = ProcessHandle.current().info().command() .orElseThrow(() -> new UpdateException("cannot locate the running executable")); @@ -168,7 +174,31 @@ public class UpdateCommand implements Callable { throw new UpdateException("running from a jar (java -jar), not the native binary — " + "nothing to self-update. Reinstall instead: curl -fsSL https://floci.io/install.sh | sh"); } - return path; + return realExecutable(path); + } + + /** + * The file an update of {@code path} has to replace. A symlinked install + * (~/bin/floci -> /opt/floci/floci) must replace the real file, not the link; this also + * resolves a relative argv[0] against the working directory. + */ + public static Path realExecutable(Path path) { + try { + return path.toRealPath(); + } catch (IOException e) { + throw new UpdateException("cannot locate the running executable (" + path + ").\n" + + "Reinstall instead: curl -fsSL https://floci.io/install.sh | sh"); + } + } + + // What --check suggests: 'floci update' where it can install, the installer where it cannot. + private static String installHint() { + try { + detectPlatform(); + return "run 'floci update' to install it"; + } catch (UpdateException e) { + return e.getMessage(); + } } /** @@ -204,15 +234,24 @@ public class UpdateCommand implements Callable { // ── platform (mirrors installer/install.sh) ────────────────────────────── static String detectPlatform() { - String os = System.getProperty("os.name", "").toLowerCase(); - String arch = System.getProperty("os.arch", "").toLowerCase(); + return detectPlatform(System.getProperty("os.name", ""), System.getProperty("os.arch", ""), + UpdateCommand::appleSilicon); + } + + /** + * The release asset suffix for this machine. An x86_64 build on a Mac may be running under + * Rosetta on Apple Silicon; it then updates to the arm64 build instead of staying x86 forever. + */ + public static String detectPlatform(String osName, String osArch, BooleanSupplier appleSilicon) { + String os = osName.toLowerCase(); + String arch = osArch.toLowerCase(); String o = null; if (os.contains("mac")) { o = "darwin"; } else if (os.contains("linux")) { o = "linux"; } else if (os.contains("windows")) { - throw new UpdateException("self-update is not supported on Windows — " + throw new UpdateException("self-update is not supported on Windows; " + "re-run the installer: irm https://floci.io/install.ps1 | iex"); } String a = switch (arch) { @@ -223,9 +262,40 @@ public class UpdateCommand implements Callable { if (o == null || a == null) { throw new UpdateException("no published build for this platform (" + os + "/" + arch + ")"); } + if (o.equals("darwin") && a.equals("amd64") && appleSilicon.getAsBoolean()) { + a = "arm64"; + } return o + "-" + a; } + private static boolean appleSilicon() { + try { + return "1".equals(probe(Duration.ofSeconds(5), "sysctl", "-n", "hw.optional.arm64")); + } catch (Exception e) { + return false; + } + } + + /** + * The trimmed output of a short command, or null when it does not finish within {@code limit}. + * The wait comes first and a late process is killed: reading first would block for as long as + * the process keeps its output open, and the limit would never apply. Only for commands that + * print a line or two, which fit the pipe without being drained. + */ + public static String probe(Duration limit, String... command) throws IOException, InterruptedException { + Process p = new ProcessBuilder(command) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + try { + if (!p.waitFor(limit.toMillis(), TimeUnit.MILLISECONDS)) { + return null; + } + return new String(p.getInputStream().readAllBytes()).trim(); + } finally { + p.destroyForcibly(); // a no-op once it has exited + } + } + // ── download + verify ──────────────────────────────────────────────────── private String fetchString(String url) throws IOException, InterruptedException { @@ -275,7 +345,7 @@ public class UpdateCommand implements Callable { in.transferTo(OutputStream.nullOutputStream()); } String actual = HexFormat.of().formatHex(sha256.digest()); - if (!actual.equals(expected)) { + if (!actual.equalsIgnoreCase(expected)) { throw new UpdateException("checksum mismatch for " + asset + "\n expected: " + expected + "\n actual: " + actual + "\nThe download may be corrupt or tampered with. Aborting."); } @@ -283,7 +353,8 @@ public class UpdateCommand implements Callable { // ── atomic replace ─────────────────────────────────────────────────────── - private static void replaceAtomically(Path fresh, Path target) throws IOException { + /** Puts {@code fresh} in place of {@code target} in one step. Public as a test seam. */ + public static void replaceAtomically(Path fresh, Path target) throws IOException { // Stage in the TARGET's directory (same filesystem), then atomically rename over it. // The running process keeps its old inode; the path now serves the new binary. Path staged = target.resolveSibling("." + target.getFileName() + ".new"); diff --git a/src/main/java/io/floci/cli/update/UpdateNotifier.java b/src/main/java/io/floci/cli/update/UpdateNotifier.java index 3a85a8e..6e8a2b4 100644 --- a/src/main/java/io/floci/cli/update/UpdateNotifier.java +++ b/src/main/java/io/floci/cli/update/UpdateNotifier.java @@ -29,6 +29,9 @@ public final class UpdateNotifier { static final Duration TTL = Duration.ofHours(24); + /** How soon a check that did not produce a result (still in flight, or failed) is tried again. */ + static final Duration RETRY_AFTER = Duration.ofHours(1); + private static final ObjectMapper JSON = new ObjectMapper(); /** The in-flight refresh, if this run started one; lets main() grant it a short grace. */ @@ -74,22 +77,54 @@ public final class UpdateNotifier { if (cache.isPresent() && !isStale(cache.get())) { return; } - // Virtual threads do not keep the JVM alive: a quick exit just drops the check and it - // is retried next time; main() grants a short grace via awaitRefresh so commands that - // finish fast still get the cache populated eventually. + // Virtual threads do not keep the JVM alive: a quick exit just drops the check; main() + // grants a short grace via awaitRefresh so commands that finish fast still get the cache + // populated eventually. REFRESH.set(Thread.ofVirtual().name("floci-update-check").start(() -> { + // The attempt is recorded before the request, not after it fails: a request that is + // still waiting when the command exits never reaches a catch block, and every run + // would start it again and wait at exit. + if (!recordAttempt()) { + return; // another process got there first + } try { String latest = fetchLatestVersion(latestReleaseUrl); - Path path = cachePath(); - Files.createDirectories(path.getParent()); - JSON.writeValue(path.toFile(), - new UpdateCache(Instant.now().getEpochSecond(), latest)); + write(new UpdateCache(Instant.now().getEpochSecond(), latest)); } catch (Exception _) { - // Network/parse failure — never surfaced; the stale/absent cache stays as-is. + // Network/parse failure, never surfaced. The attempt is already on record. } })); } + /** + * Marks the cache as "checked, try again in {@link #RETRY_AFTER}", keeping the last known + * version. The file is read again right before the write: another process may have finished + * a check since this one found the cache stale, and its result (or its own attempt) stands. + * + * @return false when the cache is no longer stale, so there is nothing left to check + */ + static boolean recordAttempt() { + try { + Optional onDisk = readQuietly(); + if (onDisk.isPresent() && !isStale(onDisk.get())) { + return false; + } + // Backdated so the entry turns stale again after RETRY_AFTER rather than a full TTL: + // an attempt is not a result. + long checkedAt = Instant.now().minus(TTL).plus(RETRY_AFTER).getEpochSecond(); + write(new UpdateCache(checkedAt, onDisk.map(UpdateCache::latestVersion).orElse(null))); + } catch (Exception _) { + // An unwritable cache must not stop the check itself. + } + return true; + } + + private static void write(UpdateCache cache) throws Exception { + Path path = cachePath(); + Files.createDirectories(path.getParent()); + JSON.writeValue(path.toFile(), cache); + } + /** Give an in-flight refresh a bounded chance to finish before the JVM exits. */ public static void awaitRefresh(Duration grace) { Thread refresh = REFRESH.get(); diff --git a/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java b/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java new file mode 100644 index 0000000..4a14149 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java @@ -0,0 +1,114 @@ +package io.floci.cli.unit; + +import io.floci.cli.commands.UpdateCommand; +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 picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-049: which release asset floci update picks for the machine it runs on. */ +class UpdatePlatformTest { + + @Test + void picksTheAssetForEachPublishedPlatform() { + assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "aarch64", () -> true)); + assertEquals("linux-amd64", UpdateCommand.detectPlatform("Linux", "amd64", () -> false)); + assertEquals("linux-arm64", UpdateCommand.detectPlatform("Linux", "aarch64", () -> false)); + } + + /** An x86 build under Rosetta must move to the arm64 build, not stay x86 forever. */ + @Test + void anX86BuildOnAppleSiliconUpdatesToArm64() { + assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> true)); + assertEquals("darwin-amd64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> false)); + } + + @Test + void windowsPointsAtTheInstaller() { + RuntimeException e = assertThrows(RuntimeException.class, + () -> UpdateCommand.detectPlatform("Windows 11", "amd64", () -> false)); + assertTrue(e.getMessage().contains("install.ps1"), e.getMessage()); + } + + /** An invalid --version is refused before it reaches a download URL; --check reports it as 2. */ + @Test + void anInvalidVersionIsAFailedCheck() { + PrintStream err = System.err; + PrintStream out = System.out; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + int exit; + try { + exit = new CommandLine(new UpdateCommand()).execute("--check", "--version", "../../evil"); + } finally { + System.setErr(err); + System.setOut(out); + } + + assertEquals(2, exit); + assertTrue(errBuf.toString().contains("invalid --version"), errBuf.toString()); + } + + /** + * An install reached through a symlink (~/bin/floci -> /opt/floci/floci): the update replaces + * the file the link points at and leaves the link a link. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void updatingThroughASymlinkReplacesItsTargetAndKeepsTheLink(@TempDir Path dir) throws Exception { + Path real = Files.writeString(Files.createDirectories(dir.resolve("opt")).resolve("floci"), "old"); + Path link = Files.createSymbolicLink(Files.createDirectories(dir.resolve("bin")).resolve("floci"), real); + Path fresh = Files.writeString(dir.resolve("download"), "new"); + + Path binary = UpdateCommand.realExecutable(link); + UpdateCommand.replaceAtomically(fresh, binary); + + assertEquals(real.toRealPath(), binary); + assertTrue(Files.isSymbolicLink(link), "the link is still a link"); + assertEquals(real.toRealPath(), link.toRealPath()); + assertEquals("new", Files.readString(real)); + assertEquals("new", Files.readString(link)); + try (var files = Files.list(real.getParent())) { + assertEquals(List.of("floci"), files.map(p -> p.getFileName().toString()).toList(), "no staging file left"); + } + } + + @Test + void anExecutableThatCannotBeFoundIsReportedWithAWayOut(@TempDir Path dir) { + RuntimeException e = assertThrows(RuntimeException.class, + () -> UpdateCommand.realExecutable(dir.resolve("gone"))); + + assertTrue(e.getMessage().contains("cannot locate the running executable"), e.getMessage()); + assertTrue(e.getMessage().contains("install.sh"), e.getMessage()); + } + + /** A probe that stalls with its output still open is cut off at the limit, and killed. */ + @Test + @DisabledOnOs(OS.WINDOWS) + void aStalledProbeGivesUpAtItsLimit() throws Exception { + long start = System.nanoTime(); + + String out = UpdateCommand.probe(Duration.ofMillis(300), "sh", "-c", "echo 1; exec sleep 30"); + + long elapsedMs = (System.nanoTime() - start) / 1_000_000; + assertNull(out); + assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms"); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void aProbeThatFinishesReturnsItsOutput() throws Exception { + assertEquals("1", UpdateCommand.probe(Duration.ofSeconds(5), "sh", "-c", "echo 1")); + } +} diff --git a/src/test/java/io/floci/cli/update/UpdateNotifierTest.java b/src/test/java/io/floci/cli/update/UpdateNotifierTest.java new file mode 100644 index 0000000..84d8a40 --- /dev/null +++ b/src/test/java/io/floci/cli/update/UpdateNotifierTest.java @@ -0,0 +1,154 @@ +package io.floci.cli.update; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +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 java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-026: a failed check is recorded too, so the next run does not retry and wait again. */ +class UpdateNotifierTest { + + @TempDir + Path home; + + private String realHome; + + @BeforeEach + void pointHomeAtATempDir() { + realHome = System.getProperty("user.home"); + System.setProperty("user.home", home.toString()); + } + + @AfterEach + void restoreHome() { + System.setProperty("user.home", realHome); + } + + private Path cache; + + private void writeCache(Instant checkedAt, String version) throws Exception { + cache = home.resolve(".floci").resolve("update-check.json"); + Files.createDirectories(cache.getParent()); + Files.writeString(cache, "{\"checkedAtEpochSeconds\":" + checkedAt.getEpochSecond() + + ",\"latestVersion\":" + (version == null ? "null" : "\"" + version + "\"") + "}"); + } + + private UpdateCache readCache() throws Exception { + return new ObjectMapper().readValue(cache.toFile(), UpdateCache.class); + } + + private static boolean staleAt(UpdateCache entry, Instant when) { + return Instant.ofEpochSecond(entry.checkedAtEpochSeconds()).plus(UpdateNotifier.TTL).isBefore(when); + } + + // A port that was just bound and released: nothing listens there, so the fetch fails at once. + private static String refusedUrl() throws Exception { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + return "http://127.0.0.1:" + socket.getLocalPort() + "/releases/latest"; + } + } + + @Test + void aFailedCheckIsNotRetriedByTheNextRunAndKeepsTheLastKnownVersion() throws Exception { + writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0"); + + UpdateNotifier.refreshInBackground(refusedUrl()); + UpdateNotifier.awaitRefresh(Duration.ofSeconds(5)); + + UpdateCache written = readCache(); + assertEquals("0.2.0", written.latestVersion()); + assertFalse(staleAt(written, Instant.now()), "the next run does not check again"); + assertTrue(staleAt(written, Instant.now().plus(UpdateNotifier.RETRY_AFTER).plusSeconds(60)), + "but an attempt is not a result: it is tried again after RETRY_AFTER, not a full day"); + } + + /** + * The attempt is on record before the request is answered. A command that exits while the + * request is still waiting never reaches a failure handler, and would otherwise check again, + * and wait again, on every run. + */ + @Test + void anAttemptIsRecordedWhileTheRequestIsStillWaiting() throws Exception { + writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0"); + CountDownLatch release = new CountDownLatch(1); + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/", exchange -> { + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + exchange.close(); + }); + server.start(); + try { + UpdateNotifier.refreshInBackground("http://127.0.0.1:" + server.getAddress().getPort() + "/latest"); + UpdateNotifier.awaitRefresh(Duration.ofMillis(250)); // what main() grants a quick command + + UpdateCache written = readCache(); + assertEquals("0.2.0", written.latestVersion()); + assertFalse(staleAt(written, Instant.now()), "recorded although the request has not come back"); + } finally { + release.countDown(); + server.stop(0); + } + } + + /** Another process finished a check in the meantime: its result stands and nothing is overwritten. */ + @Test + void anAttemptDoesNotOverwriteAResultAnotherProcessJustWrote() throws Exception { + writeCache(Instant.now(), "0.4.0"); + String before = Files.readString(cache); + + assertFalse(UpdateNotifier.recordAttempt()); + + assertEquals(before, Files.readString(cache)); + } + + @Test + void anAttemptOnAStaleCacheKeepsItsVersionAndAsksToGoOn() throws Exception { + writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0"); + + assertTrue(UpdateNotifier.recordAttempt()); + + assertEquals("0.2.0", readCache().latestVersion()); + } + + @Test + void aSuccessfulCheckStoresTheVersionForAFullDay() throws Exception { + writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0"); + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/", exchange -> { + byte[] body = "{\"tag_name\":\"0.4.0\"}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + server.start(); + try { + UpdateNotifier.refreshInBackground("http://127.0.0.1:" + server.getAddress().getPort() + "/latest"); + UpdateNotifier.awaitRefresh(Duration.ofSeconds(5)); + + UpdateCache written = readCache(); + assertEquals("0.4.0", written.latestVersion()); + assertFalse(staleAt(written, Instant.now().plus(UpdateNotifier.RETRY_AFTER).plusSeconds(60))); + } finally { + server.stop(0); + } + } +}