Bläddra i källkod

fix(updater): match marker by prefix and surface human-readable update errors (#512) (#515)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 månader sedan
förälder
incheckning
c6df3a192d

+ 7 - 0
app/public/locales/en/translation.json

@@ -1379,6 +1379,13 @@
       "changelogFallback": "Could not load changelog.",
       "changelogLink": "View release notes on GitHub",
       "downNotice": "The service will be down while it restarts"
+    },
+    "errors": {
+      "exitRestart": "The server restarted itself to apply the update (the normal final step). If the version has not changed in a few minutes, check for updates again.",
+      "exitCode": "The update process exited with code {{code}}. Check the update log for details.",
+      "noTarget": "No target version known: check for updates before applying.",
+      "noToken": "GitHub request limit reached; it resets within the hour. Try again later.",
+      "generic": "The update failed ({{code}}). Check the update log for details."
     }
   },
   "demo": {

+ 7 - 0
app/public/locales/es/translation.json

@@ -1379,6 +1379,13 @@
       "changelogFallback": "No se ha podido cargar el changelog.",
       "changelogLink": "Ver notas del release en GitHub",
       "downNotice": "El servicio estará caído mientras se reinicia"
+    },
+    "errors": {
+      "exitRestart": "El servidor se reinició para aplicar la actualización (el paso final normal). Si en unos minutos la versión no ha cambiado, vuelve a comprobar actualizaciones.",
+      "exitCode": "El proceso de actualización terminó con el código {{code}}. Revisa el registro para más detalle.",
+      "noTarget": "No se conoce la versión objetivo: comprueba actualizaciones antes de aplicar.",
+      "noToken": "Se alcanzó el límite de peticiones a GitHub; se recupera solo en la próxima hora. Reintenta más tarde.",
+      "generic": "La actualización falló ({{code}}). Revisa el registro para más detalle."
     }
   },
   "demo": {

+ 3 - 1
app/src/components/UpdateDialog.tsx

@@ -28,6 +28,7 @@ import { Progress } from '@/components/ui/progress'
 import { Button } from '@/components/ui/button'
 import { Checkbox } from '@/components/ui/checkbox'
 import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
+import { updateErrorText } from '@/lib/updateErrors'
 
 /** Commit entre current y latest (compare de GitHub, issue #490). */
 export interface UpdateCommit {
@@ -470,7 +471,8 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
               <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-danger" strokeWidth={1.75} aria-hidden="true" />
               <div className="min-w-0">
                 <p className="text-sm font-medium text-danger">{t('update.dialog.failed')}</p>
-                {errorCode && <p className="mt-0.5 font-mono text-caption text-text-muted">{errorCode}</p>}
+                <p className="mt-0.5 text-caption text-text-secondary">{updateErrorText(t, errorCode)}</p>
+                {errorCode && <p className="mt-0.5 font-mono text-[11px] text-text-muted">{errorCode}</p>}
               </div>
             </div>
             <DialogFooter>

+ 14 - 0
app/src/lib/updateErrors.ts

@@ -0,0 +1,14 @@
+// updateErrors.ts — traduce los códigos de error del updater a texto
+// humano (#512): "update_exit_-1" no le dice nada a nadie. El código crudo
+// se sigue mostrando como detalle pequeño para depuración.
+import type { TFunction } from 'i18next'
+
+export function updateErrorText(t: TFunction, code: string | null | undefined): string {
+  if (!code) return ''
+  if (code === 'update_exit_-1') return t('update.errors.exitRestart')
+  const m = /^update_exit_(-?\d+)$/.exec(code)
+  if (m) return t('update.errors.exitCode', { code: m[1] })
+  if (code === 'stable_no_target') return t('update.errors.noTarget')
+  if (code === 'no_token') return t('update.errors.noToken')
+  return t('update.errors.generic', { code })
+}

+ 12 - 0
server-go/internal/updater/history.go

@@ -156,3 +156,15 @@ func ListHistory(db *sql.DB, limit int) ([]HistoryEntry, error) {
 	}
 	return out, rows.Err()
 }
+
+// updateHistoryTarget rectifica el version_to de una entrada en curso (#512
+// drift: main avanzó entre el check y el fetch; el marcador del script lleva
+// el SHA realmente instalado).
+func (u *Updater) updateHistoryTarget(id int64, to string) {
+	if u.db == nil || id < 0 || to == "" {
+		return
+	}
+	if _, err := u.db.Exec(`UPDATE update_history SET version_to = ? WHERE id = ?`, to, id); err != nil {
+		fmt.Printf("[netpulse] no se pudo rectificar el target del historial: %v\n", err)
+	}
+}

+ 21 - 0
server-go/internal/updater/pending.go

@@ -131,3 +131,24 @@ func (u *Updater) AckPending() {
 	u.pendingApply = nil
 	u.mu.Unlock()
 }
+
+// retargetPendingApply rectifica el To del marcador persistido (#512 drift):
+// la confirmación post-arranque compara el commit del binario nuevo, que es
+// el SHA del marcador, no el que el check vio al lanzar el apply.
+func (u *Updater) retargetPendingApply(to string) {
+	if u.db == nil || to == "" {
+		return
+	}
+	p, ok := readPendingApply(u.db)
+	if !ok || p.To == to {
+		return
+	}
+	p.To = to
+	data, err := json.Marshal(p)
+	if err != nil {
+		return
+	}
+	_, _ = u.db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		pendingApplyKey, string(data))
+}

