|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/flatrun/agent/pkg/config" |
| 8 | + "github.com/gin-gonic/gin" |
| 9 | +) |
| 10 | + |
| 11 | +func (s *Server) listConfig(c *gin.Context) { |
| 12 | + entries := config.Walk(s.config) |
| 13 | + c.JSON(http.StatusOK, gin.H{ |
| 14 | + "config": entries, |
| 15 | + "runtime": s.runtimeConfigKeys(), |
| 16 | + }) |
| 17 | +} |
| 18 | + |
| 19 | +func (s *Server) getConfigKey(c *gin.Context) { |
| 20 | + key := normalizeConfigKey(c.Param("key")) |
| 21 | + entry, err := config.Get(s.config, key) |
| 22 | + if err != nil { |
| 23 | + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) |
| 24 | + return |
| 25 | + } |
| 26 | + c.JSON(http.StatusOK, gin.H{ |
| 27 | + "entry": entry, |
| 28 | + "runtime": s.runtimeConfigKeys()[key], |
| 29 | + }) |
| 30 | +} |
| 31 | + |
| 32 | +func (s *Server) updateConfigKey(c *gin.Context) { |
| 33 | + key := normalizeConfigKey(c.Param("key")) |
| 34 | + |
| 35 | + var req struct { |
| 36 | + Value interface{} `json:"value"` |
| 37 | + } |
| 38 | + if err := c.ShouldBindJSON(&req); err != nil { |
| 39 | + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + if err := config.Set(s.config, key, req.Value); err != nil { |
| 44 | + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + if s.configPath != "" { |
| 49 | + if err := config.Save(s.config, s.configPath); err != nil { |
| 50 | + c.JSON(http.StatusInternalServerError, gin.H{"error": "value updated in memory but not persisted: " + err.Error()}) |
| 51 | + return |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + applied := false |
| 56 | + if apply, ok := s.runtimeAppliers()[key]; ok { |
| 57 | + apply(s) |
| 58 | + applied = true |
| 59 | + } |
| 60 | + |
| 61 | + entry, _ := config.Get(s.config, key) |
| 62 | + c.JSON(http.StatusOK, gin.H{ |
| 63 | + "entry": entry, |
| 64 | + "applied": applied, |
| 65 | + }) |
| 66 | +} |
| 67 | + |
| 68 | +func (s *Server) runtimeAppliers() map[string]func(*Server) { |
| 69 | + return map[string]func(*Server){ |
| 70 | + "cleanup.timeout": func(srv *Server) { |
| 71 | + srv.manager.SetCleanupTimeout(srv.config.Cleanup.Timeout) |
| 72 | + }, |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func (s *Server) runtimeConfigKeys() map[string]bool { |
| 77 | + keys := make(map[string]bool) |
| 78 | + for k := range s.runtimeAppliers() { |
| 79 | + keys[k] = true |
| 80 | + } |
| 81 | + return keys |
| 82 | +} |
| 83 | + |
| 84 | +func normalizeConfigKey(raw string) string { |
| 85 | + return strings.Trim(raw, "/") |
| 86 | +} |
0 commit comments