diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index 4bd0d9b..20bf338 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -164,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")); @@ -174,9 +174,16 @@ 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 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 { - // 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. return path.toRealPath(); } catch (IOException e) { throw new UpdateException("cannot locate the running executable (" + path + ").\n" @@ -263,16 +270,32 @@ public class UpdateCommand implements Callable { private static boolean appleSilicon() { try { - Process p = new ProcessBuilder("sysctl", "-n", "hw.optional.arm64") - .redirectError(ProcessBuilder.Redirect.DISCARD) - .start(); - String out = new String(p.getInputStream().readAllBytes()).trim(); - return p.waitFor(5, TimeUnit.SECONDS) && "1".equals(out); + 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 { @@ -330,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 f0e43b1..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,30 +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. Record the attempt anyway (keeping the - // last known version), or every interactive run would retry and wait at exit. - try { - Path path = cachePath(); - Files.createDirectories(path.getParent()); - JSON.writeValue(path.toFile(), new UpdateCache(Instant.now().getEpochSecond(), - cache.map(UpdateCache::latestVersion).orElse(null))); - } catch (Exception ignored) { - } + // 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 index 5bf6aab..4a14149 100644 --- a/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java +++ b/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java @@ -2,10 +2,17 @@ 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.*; @@ -52,4 +59,56 @@ class UpdatePlatformTest { 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 index e433320..84d8a40 100644 --- a/src/test/java/io/floci/cli/update/UpdateNotifierTest.java +++ b/src/test/java/io/floci/cli/update/UpdateNotifierTest.java @@ -1,15 +1,22 @@ 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.*; @@ -32,19 +39,116 @@ class UpdateNotifierTest { System.setProperty("user.home", realHome); } - @Test - void aFailedCheckRefreshesTheTimestampAndKeepsTheLastKnownVersion() throws Exception { - Path cache = home.resolve(".floci").resolve("update-check.json"); - Files.createDirectories(cache.getParent()); - long stale = Instant.now().minus(Duration.ofDays(3)).getEpochSecond(); - Files.writeString(cache, "{\"checkedAtEpochSeconds\":" + stale + ",\"latestVersion\":\"0.2.0\"}"); + private Path cache; - // Port 9 refuses connections, so the fetch fails at once. - UpdateNotifier.refreshInBackground("http://127.0.0.1:9/releases/latest"); + 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 = new ObjectMapper().readValue(cache.toFile(), UpdateCache.class); + UpdateCache written = readCache(); assertEquals("0.2.0", written.latestVersion()); - assertTrue(written.checkedAtEpochSeconds() > stale + 60, "the attempt was recorded"); + 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); + } } }