+ 42 - 6
server-go/internal/updater/updater.go

@@ -711,12 +711,20 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 			u.lastLog = &log
 			u.updateAvail = false
 			u.finishHistory(historyID, "success", "", dur)
-		} else if marker := readAppliedMarker(u.appliedMarkerPath()); marker != "" && to != nil && marker == strings.TrimSpace(*to) {
-			// #444: el reinicio diferido (systemd.path) mata el script justo
-			// después del swap. Si el marcador pre-reinicio lleva el SHA
-			// objetivo, esto es el camino de éxito, no un fallo: se registra
-			// success y se MANTIENE el pendingApply para la confirmación
-			// post-reinicio (#161).
+		} else if marker := readAppliedMarker(u.appliedMarkerPath()); marker != "" {
+			// #444/#512: el reinicio diferido (systemd.path) mata el script
+			// justo después del swap. Si el marcador pre-reinicio existe, el
+			// swap se hizo y pidió el reinicio: es el camino de éxito, no un
+			// fallo. update.sh escribe el SHA COMPLETO (git rev-parse) y el
+			// check guarda el corto, así que se compara por prefijo (#512).
+			// Si además el SHA no casa con el target registrado, main avanzó
+			// entre el check y el fetch: el marcador es la verdad del terreno
+			// y se rectifican historial y pendingApply al SHA instalado.
+			if to != nil && !markerMatchesTarget(marker, *to) {
+				short := shortSHA(marker)
+				u.updateHistoryTarget(historyID, short)
+				u.retargetPendingApply(short)
+			}
 			u.setStepLocked("done")
 			log := u.updatingLog
 			u.lastLog = &log
@@ -900,3 +908,31 @@ func readAppliedMarker(path string) string {
 	}
 	return strings.TrimSpace(string(b))
 }
