pending.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // pending.go — confirmación post-update (issue #161): antes de aplicar se
  2. // persiste un marcador from→to en kv; en el siguiente arranque se compara el
  3. // commit actual. Si cambió → se expone la confirmación (toast "Actualizado a
  4. // <sha>" en el frontend); si no → se limpia en silencio (el apply falló). El
  5. // marcador se borra en ambos casos, así que la confirmación es de una sola vez.
  6. package updater
  7. import (
  8. "database/sql"
  9. "encoding/json"
  10. "fmt"
  11. "os"
  12. "strings"
  13. )
  14. // pendingApplyKey es la clave kv del marcador pre-update.
  15. const pendingApplyKey = "update.pending_apply"
  16. // PendingApply es el marcador from→to y, tras un arranque con confirmación,
  17. // el valor expuesto en /api/update/status (campo `pendingApply`). To es el
  18. // SHA que quedó corriendo tras el arranque confirmado.
  19. type PendingApply struct {
  20. From string `json:"from"`
  21. To string `json:"to"`
  22. }
  23. // persistPendingApply guarda el marcador en kv (best-effort; sin BD → no-op).
  24. func (u *Updater) persistPendingApply(from string, to *string) {
  25. if u.db == nil {
  26. return
  27. }
  28. p := PendingApply{From: from}
  29. if to != nil {
  30. p.To = *to
  31. }
  32. data, err := json.Marshal(p)
  33. if err != nil {
  34. return
  35. }
  36. if _, err := u.db.Exec(
  37. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  38. pendingApplyKey, string(data)); err != nil {
  39. fmt.Printf("[netpulse] could not persist the update marker: %v\n", err)
  40. }
  41. }
  42. // clearPendingApply borra el marcador (apply falló o ya confirmado).
  43. func (u *Updater) clearPendingApply() {
  44. if u.db == nil {
  45. return
  46. }
  47. _, _ = u.db.Exec(`DELETE FROM kv WHERE key = ?`, pendingApplyKey)
  48. }
  49. // readPendingApply lee el marcador del kv (false si no existe o es inválido).
  50. func readPendingApply(db *sql.DB) (PendingApply, bool) {
  51. var v string
  52. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", pendingApplyKey).Scan(&v); err != nil {
  53. return PendingApply{}, false
  54. }
  55. var p PendingApply
  56. if json.Unmarshal([]byte(v), &p) != nil || p.From == "" {
  57. return PendingApply{}, false
  58. }
  59. return p, true
  60. }
  61. // loadPendingApply se ejecuta al crear el updater (cada arranque): finaliza
  62. // historial interrumpido y procesa el marcador pendiente si lo hay.
  63. func (u *Updater) loadPendingApply() {
  64. if u.db == nil {
  65. return
  66. }
  67. u.finalizeInterrupted()
  68. if u.mode != "rolling" {
  69. // #480: en estable el marcador de éxito vive en el dataDir, que
  70. // llega DESPUÉS de New (WithDataDir) → la confirmación va allí.
  71. return
  72. }
  73. p, ok := readPendingApply(u.db)
  74. if !ok {
  75. return
  76. }
  77. defer u.clearPendingApply()
  78. now := gitShort(u.repoRoot)
  79. if now == "" || now == p.From {
  80. return // sin cambio o commit desconocido → silencioso
  81. }
  82. u.mu.Lock()
  83. u.pendingApply = &PendingApply{From: p.From, To: now}
  84. u.mu.Unlock()
  85. fmt.Printf("[netpulse] update confirmado: %s → %s\n", p.From, now)
  86. }
  87. // loadStablePending confirma (o descarta en silencio) el apply estable
  88. // pendiente una vez el dataDir está disponible (#480). Idempotente: sin
  89. // marcador en kv no hace nada. El apply estable mata el proceso con el
  90. // restart, así que este es el único sitio donde el éxito se puede registrar:
  91. // exige el marcador de éxito del helper con el objetivo esperado (patrón
  92. // #444) y re-marca el historial que finalizeInterrupted dejó como fallido.
  93. func (u *Updater) loadStablePending() {
  94. if u.db == nil || u.dataDir == "" {
  95. return
  96. }
  97. p, ok := readPendingApply(u.db)
  98. if !ok {
  99. return
  100. }
  101. defer u.clearPendingApply()
  102. now := u.version
  103. if now == "" || now == "desconocido" || now == p.From {
  104. return // sin cambio o versión desconocida → silencioso
  105. }
  106. marker := readAppliedMarker(u.appliedMarkerPath())
  107. if marker == "" || (p.To != "" && marker != strings.TrimSpace(p.To)) {
  108. fmt.Printf("[netpulse] stable apply without a success marker (marker=%q, target=%q), not confirming\n", marker, p.To)
  109. return
  110. }
  111. _ = os.Remove(u.appliedMarkerPath())
  112. u.markInterruptedAsSuccess(strings.TrimSpace(p.To))
  113. u.mu.Lock()
  114. u.pendingApply = &PendingApply{From: p.From, To: now}
  115. u.mu.Unlock()
  116. fmt.Printf("[netpulse] update confirmado: %s → %s\n", p.From, now)
  117. }
  118. // AckPending confirma y descarta el pendingApply en memoria (una sola vez:
  119. // el frontend lo muestra y llama a POST /api/update/pending-confirm).
  120. func (u *Updater) AckPending() {
  121. u.mu.Lock()
  122. u.pendingApply = nil
  123. u.mu.Unlock()
  124. }
  125. // retargetPendingApply rectifica el To del marcador persistido (#512 drift):
  126. // la confirmación post-arranque compara el commit del binario nuevo, que es
  127. // el SHA del marcador, no el que el check vio al lanzar el apply.
  128. func (u *Updater) retargetPendingApply(to string) {
  129. if u.db == nil || to == "" {
  130. return
  131. }
  132. p, ok := readPendingApply(u.db)
  133. if !ok || p.To == to {
  134. return
  135. }
  136. p.To = to
  137. data, err := json.Marshal(p)
  138. if err != nil {
  139. return
  140. }
  141. _, _ = u.db.Exec(
  142. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  143. pendingApplyKey, string(data))
  144. }