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(ws): add WorkspaceCreate model to backend #205

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
93 changes: 72 additions & 21 deletions workspaces/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,29 @@ The Kubeflow Workspaces Backend is the _backend for frontend_ (BFF) used by the
> We greatly appreciate any contributions.

# Building and Deploying

TBD

# Development

Run the following command to build the BFF:

```shell
make build
```

After building it, you can run our app with:

```shell
make run
```

If you want to use a different port:

```shell
make run PORT=8000
```

### Endpoints

| URL Pattern | Handler | Action |
Expand All @@ -43,56 +51,99 @@ make run PORT=8000
| DELETE /api/v1/workspacekinds/{name} | TBD | Delete a WorkspaceKind entity |

### Sample local calls
```

Healthcheck:

```shell
# GET /api/v1/healthcheck
curl -i localhost:4000/api/v1/healthcheck
```
```

List all Namespaces:

```shell
# GET /api/v1/namespaces
curl -i localhost:4000/api/v1/namespaces
```
```

List all Workspaces:

```shell
# GET /api/v1/workspaces/
curl -i localhost:4000/api/v1/workspaces
```
```

List all Workspaces in a Namespace:

```shell
# GET /api/v1/workspaces/{namespace}
curl -i localhost:4000/api/v1/workspaces/default
```
```

Create a Workspace:

```shell
# POST /api/v1/workspaces/{namespace}
curl -X POST http://localhost:4000/api/v1/workspaces/default \
-H "Content-Type: application/json" \
-d '{
"data": {
"name": "dora",
"kind": "jupyterlab",
"paused": false,
"defer_updates": false,
"kind": "jupyterlab",
"image_config": "jupyterlab_scipy_190",
"pod_config": "tiny_cpu",
"home_volume": "workspace-home-bella",
"data_volumes": [
{
"pvc_name": "workspace-data-bella",
"mount_path": "/data/my-data",
"read_only": false
"pod_template": {
"pod_metadata": {
"labels": {
"app": "dora"
},
"annotations": {
"app": "dora"
}
},
"volumes": {
"home": "workspace-home-bella",
"data": [
{
"pvc_name": "workspace-data-bella",
"mount_path": "/data/my-data",
"read_only": false
}
]
},
"options": {
"image_config": "jupyterlab_scipy_190",
"pod_config": "tiny_cpu"
}
]
}'
```
}
}
}'
```

Get a Workspace:

```shell
# GET /api/v1/workspaces/{namespace}/{name}
curl -i localhost:4000/api/v1/workspaces/default/dora
```
```

Delete a Workspace:

```shell
# DELETE /api/v1/workspaces/{namespace}/{name}
curl -X DELETE localhost:4000/api/v1/workspaces/workspace-test/dora
```
curl -X DELETE localhost:4000/api/v1/workspaces/default/dora
```

List all WorkspaceKinds:

```shell
# GET /api/v1/workspacekinds
curl -i localhost:4000/api/v1/workspacekinds
```
```

Get a WorkspaceKind:

```shell
# GET /api/v1/workspacekinds/{name}
curl -i localhost:4000/api/v1/workspacekinds/jupyterlab
```
12 changes: 6 additions & 6 deletions workspaces/backend/api/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,20 @@ const (
Version = "1.0.0"
PathPrefix = "/api/v1"

NamespacePathParam = "namespace"
ResourceNamePathParam = "name"

// healthcheck
HealthCheckPath = PathPrefix + "/healthcheck"

// workspaces
AllWorkspacesPath = PathPrefix + "/workspaces"
NamespacePathParam = "namespace"
WorkspaceNamePathParam = "name"
WorkspacesByNamespacePath = AllWorkspacesPath + "/:" + NamespacePathParam
WorkspacesByNamePath = AllWorkspacesPath + "/:" + NamespacePathParam + "/:" + WorkspaceNamePathParam
WorkspacesByNamePath = AllWorkspacesPath + "/:" + NamespacePathParam + "/:" + ResourceNamePathParam

// workspacekinds
AllWorkspaceKindsPath = PathPrefix + "/workspacekinds"
WorkspaceKindNamePathParam = "name"
WorkspaceKindsByNamePath = AllWorkspaceKindsPath + "/:" + WorkspaceNamePathParam
AllWorkspaceKindsPath = PathPrefix + "/workspacekinds"
WorkspaceKindsByNamePath = AllWorkspaceKindsPath + "/:" + ResourceNamePathParam

// namespaces
AllNamespacesPath = PathPrefix + "/namespaces"
Expand Down
2 changes: 1 addition & 1 deletion workspaces/backend/api/healthcheck_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ var _ = Describe("HealthCheck Handler", func() {
defer rs.Body.Close()

By("verifying the HTTP response status code")
Expect(rs.StatusCode).To(Equal(http.StatusOK))
Expect(rs.StatusCode).To(Equal(http.StatusOK), descUnexpectedHTTPStatus, rr.Body.String())

By("reading the HTTP response body")
body, err := io.ReadAll(rs.Body)
Expand Down
46 changes: 46 additions & 0 deletions workspaces/backend/api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,20 @@ package api

import (
"encoding/json"
"fmt"
"mime"
"net/http"
"strings"
)

// Envelope is the body of all requests and responses that contain data.
// NOTE: error responses use the ErrorEnvelope type
type Envelope[D any] struct {
// TODO: make all declarations of Envelope use pointers for D
Data D `json:"data"`
}

// WriteJSON writes a JSON response with the given status code, data, and headers.
func (a *App) WriteJSON(w http.ResponseWriter, status int, data any, headers http.Header) error {

js, err := json.MarshalIndent(data, "", "\t")
Expand All @@ -47,3 +54,42 @@ func (a *App) WriteJSON(w http.ResponseWriter, status int, data any, headers htt

return nil
}

// DecodeJSON decodes the JSON request body into the given value.
func (a *App) DecodeJSON(r *http.Request, v any) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(v); err != nil {
return fmt.Errorf("error decoding JSON: %w", err)
}
return nil
}

// ValidateContentType validates the Content-Type header of the request.
// If this method returns false, the request has been handled and the caller should return immediately.
// If this method returns true, the request has the correct Content-Type.
func (a *App) ValidateContentType(w http.ResponseWriter, r *http.Request, expectedMediaType string) bool {
contentType := r.Header.Get("Content-Type")
if contentType == "" {
a.unsupportedMediaTypeResponse(w, r, fmt.Errorf("Content-Type header is missing"))
return false
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
a.badRequestResponse(w, r, fmt.Errorf("error parsing Content-Type header: %w", err))
return false
}
if mediaType != expectedMediaType {
a.unsupportedMediaTypeResponse(w, r, fmt.Errorf("unsupported media type: %s, expected: %s", mediaType, expectedMediaType))
return false
}

return true
}

// LocationGetWorkspace returns the GET location (HTTP path) for a workspace resource.
func (a *App) LocationGetWorkspace(namespace, name string) string {
path := strings.Replace(WorkspacesByNamePath, ":"+NamespacePathParam, namespace, 1)
path = strings.Replace(path, ":"+ResourceNamePathParam, name, 1)
return path
}
46 changes: 46 additions & 0 deletions workspaces/backend/api/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package api

import "net/http"

// LogError logs an error message with the request details.
func (a *App) LogError(r *http.Request, err error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a style choice, but maybe unify them under a single Log(level, message, error, r *http.Request)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a lot more common to have separate functions, especially because some of them don't have errors.

var (
method = r.Method
uri = r.URL.RequestURI()
)
a.logger.Error(err.Error(), "method", method, "uri", uri)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing that we did on MR is to have tracing or correlation IDs on requests. When we do that, we should remember to log here also the r.context().

@alexcreasy I wonder if this would be something that you can do eventually for us? (include the debug/logs that you did on MR on Notebooks 2.0)

}

// LogWarn logs a warning message with the request details.
func (a *App) LogWarn(r *http.Request, message string) {
var (
method = r.Method
uri = r.URL.RequestURI()
)
a.logger.Warn(message, "method", method, "uri", uri)
}

// LogInfo logs an info message with the request details.
func (a *App) LogInfo(r *http.Request, message string) {
var (
method = r.Method
uri = r.URL.RequestURI()
)
a.logger.Info(message, "method", method, "uri", uri)
}
12 changes: 3 additions & 9 deletions workspaces/backend/api/namespaces_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
models "github.com/kubeflow/notebooks/workspaces/backend/internal/models/namespaces"
)

type NamespacesEnvelope Envelope[[]models.Namespace]
type NamespaceListEnvelope Envelope[[]models.Namespace]

func (a *App) GetNamespacesHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

Expand All @@ -48,12 +48,6 @@ func (a *App) GetNamespacesHandler(w http.ResponseWriter, r *http.Request, _ htt
return
}

namespacesEnvelope := NamespacesEnvelope{
Data: namespaces,
}

err = a.WriteJSON(w, http.StatusOK, namespacesEnvelope, nil)
if err != nil {
a.serverErrorResponse(w, r, err)
}
responseEnvelope := &NamespaceListEnvelope{Data: namespaces}
a.dataResponse(w, r, responseEnvelope)
}
6 changes: 3 additions & 3 deletions workspaces/backend/api/namespaces_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,14 @@ var _ = Describe("Namespaces Handler", func() {
defer rs.Body.Close()

By("verifying the HTTP response status code")
Expect(rs.StatusCode).To(Equal(http.StatusOK))
Expect(rs.StatusCode).To(Equal(http.StatusOK), descUnexpectedHTTPStatus, rr.Body.String())

By("reading the HTTP response body")
body, err := io.ReadAll(rs.Body)
Expect(err).NotTo(HaveOccurred())

By("unmarshalling the response JSON to NamespacesEnvelope")
var response NamespacesEnvelope
By("unmarshalling the response JSON to NamespaceListEnvelope")
var response NamespaceListEnvelope
err = json.Unmarshal(body, &response)
Expect(err).NotTo(HaveOccurred())

Expand Down
Loading
Loading