package api import ( "encoding/json" "net/http" "sync" "time" "github.com/gin-gonic/gin" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) // publicRegionsTTL is how long an instance serves the platform regions // from memory, so the endpoint costs the database next to nothing however // often a front page asks. const publicRegionsTTL = 30 * time.Second // publicRegion is a platform region as anyone may see it. Organizations' // own regions are never listed. type publicRegion struct { Key string `json:"key"` Name string `json:"name"` // Latitude and longitude are absent for regions without a location. Latitude *float64 `json:"latitude,omitempty"` Longitude *float64 `json:"longitude,omitempty"` // Online is set while at least one checker of the region is connected. Online bool `json:"online"` } type publicRegionsCache struct { mu sync.Mutex body []byte expires time.Time } // listPublicRegions answers without authentication and to any origin, for // a website showing where the platform checks from. func (s *Server) listPublicRegions(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Cache-Control", "public, max-age=60") body, err := s.publicRegionsBody(c) if err != nil { internalError(c, err) return } c.Data(http.StatusOK, "application/json; charset=utf-8", body) } func (s *Server) publicRegionsBody(c *gin.Context) ([]byte, error) { cache := &s.publicRegions cache.mu.Lock() defer cache.mu.Unlock() if cache.body != nil && time.Now().Before(cache.expires) { return cache.body, nil } ctx := c.Request.Context() var rows []store.Region err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error rows, err = q.ListPlatformRegions(ctx) return err }) if err != nil { return nil, err } out := make([]publicRegion, len(rows)) for i, r := range rows { n, err := s.sched.Instances(ctx, r.ID.String()) if err != nil { return nil, err } out[i] = publicRegion{Key: r.Key, Name: r.Name, Latitude: r.Latitude, Longitude: r.Longitude, Online: n > 0} } body, err := json.Marshal(gin.H{"regions": out}) if err != nil { return nil, err } cache.body, cache.expires = body, time.Now().Add(publicRegionsTTL) return body, nil }