Просмотр исходного кода

fix(update): refresh a stale check before applying (#1882)

Nacho 4 недель назад
Родитель
Сommit
0d3c6185d6

+ 25 - 0
server-go/internal/updater/updater.go

@@ -628,11 +628,36 @@ func (u *Updater) broadcastLocked() {
 // already_updating) o si no se pudo copiar.
 func (u *Updater) Apply() bool { return u.ApplyBy("admin") }
 
+// applyFreshCheckAge: antigüedad máxima del chequeo que se acepta como
+// objetivo de un apply (#1881). Con checkInterval a 24 h, un apply manual con
+// el estado del último chequeo descargaba una release ya superada y costaba un
+// segundo reinicio.
+const applyFreshCheckAge = 10 * time.Minute
+
+// needsFreshCheck indica si el objetivo guardado es demasiado viejo para
+// aplicarlo sin volver a preguntar a GitHub.
+func (u *Updater) needsFreshCheck() bool {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	return u.lastCheck == nil || time.Since(time.UnixMilli(*u.lastCheck)) > applyFreshCheckAge
+}
+
 // ApplyBy lanza update.sh en segundo plano con el iniciador dado ("admin"
 // manual o "auto" para el rolling main). Antes de lanzar registra la entrada
 // 'running' del historial (#159) y persiste el marcador pendingApply (#161);
 // la goroutine finaliza ambos según el resultado del script.
 func (u *Updater) ApplyBy(initiatedBy string) bool {
+	// #1881: el objetivo es el último chequeo, que puede tener hasta 24 h
+	// (checkInterval). Aplicar con ese estado instala una release ya superada
+	// y obliga a un segundo reinicio; refrescamos antes de elegir target. Si
+	// el chequeo falla, Check conserva el anterior: aplicar nunca depende de
+	// que GitHub responda.
+	if u.needsFreshCheck() {
+		ctx, cancel := context.WithTimeout(context.Background(), 2*httpTimeout+2*time.Second)
+		u.Check(ctx)
+		cancel()
+	}
+
 	u.mu.Lock()
 	if u.updatingStep != nil {
 		u.mu.Unlock()

+ 85 - 0
server-go/internal/updater/updater_freshcheck_test.go

@@ -0,0 +1,85 @@
+// updater_freshcheck_test.go — #1881: un apply con el chequeo viejo refresca
+// el objetivo antes de descargar (si no, instala una release ya superada y
+// necesita un segundo reinicio); con el chequeo fresco no gasta otra consulta.
+package updater
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"sync/atomic"
+	"testing"
+	"time"
+)
+
+// setLastCheck fija el instante del último chequeo (edad respecto a ahora).
+func setLastCheck(u *Updater, age time.Duration) {
+	ts := time.Now().Add(-age).UnixMilli()
+	u.mu.Lock()
+	u.lastCheck = &ts
+	u.mu.Unlock()
+}
+
+// applyTarget devuelve el objetivo que ApplyBy usaría ahora mismo.
+func applyTarget(u *Updater) string {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	if u.latest == nil {
+		return ""
+	}
+	return *u.latest
+}
+
+func TestApplyRefreshesStaleTarget(t *testing.T) {
+	var latest atomic.Value
+	latest.Store("v2.9.0")
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
+			w.WriteHeader(http.StatusNotFound)
+			return
+		}
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprintf(w, `{"tag_name":%q,"name":%q}`, latest.Load(), latest.Load())
+	})
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
+
+	if st := u.Check(context.Background()); !st.UpdateAvailable {
+		t.Fatalf("esperaba novedad: %+v", st)
+	}
+	// Escenario real: el último chequeo es de hace 24 h (checkInterval) y
+	// desde entonces salió una release nueva.
+	setLastCheck(u, 24*time.Hour)
+	latest.Store("v2.10.0")
+
+	if !u.ApplyBy("admin") {
+		t.Fatal("apply rechazado")
+	}
+	if got := applyTarget(u); got != "v2.10.0" {
+		t.Fatalf("objetivo = %q, esperaba v2.10.0 (apply con chequeo viejo)", got)
+	}
+}
+
+func TestApplyKeepsTargetWhenCheckIsFresh(t *testing.T) {
+	var hits int32
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
+			w.WriteHeader(http.StatusNotFound)
+			return
+		}
+		atomic.AddInt32(&hits, 1)
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"tag_name":"v2.9.0","name":"v2.9.0"}`)
+	})
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
+	u.Check(context.Background())
+
+	if !u.ApplyBy("admin") {
+		t.Fatal("apply rechazado")
+	}
+	if got := atomic.LoadInt32(&hits); got != 1 {
+		t.Fatalf("consultas a GitHub = %d, esperaba 1 (sin re-chequeo)", got)
+	}
+	if got := applyTarget(u); got != "v2.9.0" {
+		t.Fatalf("objetivo = %q", got)
+	}
+}