Files
aeternalis/server/internal/transport/catalog.go
T

94 lines
2.5 KiB
Go

package transport
import (
"aeternalis/server/internal/store"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
func (h *HTTP) catalogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control/catalog", func(w http.ResponseWriter, r *http.Request) {
if _, ok := h.admin(w, r); !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
catalog, err := h.auth.db.Catalog(ctx)
if err != nil {
fail(w, 503, "catalog unavailable")
return
}
changes, err := h.auth.db.CatalogChanges(ctx)
if err != nil {
fail(w, 503, "catalog audit unavailable")
return
}
respond(w, 200, map[string]any{"catalog": catalog, "changes": changes})
})
for _, path := range []string{"/api/control/catalog", "/api/control/catalog/preview"} {
mux.HandleFunc("POST "+path, func(w http.ResponseWriter, r *http.Request) {
actor, ok := h.admin(w, r)
if !ok {
return
}
var change store.CatalogChange
r.Body = http.MaxBytesReader(w, r.Body, 32768)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&change); err != nil {
fail(w, 400, "invalid catalog change")
return
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
fail(w, 400, "invalid catalog change")
return
}
if change.HasDefinitionID() {
fail(w, 400, "Content IDs are assigned by the server. Refresh the editor and omit the definition ID.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
var result any
var err error
if r.URL.Path == "/api/control/catalog/preview" {
result, err = h.auth.db.PreviewCatalog(ctx, change)
} else {
result, err = h.auth.db.PublishCatalog(ctx, actor, change)
}
switch {
case errors.Is(err, store.ErrCatalogConflict), errors.Is(err, store.ErrCatalogRequest):
fail(w, 409, err.Error())
case errors.Is(err, store.ErrCatalogInvalid):
fail(w, 400, err.Error())
case err != nil:
fail(w, 503, "catalog publication unavailable")
default:
respond(w, 200, result)
}
})
}
}
// Caller holds s.mu. Checkpoint a catalog before it can reach a snapshot.
func (s *Service) refreshCatalog(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
catalog, err := s.lease.DB.CatalogAfter(ctx, s.world.CatalogVersion)
if err != nil {
return err
}
if catalog == nil {
return nil
}
if err = s.world.ApplyCatalog(*catalog); err != nil {
return err
}
return s.persist(ctx, "")
}