Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(daemon): add ErrorResponse to allow external error creation #303

Merged
merged 7 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,11 +416,15 @@ func (e *Error) Error() string {
return e.Message
}

// Error kinds for use as a response or maintenance result
const (
ErrorKindLoginRequired = "login-required"
ErrorKindNoDefaultServices = "no-default-services"
ErrorKindNotFound = "not-found"
ErrorKindPermissionDenied = "permission-denied"
ErrorKindGenericFileError = "generic-file-error"
ErrorKindSystemRestart = "system-restart"
ErrorKindDaemonRestart = "daemon-restart"
ErrorKindNoDefaultServices = "no-default-services"
)

func (rsp *response) err(cli *Client) error {
Expand Down
71 changes: 39 additions & 32 deletions internals/daemon/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ func (r *resp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
if err != nil {
logger.Noticef("Cannot marshal %#v to JSON: %v", *r, err)
bs = nil
status = 500
status = http.StatusInternalServerError
}

hdr := w.Header()
if r.Status == 202 || r.Status == 201 {
if r.Status == http.StatusAccepted || r.Status == http.StatusCreated {
if m, ok := r.Result.(map[string]interface{}); ok {
if location, ok := m["resource"]; ok {
if location, ok := location.(string); ok && location != "" {
Expand All @@ -116,22 +116,21 @@ func (r *resp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {

type errorKind string
flotter marked this conversation as resolved.
Show resolved Hide resolved

// Error kinds for use as a response or maintenance result
const (
errorKindLoginRequired = errorKind("login-required")
errorKindDaemonRestart = errorKind("daemon-restart")
errorKindSystemRestart = errorKind("system-restart")
errorKindNoDefaultServices = errorKind("no-default-services")
errorKindNotFound = errorKind("not-found")
errorKindPermissionDenied = errorKind("permission-denied")
errorKindGenericFileError = errorKind("generic-file-error")
errorKindSystemRestart = errorKind("system-restart")
errorKindDaemonRestart = errorKind("daemon-restart")
)

type errorValue interface{}
flotter marked this conversation as resolved.
Show resolved Hide resolved

type errorResult struct {
Message string `json:"message"` // note no omitempty
Kind errorKind `json:"kind,omitempty"`
Value errorValue `json:"value,omitempty"`
Message string `json:"message"` // note no omitempty
Kind errorKind `json:"kind,omitempty"`
Value interface{} `json:"value,omitempty"`
}

func SyncResponse(result interface{}) Response {
Expand All @@ -145,15 +144,15 @@ func SyncResponse(result interface{}) Response {

return &resp{
Type: ResponseTypeSync,
Status: 200,
Status: http.StatusOK,
Result: result,
}
}

func AsyncResponse(result map[string]interface{}, change string) Response {
return &resp{
Type: ResponseTypeAsync,
Status: 202,
Status: http.StatusAccepted,
Result: result,
Change: change,
}
Expand All @@ -169,22 +168,30 @@ func (f fileResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, string(f))
}

// Responsef builds an error Response that returns the status and formatted message.
flotter marked this conversation as resolved.
Show resolved Hide resolved
//
// If no arguments are provided, formatting is disabled, and the format string
// is used as is and not interpreted in any way.
func ErrorResponse(status int, format string, v ...interface{}) Response {
flotter marked this conversation as resolved.
Show resolved Hide resolved
res := &errorResult{}
if len(v) == 0 {
res.Message = format
} else {
res.Message = fmt.Sprintf(format, v...)
}
flotter marked this conversation as resolved.
Show resolved Hide resolved
if status == http.StatusUnauthorized {
res.Kind = errorKindLoginRequired
}
return &resp{
Type: ResponseTypeError,
Result: res,
Status: status,
}
}

func makeErrorResponder(status int) errorResponder {
return func(format string, v ...interface{}) Response {
res := &errorResult{}
if len(v) == 0 {
res.Message = format
} else {
res.Message = fmt.Sprintf(format, v...)
}
if status == 401 {
res.Kind = errorKindLoginRequired
}
return &resp{
Type: ResponseTypeError,
Result: res,
Status: status,
}
return ErrorResponse(status, format, v...)
}
}

Expand All @@ -194,11 +201,11 @@ type errorResponder func(string, ...interface{}) Response

// Standard error responses.
var (
statusBadRequest = makeErrorResponder(400)
statusUnauthorized = makeErrorResponder(401)
statusForbidden = makeErrorResponder(403)
statusNotFound = makeErrorResponder(404)
statusMethodNotAllowed = makeErrorResponder(405)
statusInternalError = makeErrorResponder(500)
statusGatewayTimeout = makeErrorResponder(504)
statusBadRequest = makeErrorResponder(http.StatusBadRequest)
statusUnauthorized = makeErrorResponder(http.StatusUnauthorized)
statusForbidden = makeErrorResponder(http.StatusForbidden)
statusNotFound = makeErrorResponder(http.StatusNotFound)
statusMethodNotAllowed = makeErrorResponder(http.StatusMethodNotAllowed)
statusInternalError = makeErrorResponder(http.StatusInternalServerError)
statusGatewayTimeout = makeErrorResponder(http.StatusGatewayTimeout)
)
10 changes: 5 additions & 5 deletions internals/daemon/response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (s *responseSuite) TestRespSetsLocationIfAccepted(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 202,
Status: http.StatusAccepted,
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand All @@ -49,7 +49,7 @@ func (s *responseSuite) TestRespSetsLocationIfCreated(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 201,
Status: http.StatusCreated,
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand All @@ -64,7 +64,7 @@ func (s *responseSuite) TestRespDoesNotSetLocationIfOther(c *check.C) {
rec := httptest.NewRecorder()

rsp := &resp{
Status: 418, // I'm a teapot
Status: http.StatusTeapot, // I'm a teapot
Result: map[string]interface{}{
"resource": "foo/bar",
},
Expand Down Expand Up @@ -104,7 +104,7 @@ func (s *responseSuite) TestRespJSONWithNullResult(c *check.C) {
}

func (s *responseSuite) TestErrorResponderPrintfsWithArgs(c *check.C) {
teapot := makeErrorResponder(418)
teapot := makeErrorResponder(http.StatusTeapot)

rec := httptest.NewRecorder()
rsp := teapot("system memory below %d%%.", 1)
Expand All @@ -119,7 +119,7 @@ func (s *responseSuite) TestErrorResponderPrintfsWithArgs(c *check.C) {
}

func (s *responseSuite) TestErrorResponderDoesNotPrintfAlways(c *check.C) {
teapot := makeErrorResponder(418)
teapot := makeErrorResponder(http.StatusTeapot)

rec := httptest.NewRecorder()
rsp := teapot("system memory below 1%.")
Expand Down