package web
import (
"encoding/json"
"html/template"
"net/http"
"time"
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
)
// TopologySource is a Source that can map its fabrics.
type TopologySource interface {
Topologies() []adminapi.TopologyView
Topology(id string) (adminapi.TopologyView, bool)
}
type fabricPageData struct {
Nav Nav
OnAdminListener bool
Base string
List []adminapi.TopologyView
Current *adminapi.TopologyView
// Data is the current fabric as JSON, for the drawing to start from
// without a round trip. json.Marshal escapes <, > and &, so a switch
// description cannot close the script it sits in.
Data template.JS
Version string
Now string
}
// FabricsPage shows every physical fabric and, for one, its map.
func FabricsPage(src Source, onAdminListener bool, version string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ts, ok := src.(TopologySource)
if !ok {
http.NotFound(w, r)
return
}
d := fabricPageData{Nav: navFrom(r, "cluster"), OnAdminListener: onAdminListener, Base: "/admin/fabrics",
List: ts.Topologies(), Version: version, Now: time.Now().UTC().Format(time.RFC3339)}
if onAdminListener {
d.Base = "/fabrics"
}
id := r.PathValue("id")
if id == "" && len(d.List) > 0 {
id = d.List[0].ID
}
if id != "" {
t, ok := ts.Topology(id)
if !ok {
http.NotFound(w, r)
return
}
d.Current = &t
b, _ := json.Marshal(t)
d.Data = template.JS(b) //nolint:gosec // json.Marshal escapes <, > and &
}
noStore(w)
render(w, "fabrics", d)
}
}
// FabricTopologyJSON is one fabric's map and live state, for the drawing to
// refresh from.
func FabricTopologyJSON(src Source) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ts, ok := src.(TopologySource)
if !ok {
http.NotFound(w, r)
return
}
t, ok := ts.Topology(r.PathValue("id"))
if !ok {
http.NotFound(w, r)
return
}
noStore(w)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(t)
}
}