Skip to content

feat: added include_deleted to getWorkspaceByOwnerAndName #2164

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

Merged
merged 10 commits into from
Jun 8, 2022
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
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"workspaceapp",
"workspaceapps",
"workspacebuilds",
"workspacename",
Copy link
Member

Choose a reason for hiding this comment

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

👍

"wsconncache",
"xerrors",
"xstate",
Expand Down
4 changes: 2 additions & 2 deletions cli/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func create() *cobra.Command {
workspaceName, err = cliui.Prompt(cmd, cliui.PromptOptions{
Text: "Specify a name for your workspace:",
Validate: func(workspaceName string) error {
_, err = client.WorkspaceByOwnerAndName(cmd.Context(), codersdk.Me, workspaceName)
_, err = client.WorkspaceByOwnerAndName(cmd.Context(), codersdk.Me, workspaceName, codersdk.WorkspaceByOwnerAndNameParams{})
if err == nil {
return xerrors.Errorf("A workspace already exists named %q!", workspaceName)
}
Expand All @@ -61,7 +61,7 @@ func create() *cobra.Command {
}
}

_, err = client.WorkspaceByOwnerAndName(cmd.Context(), codersdk.Me, workspaceName)
_, err = client.WorkspaceByOwnerAndName(cmd.Context(), codersdk.Me, workspaceName, codersdk.WorkspaceByOwnerAndNameParams{})
if err == nil {
return xerrors.Errorf("A workspace already exists named %q!", workspaceName)
}
Expand Down
2 changes: 1 addition & 1 deletion cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func namedWorkspace(cmd *cobra.Command, client *codersdk.Client, identifier stri
return codersdk.Workspace{}, xerrors.Errorf("invalid workspace name: %q", identifier)
}

return client.WorkspaceByOwnerAndName(cmd.Context(), owner, name)
return client.WorkspaceByOwnerAndName(cmd.Context(), owner, name, codersdk.WorkspaceByOwnerAndNameParams{})
}

// createConfig consumes the global configuration flag to produce a config root.
Expand Down
22 changes: 22 additions & 0 deletions coderd/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,32 @@ func (api *API) workspaceByOwnerAndName(rw http.ResponseWriter, r *http.Request)
owner := httpmw.UserParam(r)
workspaceName := chi.URLParam(r, "workspacename")

includeDeleted := false
if s := r.URL.Query().Get("include_deleted"); s != "" {
var err error
includeDeleted, err = strconv.ParseBool(s)
if err != nil {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: fmt.Sprintf("Invalid boolean value %q for \"include_deleted\" query param.", s),
Validations: []httpapi.Error{
{Field: "include_deleted", Detail: "Must be a valid boolean"},
},
})
return
}
}

