update.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // update.go — rutas /api/update/* (paridad src/routes/update.js, SPEC §2.18,
  2. // solo admin):
  3. //
  4. // GET /api/update/status → estado actual (incl. readiness + pendingApply)
  5. // POST /api/update/check → fuerza un chequeo contra GitHub
  6. // POST /api/update/apply → aplica la actualización (202 | 409)
  7. // GET /api/update/stream → SSE con el estado en cada cambio (issue #280)
  8. // GET /api/updates/history → historial de updates (issue #159)
  9. // POST /api/update/pending-confirm → descarta la confirmación post-update (issue #161)
  10. package httpapi
  11. import (
  12. "context"
  13. "encoding/json"
  14. "fmt"
  15. "net/http"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/auth"
  18. "github.com/gnacho/netpulse/server-go/internal/updater"
  19. )
  20. // registerUpdateRoutes registra las rutas /api/update/* (solo si hay updater).
  21. func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
  22. mux.Handle("GET /api/update/status", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  23. writeJSON(w, http.StatusOK, u.Status())
  24. })))
  25. // Stream SSE del estado del update (issue #280): evento inicial con el
  26. // estado completo, luego un evento por cambio de paso/progreso. El
  27. // heartbeat de 15 s mantiene la conexión viva; el stream MUERE con el
  28. // proceso durante el reinicio final (el cliente debe tratarlo como
  29. // fase "restarting" y sondear /api/health).
  30. mux.Handle("GET /api/update/stream", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  31. flusher, ok := w.(http.Flusher)
  32. if !ok {
  33. writeError(w, http.StatusInternalServerError, "streaming_unsupported")
  34. return
  35. }
  36. w.Header().Set("Content-Type", "text/event-stream")
  37. w.Header().Set("Cache-Control", "no-cache")
  38. w.Header().Set("X-Accel-Buffering", "no")
  39. ch, cancel := u.Subscribe()
  40. defer cancel()
  41. writeEvent := func(st updater.Status) {
  42. raw, err := json.Marshal(st)
  43. if err != nil {
  44. return
  45. }
  46. fmt.Fprintf(w, "event: update\ndata: %s\n\n", raw)
  47. flusher.Flush()
  48. }
  49. writeEvent(u.Status())
  50. heartbeat := time.NewTicker(15 * time.Second)
  51. defer heartbeat.Stop()
  52. for {
  53. select {
  54. case <-r.Context().Done():
  55. return
  56. case <-heartbeat.C:
  57. // Comentario SSE: mantiene viva la conexión sin evento.
  58. fmt.Fprint(w, ": ping\n\n")
  59. flusher.Flush()
  60. case st := <-ch:
  61. writeEvent(st)
  62. }
  63. }
  64. })))
  65. mux.Handle("POST /api/update/check", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  66. ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
  67. defer cancel()
  68. writeJSON(w, http.StatusOK, u.Check(ctx))
  69. })))
  70. mux.Handle("POST /api/update/apply", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  71. if !u.CanApply() {
  72. // Layout install.sh (single-binary): sin deploy/update.sh ni
  73. // permisos para swap del binario. El usuario debe re-ejecutar
  74. // install.sh (la vía documentada para estables).
  75. writeError(w, http.StatusConflict, "update_unavailable")
  76. return
  77. }
  78. if !u.Apply() {
  79. writeError(w, http.StatusConflict, "already_updating")
  80. return
  81. }
  82. writeJSON(w, http.StatusAccepted, u.Status())
  83. })))
  84. // Historial de updates (issue #159): los últimos N registros, por ahora
  85. // sin paginar (cota de 200 en ListHistory).
  86. mux.Handle("GET /api/updates/history", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  87. history, err := updater.ListHistory(s.db.DB, 50)
  88. if err != nil {
  89. writeError(w, http.StatusInternalServerError, "history_error")
  90. return
  91. }
  92. writeJSON(w, http.StatusOK, map[string]any{"history": history})
  93. })))
  94. // Descarta la confirmación post-update tras mostrarla (issue #161).
  95. mux.Handle("POST /api/update/pending-confirm", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  96. u.AckPending()
  97. w.WriteHeader(http.StatusNoContent)
  98. })))
  99. }
  100. // registerAutoUpdateSettings (#759): ajustes del auto-update programado.
  101. // Funcionan aunque el updater no esté montado (el loop simplemente no corre).
  102. func (s *server) registerAutoUpdateSettings(mux *http.ServeMux) {
  103. mux.Handle("GET /api/settings/autoupdate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  104. st := updater.LoadAutoUpdateSettings(s.db.DB)
  105. lastRun, lastResult := updater.AutoRunState(s.db.DB)
  106. out := map[string]any{
  107. "settings": st,
  108. "lastRunMs": lastRun,
  109. "lastResult": lastResult,
  110. }
  111. if st.Enabled {
  112. next := updater.NextAutoUpdateAt(st, lastRun, time.Now())
  113. if !next.IsZero() {
  114. out["nextRunMs"] = next.UnixMilli()
  115. }
  116. }
  117. writeJSON(w, http.StatusOK, out)
  118. })))
  119. mux.Handle("PUT /api/settings/autoupdate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  120. var body updater.AutoUpdateSettings
  121. if st := readJSONBody(w, r, &body); st != 0 {
  122. return
  123. }
  124. if body.Kind == "" {
  125. writeError(w, http.StatusBadRequest, "invalid_body", "kind es requerido")
  126. return
  127. }
  128. if err := updater.SaveAutoUpdateSettings(s.db.DB, body); err != nil {
  129. writeError(w, http.StatusBadRequest, "invalid_body", err.Error())
  130. return
  131. }
  132. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  133. })))
  134. }