emissary/internal/server/api/update_agent_spec.go

94 lines
2.0 KiB
Go
Raw Normal View History

2024-02-27 09:56:15 +01:00
package api
import (
"net/http"
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
"forge.cadoles.com/Cadoles/emissary/internal/spec"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/api"
"gitlab.com/wpetit/goweb/logger"
)
const (
ErrCodeUnexpectedRevision api.ErrorCode = "unexpected-revision"
)
type updateAgentSpecRequest struct {
2024-02-27 09:56:15 +01:00
spec.RawSpec
}
func (m *Mount) updateAgentSpec(w http.ResponseWriter, r *http.Request) {
2024-02-27 09:56:15 +01:00
agentID, ok := getAgentID(w, r)
if !ok {
return
}
ctx := r.Context()
updateSpecReq := &updateAgentSpecRequest{}
2024-02-27 09:56:15 +01:00
if ok := api.Bind(w, r, updateSpecReq); !ok {
return
}
if updateSpecReq.DefinitionVersion == "" {
updateSpecReq.DefinitionVersion = spec.DefaultVersion
}
validator := spec.NewValidator(m.specDefRepo)
if err := validator.Validate(ctx, updateSpecReq); err != nil {
2024-02-27 09:56:15 +01:00
data := struct {
Message string `json:"message"`
}{}
var validationErr *spec.ValidationError
if errors.As(err, &validationErr) {
data.Message = validationErr.Error()
}
err = errors.WithStack(err)
logger.Error(ctx, "could not validate spec", logger.CapturedE(err))
api.ErrorResponse(w, http.StatusBadRequest, api.ErrCodeInvalidRequest, data)
return
}
spec, err := m.agentRepo.UpdateSpec(
ctx,
datastore.AgentID(agentID),
updateSpecReq.SpecDefinitionName(),
updateSpecReq.SpecDefinitionVersion(),
2024-02-27 09:56:15 +01:00
updateSpecReq.SpecRevision(),
updateSpecReq.SpecData(),
)
if err != nil {
if errors.Is(err, datastore.ErrNotFound) {
api.ErrorResponse(w, http.StatusNotFound, ErrCodeNotFound, nil)
return
}
if errors.Is(err, datastore.ErrUnexpectedRevision) {
api.ErrorResponse(w, http.StatusConflict, ErrCodeUnexpectedRevision, nil)
return
}
err = errors.WithStack(err)
logger.Error(ctx, "could not update spec", logger.CapturedE(err))
api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil)
return
}
api.DataResponse(w, http.StatusOK, struct {
Spec *datastore.Spec `json:"spec"`
}{
Spec: spec,
})
}