workspace, err := api.Database.GetWorkspaceByOwnerIDAndName(r.Context(), database.GetWorkspaceByOwnerIDAndNameParams{
OwnerID: owner.ID,
Name: workspaceName,
})
if includeDeleted && errors.Is(err, sql.ErrNoRows) {
workspace, err = api.Database.GetWorkspaceByOwnerIDAndName(r.Context(), database.GetWorkspaceByOwnerIDAndNameParams{
OwnerID: owner.ID,
Name: workspaceName,
Deleted: includeDeleted,
Copy link
Member

Choose a reason for hiding this comment

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

I don't think this works as intended. The param here in the SQL matches for deleted = $includeDeleted.

So if you set this to true, the workspace will not show if the workspace is deleted. We will need to update the SQL too, or just always return deleted workspaces by default.

Copy link
Member

Choose a reason for hiding this comment

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

See how it's handled here:

if workspace.Deleted && !showDeleted {
httpapi.Write(rw, http.StatusGone, httpapi.Response{
Message: fmt.Sprintf("Workspace %q was deleted, you can view this workspace by specifying '?deleted=true' and trying again.", workspace.ID.String()),
})
return
}

I think the deleted query param is kinda annoying as you have to know the state of the workspace to query it.

Copy link
Member Author

Choose a reason for hiding this comment

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

@Emyrk Hmm, testing it in the UI seems to work.

  1. if include_deleted is false, then we never enter this code block (because errors.Is(err, sql.ErrNoRows) is false
  2. otherwise we enter this code block and try to query for a deleted workspace

In either case, if we get nothing back, we then go into the httpapi.Forbidden(rw) block below. I agree editing the SQL would also work. I just didn't know what other ramifications that would have.

Let me know if I'm misunderstanding your comment!

})
}
if errors.Is(err, sql.ErrNoRows) {
// Do not leak information if the workspace exists or not
httpapi.Forbidden(rw)
Expand Down
33 changes: 31 additions & 2 deletions coderd/workspaces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ func TestWorkspaceByOwnerAndName(t *testing.T) {
t.Run("NotFound", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_, err := client.WorkspaceByOwnerAndName(context.Background(), codersdk.Me, "something")
_, err := client.WorkspaceByOwnerAndName(context.Background(), codersdk.Me, "something", codersdk.WorkspaceByOwnerAndNameParams{})
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusUnauthorized, apiErr.StatusCode())
Expand All @@ -271,9 +271,38 @@ func TestWorkspaceByOwnerAndName(t *testing.T) {
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
_, err := client.WorkspaceByOwnerAndName(context.Background(), codersdk.Me, workspace.Name)
_, err := client.WorkspaceByOwnerAndName(context.Background(), codersdk.Me, workspace.Name, codersdk.WorkspaceByOwnerAndNameParams{})
require.NoError(t, err)
})
t.Run("deletedGetWorkspaceByOwnerAndName", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerD: true})
user := coderdtest.CreateFirstUser(t, client)
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJob(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, user.OrganizationID, template.ID)
coderdtest.AwaitWorkspaceBuildJob(t, client, workspace.LatestBuild.ID)

// Given:
// We delete the workspace
build, err := client.CreateWorkspaceBuild(context.Background(), workspace.ID, codersdk.CreateWorkspaceBuildRequest{
Transition: codersdk.WorkspaceTransitionDelete,
})
require.NoError(t, err, "delete the workspace")
coderdtest.AwaitWorkspaceBuildJob(t, client, build.ID)

// Then:
// when we call without includes_deleted, we don't expect to get the workspace back
_, err = client.WorkspaceByOwnerAndName(context.Background(), workspace.OwnerName, workspace.Name, codersdk.WorkspaceByOwnerAndNameParams{})
require.ErrorContains(t, err, "403")

// Then:
// When we call with includes_deleted, we should get the workspace back
workspaceNew, err := client.WorkspaceByOwnerAndName(context.Background(), workspace.OwnerName, workspace.Name, codersdk.WorkspaceByOwnerAndNameParams{IncludeDeleted: true})
require.NoError(t, err)
require.Equal(t, workspace.ID, workspaceNew.ID)
})
}

func TestWorkspaceFilter(t *testing.T) {
Expand Down
12 changes: 10 additions & 2 deletions codersdk/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,17 @@ func (c *Client) Workspaces(ctx context.Context, filter WorkspaceFilter) ([]Work
return workspaces, json.NewDecoder(res.Body).Decode(&workspaces)
}

type WorkspaceByOwnerAndNameParams struct {
IncludeDeleted bool `json:"include_deleted,omitempty"`
}

// WorkspaceByOwnerAndName returns a workspace by the owner's UUID and the workspace's name.
func (c *Client) WorkspaceByOwnerAndName(ctx context.Context, owner string, name string) (Workspace, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/users/%s/workspace/%s", owner, name), nil)
func (c *Client) WorkspaceByOwnerAndName(ctx context.Context, owner string, name string, params WorkspaceByOwnerAndNameParams) (Workspace, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/users/%s/workspace/%s", owner, name), nil, func(r *http.Request) {
q := r.URL.Query()
q.Set("include_deleted", fmt.Sprintf("%t", params.IncludeDeleted))
r.URL.RawQuery = q.Encode()
})
if err != nil {
return Workspace{}, err
}
Expand Down
4 changes: 3 additions & 1 deletion site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ export const getWorkspaceByOwnerAndName = async (
username = "me",
workspaceName: string,
): Promise<TypesGen.Workspace> => {
const response = await axios.get<TypesGen.Workspace>(`/api/v2/users/${username}/workspace/${workspaceName}`)
const response = await axios.get<TypesGen.Workspace>(`/api/v2/users/${username}/workspace/${workspaceName}`, {
params: { include_deleted: true },
})
return response.data
}

Expand Down
5 changes: 5 additions & 0 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,11 @@ export interface WorkspaceBuildsRequest extends Pagination {
readonly WorkspaceID: string
}

// From codersdk/workspaces.go:261:6
export interface WorkspaceByOwnerAndNameParams {
readonly include_deleted?: boolean
}

// From codersdk/workspaces.go:219:6
export interface WorkspaceFilter {
readonly organization_id?: string
Expand Down