Skip to content
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
1 change: 1 addition & 0 deletions internal/api/core/memory_workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1142,6 +1142,7 @@ func TestWorkspaceHandlersDelegateToService(t *testing.T) {
ListAllFn: func(context.Context) ([]*session.Info, error) {
info := testutil.NewSessionInfo("sess-a")
info.WorkspaceID = workspace.ID
info.State = session.StateStopped
return []*session.Info{info}, nil
},
}
Expand Down
3 changes: 2 additions & 1 deletion internal/api/core/session_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ func statusForWorkspaceError(err error) int {
return http.StatusGone
case errors.Is(err, workspacepkg.ErrWorkspaceNameTaken),
errors.Is(err, workspacepkg.ErrWorkspacePathTaken),
errors.Is(err, workspacepkg.ErrWorkspaceHasSessions):
errors.Is(err, workspacepkg.ErrWorkspaceHasSessions),
errors.Is(err, workspacepkg.ErrWorkspaceHasActiveSessions):
return http.StatusConflict
case errors.Is(err, workspacepkg.ErrWorkspaceResolverUnavailable):
return http.StatusServiceUnavailable
Expand Down
3 changes: 3 additions & 0 deletions internal/api/core/session_workspace_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ func TestSessionWorkspaceStatusMappings(t *testing.T) {
if got := statusForWorkspaceError(workspacepkg.ErrWorkspaceHasSessions); got != http.StatusConflict {
t.Fatalf("statusForWorkspaceError(has sessions) = %d, want %d", got, http.StatusConflict)
}
if got := statusForWorkspaceError(workspacepkg.ErrWorkspaceHasActiveSessions); got != http.StatusConflict {
t.Fatalf("statusForWorkspaceError(has active sessions) = %d, want %d", got, http.StatusConflict)
}
if got := statusForWorkspaceError(
workspacepkg.ErrWorkspaceResolverUnavailable,
); got != http.StatusServiceUnavailable {
Expand Down
71 changes: 71 additions & 0 deletions internal/api/core/workspaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,85 @@ func (h *BaseHandlers) DeleteWorkspace(c *gin.Context) {
return
}

stoppedSessionIDs, err := h.stoppedWorkspaceSessionIDs(c.Request.Context(), workspace.ID)
if err != nil {
h.respondError(c, StatusForWorkspaceError(err), err)
return
}

if err := h.Workspaces.Unregister(c.Request.Context(), workspace.ID); err != nil {
h.respondError(c, StatusForWorkspaceError(err), err)
return
}

if err := h.deleteStoppedWorkspaceSessions(c.Request.Context(), workspace.ID, stoppedSessionIDs); err != nil {
h.respondError(c, StatusForWorkspaceError(err), err)
return
}

c.Status(http.StatusNoContent)
}

func (h *BaseHandlers) stoppedWorkspaceSessionIDs(ctx context.Context, workspaceID string) ([]string, error) {
if h.Sessions == nil {
return nil, errors.New("api: session manager is required")
}

infos, err := h.Sessions.ListAll(ctx)
if err != nil {
return nil, fmt.Errorf("api: list sessions before deleting workspace %q: %w", workspaceID, err)
}

active := make([]string, 0)
stopped := make([]string, 0)
for _, info := range infos {
if info == nil || strings.TrimSpace(info.WorkspaceID) != workspaceID {
continue
}
sessionID := strings.TrimSpace(info.ID)
if sessionID == "" {
continue
}
if info.State == session.StateActive {
active = append(active, sessionID)
continue
}
stopped = append(stopped, sessionID)
}
if len(active) > 0 {
sort.Strings(active)
return nil, fmt.Errorf(
"api: delete workspace %q: %w: %s",
workspaceID,
workspacepkg.ErrWorkspaceHasActiveSessions,
strings.Join(active, ", "),
)
}

sort.Strings(stopped)
return stopped, nil
}

func (h *BaseHandlers) deleteStoppedWorkspaceSessions(
ctx context.Context,
workspaceID string,
sessionIDs []string,
) error {
if h.Sessions == nil {
return errors.New("api: session manager is required")
}

for _, sessionID := range sessionIDs {
if err := h.Sessions.Delete(ctx, sessionID); err != nil {
if errors.Is(err, session.ErrSessionNotFound) {
continue
}
return fmt.Errorf("api: delete session %q after workspace %q: %w", sessionID, workspaceID, err)
}
}
return nil
}

// ResolveWorkspace resolves or registers a workspace from a path.
func (h *BaseHandlers) ResolveWorkspace(c *gin.Context) {
var req contract.ResolveWorkspaceRequest
Expand Down
81 changes: 79 additions & 2 deletions internal/api/httpapi/handlers_error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,19 @@ func TestWorkspaceHandlersReturnExpectedErrors(t *testing.T) {

func TestDeleteWorkspaceHandlerReturnsConflictWhenWorkspaceHasSessions(t *testing.T) {
homePaths := newTestHomePaths(t)
stopped := newSessionInfo("sess-stopped")
stopped.WorkspaceID = "ws_alpha"
stopped.State = session.StateStopped
var deleted []string
manager := stubSessionManager{
ListAllFn: func(context.Context) ([]*session.Info, error) {
return []*session.Info{stopped}, nil
},
DeleteFn: func(_ context.Context, id string) error {
deleted = append(deleted, id)
return nil
},
}
workspaces := stubWorkspaceService{
GetFn: func(context.Context, string) (workspacepkg.Workspace, error) {
return workspacepkg.Workspace{ID: "ws_alpha", Name: "alpha"}, nil
Expand All @@ -189,15 +202,79 @@ func TestDeleteWorkspaceHandlerReturnsConflictWhenWorkspaceHasSessions(t *testin
}
engine := newTestRouter(
t,
newTestHandlersWithWorkspace(t, stubSessionManager{}, stubObserver{}, workspaces, homePaths),
newTestHandlersWithWorkspace(t, manager, stubObserver{}, workspaces, homePaths),
)

resp := performRequest(t, engine, http.MethodDelete, "/api/workspaces/ws_alpha", nil)
if resp.Code != http.StatusConflict {
t.Fatalf("delete workspace status = %d, want %d", resp.Code, http.StatusConflict)
t.Fatalf(
"delete workspace status = %d, want %d; body=%s",
resp.Code,
http.StatusConflict,
resp.Body.String(),
)
}
var payload contract.ErrorPayload
decodeJSONResponse(t, resp, &payload)
if payload.Error != workspacepkg.ErrWorkspaceHasSessions.Error() {
t.Fatalf("error = %q, want %q", payload.Error, workspacepkg.ErrWorkspaceHasSessions.Error())
}
if len(deleted) != 0 {
t.Fatalf("Delete() calls = %#v, want none before failed unregister", deleted)
}
}

func TestDeleteWorkspaceHandlerReturnsConflictWhenWorkspaceHasActiveSession(t *testing.T) {
t.Parallel()

t.Run("Should return conflict before unregistering active workspace sessions", func(t *testing.T) {
t.Parallel()

homePaths := newTestHomePaths(t)
active := newSessionInfo("sess-active")
active.WorkspaceID = "ws_alpha"
active.State = session.StateActive
manager := stubSessionManager{
ListAllFn: func(context.Context) ([]*session.Info, error) {
return []*session.Info{active}, nil
},
}
unregisterCalled := false
workspaces := stubWorkspaceService{
GetFn: func(context.Context, string) (workspacepkg.Workspace, error) {
return workspacepkg.Workspace{ID: "ws_alpha", Name: "alpha"}, nil
},
UnregisterFn: func(context.Context, string) error {
unregisterCalled = true
return nil
},
}
engine := newTestRouter(
t,
newTestHandlersWithWorkspace(t, manager, stubObserver{}, workspaces, homePaths),
)

resp := performRequest(t, engine, http.MethodDelete, "/api/workspaces/ws_alpha", nil)
if resp.Code != http.StatusConflict {
t.Fatalf(
"delete workspace status = %d, want %d; body=%s",
resp.Code,
http.StatusConflict,
resp.Body.String(),
)
}
var payload contract.ErrorPayload
decodeJSONResponse(t, resp, &payload)
expectedError := "api: delete workspace \"ws_alpha\": workspace has active sessions: sess-active"
if payload.Error != expectedError {
t.Fatalf("error = %q, want %q", payload.Error, expectedError)
}
if unregisterCalled {
t.Fatal("Unregister() called despite active workspace session")
}
})
}

func TestCreateSessionHandlerMapsWorkspaceErrors(t *testing.T) {
homePaths := newTestHomePaths(t)
manager := stubSessionManager{
Expand Down
65 changes: 65 additions & 0 deletions internal/api/httpapi/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1303,6 +1303,71 @@ func TestDeleteWorkspaceHandlerReturnsNoContent(t *testing.T) {
if recorder.Code != http.StatusNoContent {
t.Fatalf("status = %d, want %d; body=%s", recorder.Code, http.StatusNoContent, recorder.Body.String())
}
if recorder.Body.Len() != 0 {
t.Fatalf("body = %q, want empty", recorder.Body.String())
}
}

func TestDeleteWorkspaceHandlerRemovesStoppedWorkspaceSessions(t *testing.T) {
t.Parallel()

t.Run("Should delete stopped workspace sessions after unregister", func(t *testing.T) {
t.Parallel()

homePaths := newTestHomePaths(t)
var calls []string
manager := stubSessionManager{
ListAllFn: func(context.Context) ([]*session.Info, error) {
matchingA := newSessionInfo("sess-a")
matchingA.WorkspaceID = "ws_alpha"
matchingA.State = session.StateStopped
matchingB := newSessionInfo("sess-b")
matchingB.WorkspaceID = "ws_alpha"
matchingB.State = session.StateStopped
otherWorkspace := newSessionInfo("sess-other")
otherWorkspace.WorkspaceID = "ws_beta"
otherWorkspace.State = session.StateStopped
return []*session.Info{matchingB, otherWorkspace, matchingA}, nil
},
DeleteFn: func(_ context.Context, id string) error {
calls = append(calls, "delete:"+id)
return nil
},
}
workspaces := stubWorkspaceService{
GetFn: func(context.Context, string) (workspacepkg.Workspace, error) {
return workspacepkg.Workspace{ID: "ws_alpha", Name: "alpha"}, nil
},
UnregisterFn: func(_ context.Context, id string) error {
if id != "ws_alpha" {
t.Fatalf("Unregister() id = %q, want ws_alpha", id)
}
calls = append(calls, "unregister:"+id)
return nil
},
}
engine := newTestRouter(
t,
newTestHandlersWithWorkspace(t, manager, stubObserver{}, workspaces, homePaths),
)

recorder := performRequest(t, engine, http.MethodDelete, "/api/workspaces/ws_alpha", nil)
if recorder.Code != http.StatusNoContent {
t.Fatalf(
"status = %d, want %d; body=%s",
recorder.Code,
http.StatusNoContent,
recorder.Body.String(),
)
}
if recorder.Body.Len() != 0 {
t.Fatalf("body = %q, want empty", recorder.Body.String())
}
expectedCalls := []string{"unregister:ws_alpha", "delete:sess-a", "delete:sess-b"}
if !slices.Equal(calls, expectedCalls) {
t.Fatalf("calls = %#v, want %#v", calls, expectedCalls)
}
})
}

func TestResolveWorkspaceHandlerReturnsWorkspace(t *testing.T) {
Expand Down
Loading
Loading