emissary/internal/server/api/update_spec.go

87 lines
1.8 KiB
Go

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 updateSpecRequest struct {
spec.RawSpec
}
func (m *Mount) updateSpec(w http.ResponseWriter, r *http.Request) {
agentID, ok := getAgentID(w, r)
if !ok {
return
}
ctx := r.Context()
updateSpecReq := &updateSpecRequest{}
if ok := api.Bind(w, r, updateSpecReq); !ok {
return
}
if err := spec.Validate(ctx, updateSpecReq); err != nil {
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),
string(updateSpecReq.SpecName()),
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,
})
}