mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
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 <hectorvent@gmail.com> * 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 <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
fa306b38a6
commit
a9edb57aa6
5 files changed
+396
-22
No files matched your search
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user