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

fix(updater): surface a failed update check instead of a stale up-to-date message (#743) (#753)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
c9b6913b5e

+ 4 - 0
CHANGELOG.md

@@ -9,6 +9,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- **"Comprobar actualizaciones" ya no dice que estás en la última versión cuando no pudo comprobar (#743)**: si el fetch a GitHub fallaba (límite de la API anónima, red, timeout), el botón devolvía el estado del último check exitoso -posiblemente de hace 24 h- sin ninguna señal, y la UI lo pintaba como "estás en la última versión". El reportero lo clavó: una release publicada dos horas antes no aparecía. Ahora el estado lleva `checkFailed` con el motivo (límite de GitHub sin token, sin conexión) y la UI muestra "No se pudo comprobar ahora (motivo); inténtalo de nuevo en unos minutos" en lugar de un falso todo-ok.
+
+### Fixed
+
 - **El test de velocidad ya no mide basura cuando la URL del servidor apunta a la web de Ookla (#744)**: la tarjeta de ajustes traía `https://speedtest.net` como valor por defecto, placeholder y botón "Restaurar" (no es un servidor de pruebas, es la web), y cualquier guardado escribía esa URL en la config: el resultado era una bajada capada, una subida ~0 y un servidor sin nombre. Ahora el campo nace vacío (autoselección), el botón pasa a "Automático", el servidor rechaza la trampa con un mensaje claro, un saneado al arranque limpia la URL trampa de instalaciones existentes, y una medición con bajada o subida <= 0 se descarta con error en vez de ensuciar la serie.
 
 ### Added

+ 4 - 1
app/public/locales/en/translation.json

@@ -1114,7 +1114,10 @@
       "sysCpu": "CPU",
       "sysRam": "RAM",
       "sysUptime": "Uptime",
-      "demoNoServer": "Server data unavailable (demo)"
+      "demoNoServer": "Server data unavailable (demo)",
+      "checkFailed": "Could not check right now ({{reason}}); try again in a few minutes",
+      "checkErrRate": "GitHub API limit without a token",
+      "checkErrNet": "no connection to GitHub"
     },
     "accent": "Accent",
     "accentAmber": "Amber",

+ 4 - 1
app/public/locales/es/translation.json

@@ -1114,7 +1114,10 @@
       "sysCpu": "CPU",
       "sysRam": "RAM",
       "sysUptime": "Tiempo activo",
-      "demoNoServer": "Datos del servidor no disponibles (demo)"
+      "demoNoServer": "Datos del servidor no disponibles (demo)",
+      "checkFailed": "No se pudo comprobar ahora ({{reason}}); inténtalo de nuevo en unos minutos",
+      "checkErrRate": "límite de la API de GitHub sin token",
+      "checkErrNet": "sin conexión con GitHub"
     },
     "accent": "Acento",
     "accentAmber": "Ámbar",

+ 20 - 0
app/src/pages/Settings.tsx

@@ -3253,6 +3253,22 @@ interface NetPulseUpdateStatus {
   repo: string
   updating: false | { step: string }
   readiness?: UpdateReadiness | null
+  checkFailed?: boolean
+  checkErr?: string
+}
+
+// checkErrText mapea el errCode crudo del updater a un motivo humano (#743).
+function checkErrText(err: string | undefined, t: (k: string) => string): string {
+  switch (err) {
+    case 'no_token':
+    case 'github_403':
+      return t('settings.about.checkErrRate')
+    case 'network':
+    case 'timeout':
+      return t('settings.about.checkErrNet')
+    default:
+      return err || t('settings.about.checkErrNet')
+  }
 }
 
 function UpdateCheckInline() {
@@ -3328,6 +3344,10 @@ function UpdateCheckInline() {
         <span className="text-[10px] font-medium text-accent">
           {t('settings.about.updateAvailable', { version: status.latest })}
         </span>
+      ) : status?.checkFailed ? (
+        <span role="alert" className="text-[10px] font-medium text-warn">
+          {t('settings.about.checkFailed', { reason: checkErrText(status.checkErr, t) })}
+        </span>
       ) : status?.updateAvailable === false ? (
         <span className="text-[10px] font-medium text-ok">{t('settings.about.upToDateShort')}</span>
       ) : error ? (

+ 29 - 15
server-go/internal/updater/updater.go

@@ -89,12 +89,18 @@ type Status struct {
 	// actualización o el compare falló: la UI cae a latestBody.
 	Commits []CommitRef `json:"commits,omitempty"`
 	// CompareURL: enlace web al compare completo current...latest (#490).
-	CompareURL string    `json:"compareUrl,omitempty"`
-	Updating   any       `json:"updating"` // false | {"step": ...}
-	Error      *string   `json:"error"`
-	LastLog    *string   `json:"lastLog"`
-	Repo       string    `json:"repo"`
-	HasToken   bool      `json:"hasToken"`
+	CompareURL string  `json:"compareUrl,omitempty"`
+	Updating   any     `json:"updating"` // false | {"step": ...}
+	Error      *string `json:"error"`
+	LastLog    *string `json:"lastLog"`
+	Repo       string  `json:"repo"`
+	HasToken   bool    `json:"hasToken"`
+	// CheckFailed (#743): el último Check no pudo completar el fetch a
+	// GitHub (rate limit anónimo, red, timeout). UpdateAvailable refleja
+	// entonces el último estado CONOCIDO, no una comprobación fresca: la UI
+	// debe mostrar "no se pudo comprobar" en vez de "estás en la última".
+	CheckFailed bool   `json:"checkFailed,omitempty"`
+	CheckErr    string `json:"checkErr,omitempty"`
 	// Readiness: pre-flight checks del apply (issue #160). Null en layout
 	// estable (sin auto-apply) o hasta el primer Status().
 	Readiness *Readiness `json:"readiness,omitempty"`
@@ -118,18 +124,20 @@ type Updater struct {
 	// persistencia deshabilitada (tests sin BD).
 	db *sql.DB
 
-	mu           sync.Mutex
-	current      string
-	latest       *string
-	latestMsg    *string
-	latestBody   *string // cuerpo del commit/notas del release (changelog #280)
+	mu         sync.Mutex
+	current    string
+	latest     *string
+	latestMsg  *string
+	latestBody *string // cuerpo del commit/notas del release (changelog #280)
 	// compare de GitHub cacheado (issue #490): commits current→latest y
 	// clave "current|latest" del último fetch para no repetir la consulta.
-	commits    []CommitRef
-	compareURL string
-	compareKey string
+	commits      []CommitRef
+	compareURL   string
+	compareKey   string
 	updateAvail  bool
 	lastCheck    *int64
+	checkFailed  bool    // #743: el último Check no llegó a completarse
+	checkErr     string  // #743: errCode del último Check fallido
 	updatingStep *string // nil = no actualizando
 	updatingPct  int     // 0-100 (issue #280); peso del paso o PROGRESS explícito
 	updatingLog  string
@@ -517,10 +525,14 @@ func (u *Updater) Check(ctx context.Context) Status {
 	u.current = current
 	u.lastCheck = &now
 	if errCode != "" {
-		u.err = &errCode // no_token no es un error visible: el banner no aparece
+		u.err = &errCode
+		u.checkFailed = true
+		u.checkErr = errCode // no_token no lanza el banner (#743): solo marca el check como fallido
 		return u.statusLocked()
 	}
 	u.err = nil
+	u.checkFailed = false
+	u.checkErr = ""
 	u.latest = &latest
 	u.latestMsg = &latestMsg
 	u.latestBody = &latestBody
@@ -850,6 +862,8 @@ func (u *Updater) statusLocked() Status {
 		LastLog:         lastLog,
 		Repo:            u.repo,
 		HasToken:        u.token != "",
+		CheckFailed:     u.checkFailed,
+		CheckErr:        u.checkErr,
 		PendingApply:    u.pendingApply,
 	}
 }

+ 72 - 0
server-go/internal/updater/updater743_test.go

@@ -0,0 +1,72 @@
+// updater743_test.go — #743: cuando el fetch a GitHub falla (rate limit
+// anónimo, red), el status debe declarar checkFailed en vez de presentar el
+// último estado conocido como "estás en la última versión".
+package updater
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"testing"
+)
+
+func TestCheckFailureIsVisibleAndRecovers(t *testing.T) {
+	var fail bool
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if fail {
+			w.WriteHeader(http.StatusForbidden) // rate limit anónimo de GitHub
+			return
+		}
+		if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
+			w.WriteHeader(http.StatusNotFound)
+			return
+		}
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"tag_name":"v2.1.0","name":"v2.1.0","body":"notas"}`)
+	})
+
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil).WithDataDir(t.TempDir())
+
+	// Escenario del reporte: el check falla tras publicarse una release
+	// nueva. El estado debe declarar el fallo y NO celebrar "última versión".
+	fail = true
+	st := u.Check(context.Background())
+	if !st.CheckFailed {
+		t.Fatal("un check fallido debe marcarse como checkFailed")
+	}
+	if st.CheckErr == "" {
+		t.Fatal("checkErr debe llevar el errCode (no_token/github_403)")
+	}
+	if st.UpdateAvailable {
+		t.Fatal("con el fetch caído no puede afirmarse que hay actualización")
+	}
+
+	// Recuperación: GitHub responde y hay una release mayor instalada.
+	fail = false
+	st2 := u.Check(context.Background())
+	if st2.CheckFailed {
+		t.Fatalf("un check exitoso debe limpiar checkFailed: %+v", st2)
+	}
+	if !st2.UpdateAvailable || st2.Latest == nil || *st2.Latest != "v2.1.0" {
+		t.Fatalf("debe detectar v2.1.0 sobre 2.0.0: %+v", st2)
+	}
+}
+
+func TestCheckSuccessKeepsCheckFailedClean(t *testing.T) {
+	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.Fprint(w, `{"tag_name":"v2.0.0","name":"v2.0.0","body":"notas"}`)
+	})
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil).WithDataDir(t.TempDir())
+	st := u.Check(context.Background())
+	if st.CheckFailed || st.CheckErr != "" {
+		t.Fatalf("check sano no debe marcar fallo: %+v", st)
+	}
+	if st.UpdateAvailable {
+		t.Fatal("misma versión: no hay actualización")
+	}
+}