+
+// markerMatchesTarget compara el SHA del marcador (completo, 40 chars, lo
+// que escribe `git rev-parse HEAD` en update.sh) con el target registrado
+// (corto, 7 chars, lo que guarda el check) por PREFIJO y sin distinguir
+// mayúsculas (#512: la igualdad literal hacía imposible el camino de éxito
+// de #444 y todo apply con reinicio registraba "update_exit_-1").
+func markerMatchesTarget(marker, target string) bool {
+	m := strings.ToLower(strings.TrimSpace(marker))
+	t := strings.ToLower(strings.TrimSpace(target))
+	if m == "" || t == "" {
+		return false
+	}
+	n := len(m)
+	if len(t) < n {
+		n = len(t)
+	}
+	return m[:n] == t[:n]
+}
+
+// shortSHA trunca un SHA al formato corto de display (7 chars), aceptando
+// ambos formatos como entrada.
+func shortSHA(sha string) string {
+	s := strings.TrimSpace(sha)
+	if len(s) > 7 {
+		return s[:7]
+	}
+	return s
+}

+ 95 - 0
server-go/internal/updater/updater_restart_test.go

@@ -103,3 +103,98 @@ func TestApplyKilledWithoutMarkerIsFailure(t *testing.T) {
 		t.Fatalf("historial: esperaba failed, got %+v", hist)
 	}
 }
+
+// #512: update.sh escribe el marcador con el SHA COMPLETO (git rev-parse
+// HEAD, 40 chars) mientras el check guarda el corto (7): la igualdad literal
+// de #444 jamás casaba y todo apply con reinicio registraba "failed
+// update_exit_-1" aunque el binario nuevo arrancara perfectamente.
+func TestApplyKilledAfterFullLengthMarkerIsSuccess(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeGitHead(t, root)
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	full := "abc1234deadbeeffed9999aaaabbbbccccdddd" // lo que git rev-parse HEAD escribe de verdad
+	script := "#!/bin/bash\necho STEP:install\necho " + full + " > '" + root + "/.update-applied'\nkill -9 $$\n"
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"sha":"`+full+`","commit":{"message":"feat: algo"}}`)
+	})
+	dbh := openDB(t)
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	u.Check(context.Background()) // latest = abc1234 (corto)
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	waitDone(t, u)
+
+	st := u.Status()
+	if st.Error != nil {
+		t.Fatalf("#512 falso fallo: %v (el marcador largo debe casar con el target corto)", *st.Error)
+	}
+	if _, ok := readPendingApply(dbh); !ok {
+		t.Fatal("pendingApply debe persistirse para la confirmación post-reinicio")
+	}
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 || hist[0].Status != "success" {
+		t.Fatalf("historial: esperaba success, got %+v", hist)
+	}
+}
+
+// #512 variante drift: main avanzó entre el check y el fetch del script, así
+// que el marcador lleva OTRO SHA que el target registrado. El marcador es la
+// verdad del terreno (el swap se hizo y pidió reinicio): success con nota y
+// el target del historial/pending actualizado al SHA realmente instalado.
+func TestApplyKilledAfterDriftedMarkerIsSuccess(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	writeGitHead(t, root)
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	drifted := "fedcba9876543210fedcba9876543210fedcba98"
+	script := "#!/bin/bash\necho STEP:install\necho " + drifted + " > '" + root + "/.update-applied'\nkill -9 $$\n"
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"sha":"abc1234deadbeeffed9999aaaabbbbccccdddd","commit":{"message":"feat: algo"}}`)
+	})
+	dbh := openDB(t)
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	u.Check(context.Background()) // latest = abc1234
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	waitDone(t, u)
+
+	st := u.Status()
+	if st.Error != nil {
+		t.Fatalf("drift tratado como fallo: %v (el marcador manda)", *st.Error)
+	}
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 || hist[0].Status != "success" {
+		t.Fatalf("historial: esperaba success, got %+v", hist)
+	}
+	if hist[0].VersionTo == nil || *hist[0].VersionTo != "fedcba9" {
+		t.Fatalf("version_to debe reflejar el SHA instalado (fedcba9), got %+v", hist[0].VersionTo)
+	}
+	if p, ok := readPendingApply(dbh); !ok || p.To != "fedcba9" {
+		t.Fatalf("pendingApply.To debe ser el SHA instalado para que la confirmación post-arranque case: %+v", p)
+	}
+}