recurrence.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // recurrence.go - programación recurrente de firmware por router (#761).
  2. //
  3. // Patrón de speedtest (#744) y backups (#741): ajustes en kv, vencimiento
  4. // derivado del last_run PERSISTIDO (reinicios/auto-update no resetean el
  5. // reloj) y decisión pura RecurrenceDue. La ejecución es idempotente por
  6. // contrato: el disparo solo flashea si la versión instalada difiere del
  7. // target guardado; un router al día es un no-op silencioso.
  8. package firmware
  9. import (
  10. "database/sql"
  11. "fmt"
  12. "log"
  13. "strconv"
  14. "time"
  15. )
  16. // Kinds de recurrencia.
  17. const (
  18. RecurrenceOnce = "once"
  19. RecurrenceWeekly = "weekly"
  20. RecurrenceMonthly = "monthly"
  21. )
  22. // Recurrence es la programación persistida de un router.
  23. type Recurrence struct {
  24. Enabled bool `json:"enabled"`
  25. // Kind: once (AtMs fijo, se desactiva tras disparar) | weekly
  26. // (DayOfWeek a Time local) | monthly (DayOfMonth a Time local; clamp
  27. // al último día si el mes no lo tiene).
  28. Kind string `json:"kind"`
  29. AtMs int64 `json:"atMs,omitempty"` // once, epoch ms
  30. DayOfWeek *int `json:"dayOfWeek,omitempty"` // 0=domingo..6 (weekly)
  31. DayOfMonth *int `json:"dayOfMonth,omitempty"` // 1..31 (monthly)
  32. Time string `json:"time,omitempty"` // "HH:MM" hora local
  33. LastRunMs int64 `json:"lastRunMs,omitempty"` // último disparo (cualquier resultado)
  34. }
  35. // ValidateRecurrence comprueba la coherencia kind/campos (patrón speedtest).
  36. func ValidateRecurrence(rc Recurrence) error {
  37. switch rc.Kind {
  38. case RecurrenceOnce:
  39. if rc.AtMs <= 0 {
  40. return fmt.Errorf("once requires atMs (epoch ms)")
  41. }
  42. case RecurrenceWeekly:
  43. if rc.DayOfWeek == nil || *rc.DayOfWeek < 0 || *rc.DayOfWeek > 6 {
  44. return fmt.Errorf("weekly requires dayOfWeek 0-6 (0 = Sunday)")
  45. }
  46. if !validRecTime(rc.Time) {
  47. return fmt.Errorf("weekly requires time HH:MM")
  48. }
  49. case RecurrenceMonthly:
  50. if rc.DayOfMonth == nil || *rc.DayOfMonth < 1 || *rc.DayOfMonth > 31 {
  51. return fmt.Errorf("monthly requires dayOfMonth 1-31")
  52. }
  53. if !validRecTime(rc.Time) {
  54. return fmt.Errorf("monthly requires time HH:MM")
  55. }
  56. default:
  57. return fmt.Errorf("kind must be once, weekly or monthly")
  58. }
  59. return nil
  60. }
  61. // RecurrenceDue decide si toca disparar (función pura). El vencimiento
  62. // siempre deriva de LastRunMs: weekly exige día exacto de la semana y que el
  63. // slot de hoy sea posterior al último disparo; monthly aplica clamp de fin de
  64. // mes; once dispara una única vez (AtMs) aunque LastRunMs sea 0.
  65. func RecurrenceDue(rc Recurrence, now time.Time) bool {
  66. if !rc.Enabled {
  67. return false
  68. }
  69. switch rc.Kind {
  70. case RecurrenceOnce:
  71. return now.UnixMilli() >= rc.AtMs && rc.LastRunMs < rc.AtMs
  72. case RecurrenceWeekly:
  73. dow := 0
  74. if rc.DayOfWeek != nil {
  75. dow = *rc.DayOfWeek
  76. }
  77. if int(now.Weekday()) != dow {
  78. return false
  79. }
  80. slot := recTodaySlot(rc.Time, now)
  81. return !now.Before(slot) && rc.LastRunMs < slot.UnixMilli()
  82. case RecurrenceMonthly:
  83. dom := 1
  84. if rc.DayOfMonth != nil {
  85. dom = *rc.DayOfMonth
  86. }
  87. h, m := recParseTime(rc.Time)
  88. slot := time.Date(now.Year(), now.Month(), recClampDay(dom, now), h, m, 0, 0, now.Location())
  89. return !now.Before(slot) && rc.LastRunMs < slot.UnixMilli()
  90. }
  91. return false
  92. }
  93. // NextRecurrenceAt calcula el próximo disparo para la UI (Status).
  94. func NextRecurrenceAt(rc Recurrence, now time.Time) time.Time {
  95. h, m := recParseTime(rc.Time)
  96. switch rc.Kind {
  97. case RecurrenceOnce:
  98. return time.UnixMilli(rc.AtMs)
  99. case RecurrenceWeekly:
  100. dow := 0
  101. if rc.DayOfWeek != nil {
  102. dow = *rc.DayOfWeek
  103. }
  104. today := recTodaySlot(rc.Time, now)
  105. if int(now.Weekday()) == dow && (now.Before(today) || rc.LastRunMs < today.UnixMilli()) {
  106. return today
  107. }
  108. days := (dow - int(now.Weekday()) + 7) % 7
  109. if days == 0 {
  110. days = 7
  111. }
  112. d := now.AddDate(0, 0, days)
  113. return time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, now.Location())
  114. case RecurrenceMonthly:
  115. dom := 1
  116. if rc.DayOfMonth != nil {
  117. dom = *rc.DayOfMonth
  118. }
  119. slot := time.Date(now.Year(), now.Month(), recClampDay(dom, now), h, m, 0, 0, now.Location())
  120. if now.Before(slot) || rc.LastRunMs < slot.UnixMilli() {
  121. return slot
  122. }
  123. next := now.AddDate(0, 1, 0)
  124. return time.Date(next.Year(), next.Month(), recClampDay(dom, next), h, m, 0, 0, now.Location())
  125. }
  126. return time.Time{}
  127. }
  128. // --- Persistencia kv (claves firmware.recurrence.<router>.<campo>) ---
  129. func recKey(routerID, field string) string {
  130. return "firmware.recurrence." + routerID + "." + field
  131. }
  132. // LoadRecurrence lee la programación del router (valores ausentes = default).
  133. func LoadRecurrence(db *sql.DB, routerID string) Recurrence {
  134. rc := Recurrence{}
  135. if db == nil || routerID == "" {
  136. return rc
  137. }
  138. rc.Enabled = recKVGet(db, recKey(routerID, "enabled")) == "1"
  139. rc.Kind = recKVGet(db, recKey(routerID, "kind"))
  140. rc.AtMs = recKVParseInt(db, recKey(routerID, "at_ms"))
  141. rc.LastRunMs = recKVParseInt(db, recKey(routerID, "last_run"))
  142. if v, ok := recKVIntPtr(db, recKey(routerID, "dow")); ok {
  143. rc.DayOfWeek = v
  144. }
  145. if v, ok := recKVIntPtr(db, recKey(routerID, "dom")); ok {
  146. rc.DayOfMonth = v
  147. }
  148. rc.Time = recKVGet(db, recKey(routerID, "time"))
  149. return rc
  150. }
  151. // SaveRecurrence persiste la programación completa (UPSERT por clave).
  152. func SaveRecurrence(db *sql.DB, routerID string, rc Recurrence) error {
  153. if db == nil || routerID == "" {
  154. return fmt.Errorf("firmware: empty db or router")
  155. }
  156. if err := ValidateRecurrence(rc); err != nil {
  157. return err
  158. }
  159. recKVSet(db, recKey(routerID, "enabled"), boolRecStr(rc.Enabled))
  160. recKVSet(db, recKey(routerID, "kind"), rc.Kind)
  161. recKVSet(db, recKey(routerID, "at_ms"), strconv.FormatInt(rc.AtMs, 10))
  162. recKVSet(db, recKey(routerID, "last_run"), strconv.FormatInt(rc.LastRunMs, 10))
  163. dow, dom := "", ""
  164. if rc.DayOfWeek != nil {
  165. dow = strconv.Itoa(*rc.DayOfWeek)
  166. }
  167. if rc.DayOfMonth != nil {
  168. dom = strconv.Itoa(*rc.DayOfMonth)
  169. }
  170. recKVSet(db, recKey(routerID, "dow"), dow)
  171. recKVSet(db, recKey(routerID, "dom"), dom)
  172. recKVSet(db, recKey(routerID, "time"), rc.Time)
  173. return nil
  174. }
  175. // SetRecurrenceLastRun actualiza solo el último disparo (lo toca el loop).
  176. func SetRecurrenceLastRun(db *sql.DB, routerID string, ms int64) {
  177. recKVSet(db, recKey(routerID, "last_run"), strconv.FormatInt(ms, 10))
  178. }
  179. // DisableRecurrence apaga la programación (config inválida detectada en
  180. // runtime: sin target guardado, etc.).
  181. func DisableRecurrence(db *sql.DB, routerID string) {
  182. recKVSet(db, recKey(routerID, "enabled"), "0")
  183. }
  184. // --- helpers (patrón speedtest, locales del paquete) ---
  185. func validRecTime(v string) bool {
  186. if v == "" {
  187. return false
  188. }
  189. _, err := time.Parse("15:04", v)
  190. return err == nil
  191. }
  192. func recParseTime(v string) (int, int) {
  193. t, err := time.Parse("15:04", v)
  194. if err != nil {
  195. return 0, 0
  196. }
  197. return t.Hour(), t.Minute()
  198. }
  199. func recDaysInMonth(t time.Time) int {
  200. return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()).Day()
  201. }
  202. func recClampDay(dom int, t time.Time) int {
  203. if dom < 1 {
  204. dom = 1
  205. }
  206. if max := recDaysInMonth(t); dom > max {
  207. dom = max
  208. }
  209. return dom
  210. }
  211. func recTodaySlot(v string, now time.Time) time.Time {
  212. h, m := recParseTime(v)
  213. return time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, now.Location())
  214. }
  215. func boolRecStr(b bool) string {
  216. if b {
  217. return "1"
  218. }
  219. return "0"
  220. }
  221. func recKVGet(db *sql.DB, key string) string {
  222. var v string
  223. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  224. return ""
  225. }
  226. return v
  227. }
  228. func recKVParseInt(db *sql.DB, key string) int64 {
  229. n, _ := strconv.ParseInt(recKVGet(db, key), 10, 64)
  230. return n
  231. }
  232. func recKVIntPtr(db *sql.DB, key string) (*int, bool) {
  233. raw := recKVGet(db, key)
  234. if raw == "" {
  235. return nil, false
  236. }
  237. n, err := strconv.Atoi(raw)
  238. if err != nil {
  239. return nil, false
  240. }
  241. return &n, true
  242. }
  243. func recKVSet(db *sql.DB, key, val string) {
  244. if _, err := db.Exec(
  245. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  246. key, val); err != nil {
  247. log.Printf("[netpulse:firmware] kv set %s: %v", key, err)
  248. }
  249. }