Files
sam e8a84d3e41
Quality / check (push) Canceled after 1m17s
deploy / gate (push) Successful in 4m31s
deploy / archied-image (push) Successful in 2m49s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
refactor(webui): extract the control-plane and logs modules (#1778)
2026-11-03 08:34:51 +11:00

187 lines
6.1 KiB
Go

package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
)
type controlPlaneCommandRequest struct {
Value json.RawMessage `json:"value"`
ExpectedVersion int64 `json:"expected_version"`
}
type controlPlaneResource struct {
Kind string `json:"kind"`
Version int64 `json:"version"`
Value json.RawMessage `json:"value"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
type controlPlaneResourceResponse struct {
Resource controlPlaneResource `json:"resource"`
}
// controlPlaneRevision is one entry of a resource's audit trail. Value is the
// payload a restore sends back through the replace command, so it stays raw
// JSON rather than the base64 a proto bytes field would otherwise render as.
type controlPlaneRevision struct {
Version int64 `json:"version"`
Value json.RawMessage `json:"value"`
Actor string `json:"actor"`
ActorName string `json:"actor_name"`
Source string `json:"source"`
RequestID string `json:"request_id"`
At *time.Time `json:"at,omitempty"`
}
type controlPlaneHistoryResponse struct {
Revisions []controlPlaneRevision `json:"revisions"`
}
// controlPlaneAPI owns the generic /api/control-plane resource routes. A nil
// client answers 503.
type controlPlaneAPI struct {
controlPlane controlpb.ControlPlaneServiceClient
actorNames func(context.Context) func(string) string
}
func newControlPlaneAPI(s *Server) *controlPlaneAPI {
return &controlPlaneAPI{controlPlane: s.ControlPlane, actorNames: s.actorNames}
}
func (a *controlPlaneAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control-plane/catalog", a.handleControlPlaneCatalog)
mux.HandleFunc("GET /api/control-plane/resources/{kind}", a.handleControlPlaneQuery)
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", a.handleControlPlaneHistory)
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", a.handleControlPlaneCommand)
}
func (a *controlPlaneAPI) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := a.controlPlane.Catalog(r.Context(), &controlpb.CatalogRequest{})
if err != nil {
writeControlPlaneError(w, err)
return
}
writeJSON(w, response)
}
func (a *controlPlaneAPI) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := a.controlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")})
if err != nil {
writeControlPlaneError(w, err)
return
}
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
}
func (a *controlPlaneAPI) handleControlPlaneHistory(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := a.controlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")})
if err != nil {
writeControlPlaneError(w, err)
return
}
revisions := make([]controlPlaneRevision, 0, len(response.Revisions))
actorName := a.actorNames(r.Context())
for _, revision := range response.Revisions {
// The value is real, not redacted: the dashboard stages a revision and
// applies it as a replace, so a redacted value would restore the marker.
view := controlPlaneRevision{
Version: revision.Version, Value: revision.ValueJson, Actor: revision.Actor, ActorName: actorName(revision.Actor),
Source: revision.Source, RequestID: revision.RequestId,
}
if revision.At != nil {
at := revision.At.AsTime()
view.At = &at
}
revisions = append(revisions, view)
}
writeJSON(w, controlPlaneHistoryResponse{Revisions: revisions})
}
func (a *controlPlaneAPI) handleControlPlaneCommand(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
var request controlPlaneCommandRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil || len(request.Value) == 0 {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
response, err := a.controlPlane.Command(r.Context(), &controlpb.CommandRequest{
Kind: r.PathValue("kind"), Command: r.PathValue("command"), ValueJson: request.Value,
ExpectedVersion: request.ExpectedVersion, Actor: string(audit.ActorID),
Source: audit.Source, RequestId: audit.RequestID,
})
if err != nil {
writeControlPlaneError(w, err)
return
}
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
}
func controlPlaneResourceView(resource *controlpb.Resource) controlPlaneResource {
if resource == nil {
return controlPlaneResource{}
}
view := controlPlaneResource{Kind: resource.Kind, Version: resource.Version, Value: resource.ValueJson}
if resource.UpdatedAt != nil {
updatedAt := resource.UpdatedAt.AsTime()
view.UpdatedAt = &updatedAt
}
return view
}
func newControlPlaneRequestID() (string, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
return "ui-" + hex.EncodeToString(value[:]), nil
}
func writeControlPlaneError(w http.ResponseWriter, err error) {
code := http.StatusInternalServerError
switch status.Code(err) {
case codes.InvalidArgument:
code = http.StatusBadRequest
case codes.NotFound:
code = http.StatusNotFound
case codes.Aborted:
code = http.StatusConflict
case codes.Unavailable, codes.DeadlineExceeded:
code = http.StatusServiceUnavailable
}
message := status.Convert(err).Message()
if message == "" {
message = http.StatusText(code)
}
http.Error(w, message, code)
}