From f5ab72c8211b6d35eca2b82ac9440144d2d6668e Mon Sep 17 00:00:00 2001 From: Yasith Jayawardana Date: Sat, 21 Nov 2026 15:55:03 -0500 Subject: [PATCH 1/2] Set allocation status --- api/core.openapi.yaml | 45 ++++++++++++++ internal/server/allocation.go | 27 ++++++++ internal/server/server.go | 1 + pkg/service/compute_allocation.go | 30 +++++++++ .../compute_allocation_integration_test.go | 48 ++++++++++++++ .../__tests__/AllocationStatusButton.test.tsx | 49 +++++++++++++++ .../core/allocations/__tests__/api.test.ts | 11 ++++ web/src/features/core/allocations/api.ts | 4 ++ .../components/AllocationDetail.tsx | 26 ++++---- .../components/AllocationStatusButton.tsx | 62 +++++++++++++++++++ web/src/features/core/allocations/queries.ts | 9 +++ web/src/mocks/handlers/allocations.ts | 10 +++ 12 files changed, 311 insertions(+), 11 deletions(-) create mode 100644 pkg/service/compute_allocation_integration_test.go create mode 100644 web/src/features/core/allocations/__tests__/AllocationStatusButton.test.tsx create mode 100644 web/src/features/core/allocations/components/AllocationStatusButton.tsx diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index ca814148e..643b78a1f 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -3649,6 +3649,51 @@ paths: summary: Update a compute allocation -> resource mapping tags: - Compute Allocation Resources + /compute-allocations/{id}/status: + put: + consumes: + - application/json + parameters: + - description: Compute allocation ID + in: path + name: id + required: true + type: string + - description: Status patch + in: body + name: request + required: true + schema: + properties: + status: + $ref: '#/definitions/AllocationStatus' + type: object + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/ComputeAllocation' + "400": + description: Bad Request + schema: + properties: + error: + type: string + type: object + "404": + description: Not Found + schema: + properties: + error: + type: string + type: object + security: + - BearerAuth: [] + summary: Update a compute allocation's status + tags: + - Compute Allocations /compute-allocations/{id}/usages: get: description: Callers without the allocations read privilege must hold a membership diff --git a/internal/server/allocation.go b/internal/server/allocation.go index 83fc9f4f7..6ff92b45f 100644 --- a/internal/server/allocation.go +++ b/internal/server/allocation.go @@ -85,6 +85,33 @@ func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request) w.WriteHeader(http.StatusNoContent) } +// @Summary Update a compute allocation's status +// @Tags Compute Allocations +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param id path string true "Compute allocation ID" +// @Param request body object{status=models.AllocationStatus} true "Status patch" +// @Success 200 {object} models.ComputeAllocation +// @Failure 400 {object} object{error=string} +// @Failure 404 {object} object{error=string} +// @Router /compute-allocations/{id}/status [put] +func (s *Server) updateComputeAllocationStatus(w http.ResponseWriter, r *http.Request) { + var body struct { + Status models.AllocationStatus `json:"status"` + } + if err := common.DecodeJSON(r, &body); err != nil { + common.WriteError(w, http.StatusBadRequest, err) + return + } + updated, err := s.svc.UpdateComputeAllocationStatus(r.Context(), r.PathValue("id"), body.Status) + if err != nil { + common.WriteServiceError(w, err) + return + } + common.WriteJSON(w, http.StatusOK, updated) +} + // @Summary Create a compute allocation diff // @Description Records a discrete change against a compute allocation (e.g. USAGE_UPDATE or ALLOCATION_STATUS_CHANGE). // @Tags Compute Allocation Diffs diff --git a/internal/server/server.go b/internal/server/server.go index 3851a8b4f..e4e274fe4 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -97,6 +97,7 @@ func (s *Server) routes() { s.router.RequirePrivilege("POST /compute-allocations", models.AllocationsWrite, s.createComputeAllocation) s.router.RequireScoped("GET /compute-allocations/{id}", s.canReadAllocation, s.getComputeAllocation) s.router.RequirePrivilege("DELETE /compute-allocations/{id}", models.AllocationsWrite, s.deleteComputeAllocation) + s.router.RequirePrivilege("PUT /compute-allocations/{id}/status", models.AllocationsWrite, s.updateComputeAllocationStatus) s.router.RequirePrivilege("POST /compute-allocation-resources", models.AllocationsWrite, s.createComputeAllocationResource) s.router.RequirePrivilege("GET /compute-allocation-resources", models.AllocationsRead, s.listComputeAllocationResources) diff --git a/pkg/service/compute_allocation.go b/pkg/service/compute_allocation.go index eceeb011f..7112a6eda 100644 --- a/pkg/service/compute_allocation.go +++ b/pkg/service/compute_allocation.go @@ -236,3 +236,33 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error } return nil } + +// UpdateComputeAllocationStatus sets an allocation's status and records a diff; INACTIVE ends its members' access. +func (s *Service) UpdateComputeAllocationStatus(ctx context.Context, id string, status models.AllocationStatus) (alloc *models.ComputeAllocation, err error) { + if status != models.ACTIVE && status != models.INACTIVE { + return nil, fmt.Errorf("%w: status must be ACTIVE or INACTIVE", ErrInvalidInput) + } + err = s.inTx(ctx, func(tx *sql.Tx) (err error) { + if alloc, err = s.allocs.FindByIDTx(ctx, tx, id, store.UpdateLock); err != nil { + return err + } + if alloc == nil { + return ErrNotFound + } + if alloc.Status == status { + return nil + } + alloc.Status = status + if err = s.UpdateComputeAllocationTx(ctx, tx, alloc); err != nil { + return err + } + _, err = s.CreateComputeAllocationDiffTx(ctx, tx, &models.ComputeAllocationDiff{ + ComputeAllocationID: id, + DiffType: "ALLOCATION_STATUS_CHANGE", + Status: status, + Description: "Set by an admin", + }) + return err + }) + return +} diff --git a/pkg/service/compute_allocation_integration_test.go b/pkg/service/compute_allocation_integration_test.go new file mode 100644 index 000000000..7cc5ce203 --- /dev/null +++ b/pkg/service/compute_allocation_integration_test.go @@ -0,0 +1,48 @@ +//go:build integration + +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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 service + +import ( + "errors" + "testing" + + "github.com/google/uuid" + + "github.com/apache/airavata-custos/pkg/models" +) + +// Make sure an admin status change records one diff, and setting the same status records none. +func TestUpdateComputeAllocationStatus_RecordsDiff(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + _, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu")) + for range 2 { + if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.INACTIVE); err != nil { + t.Fatalf("update status: %v", err) + } + } + diffs, err := svc.ListDiffsForAllocation(ctx(), allocID) + if err != nil || len(diffs) != 1 || diffs[0].DiffType != "ALLOCATION_STATUS_CHANGE" || diffs[0].Status != models.INACTIVE { + t.Fatalf("diffs: %+v, %v; want one INACTIVE ALLOCATION_STATUS_CHANGE", diffs, err) + } + if _, err := svc.UpdateComputeAllocationStatus(ctx(), allocID, models.DELETED); !errors.Is(err, ErrInvalidInput) { + t.Fatalf("status DELETED: %v, want ErrInvalidInput", err) + } +} diff --git a/web/src/features/core/allocations/__tests__/AllocationStatusButton.test.tsx b/web/src/features/core/allocations/__tests__/AllocationStatusButton.test.tsx new file mode 100644 index 000000000..91966dd9e --- /dev/null +++ b/web/src/features/core/allocations/__tests__/AllocationStatusButton.test.tsx @@ -0,0 +1,49 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. +import type { ComputeAllocation } from "@/generated/core/zod.gen"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const status = { mutate: vi.fn(), reset: vi.fn(), isPending: false, error: null }; +vi.mock("@/shared/casl/permissions", () => ({ + usePermissions: () => ({ allocationsWrite: true }), + requires: () => "", +})); +vi.mock("../queries", () => ({ useSetAllocationStatus: () => status })); + +import { AllocationStatusButton } from "../components/AllocationStatusButton"; + +const allocation = (s: ComputeAllocation["status"]) => + ({ id: "a-1", name: "Alpha", status: s }) as ComputeAllocation; + +describe("", () => { + beforeEach(() => status.mutate.mockClear()); + + it("deactivates only after the confirm", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Deactivate" })); + expect(status.mutate).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Deactivate allocation" })); + expect(status.mutate).toHaveBeenCalledWith("INACTIVE", expect.anything()); + }); + + it("reactivates at once", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Reactivate" })); + expect(status.mutate).toHaveBeenCalledWith("ACTIVE", expect.anything()); + }); +}); diff --git a/web/src/features/core/allocations/__tests__/api.test.ts b/web/src/features/core/allocations/__tests__/api.test.ts index be97e2036..aede86983 100644 --- a/web/src/features/core/allocations/__tests__/api.test.ts +++ b/web/src/features/core/allocations/__tests__/api.test.ts @@ -31,6 +31,7 @@ import { removeMember, submitChangeRequest, } from "../api"; +import { setAllocationStatus } from "../api"; const fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock); @@ -185,6 +186,16 @@ describe("removeMember", () => { }); }); +describe("setAllocationStatus", () => { + it("PUTs INACTIVE to deactivate the allocation", async () => { + fetchMock.mockResolvedValueOnce(mockResponse(200, {})); + await setAllocationStatus("alloc-001", "INACTIVE"); + const [url, init] = fetchMock.mock.calls[0] ?? []; + expect(String(url)).toMatch(/\/compute-allocations\/alloc-001\/status$/); + expect(init).toMatchObject({ method: "PUT", body: '{"status":"INACTIVE"}' }); + }); +}); + describe("listChangeRequests", () => { it("scopes to allocation when allocation_id present", async () => { fetchMock.mockResolvedValueOnce(mockResponse(200, [changeRequest])); diff --git a/web/src/features/core/allocations/api.ts b/web/src/features/core/allocations/api.ts index 4589ddc5c..2ac42965e 100644 --- a/web/src/features/core/allocations/api.ts +++ b/web/src/features/core/allocations/api.ts @@ -129,6 +129,10 @@ export async function removeMember(id: string): Promise { await apiFetch(`/compute-allocation-memberships/${id}`, { method: "DELETE" }); } +export async function setAllocationStatus(id: string, status: "ACTIVE" | "INACTIVE") { + await apiFetch(`/compute-allocations/${id}/status`, { method: "PUT", body: { status } }); +} + export async function listChangeRequests( params: ChangeRequestListParams = {}, ): Promise { diff --git a/web/src/features/core/allocations/components/AllocationDetail.tsx b/web/src/features/core/allocations/components/AllocationDetail.tsx index 22c90d2e9..40b1e1462 100644 --- a/web/src/features/core/allocations/components/AllocationDetail.tsx +++ b/web/src/features/core/allocations/components/AllocationDetail.tsx @@ -31,6 +31,7 @@ import { AllocationDetailHeader } from "./AllocationDetailHeader"; import { AllocationHistoryTab } from "./AllocationHistoryTab"; import { AllocationMembersTab } from "./AllocationMembersTab"; import { AllocationOverviewTab } from "./AllocationOverviewTab"; +import { AllocationStatusButton } from "./AllocationStatusButton"; import { AllocationUsageTab } from "./AllocationUsageTab"; export type AllocationDetailProps = { @@ -65,17 +66,20 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) {
- - Its members, resources and usage records are deleted with it. This cannot be undone. - +
+ + + Its members, resources and usage records are deleted with it. This cannot be undone. + +
+ { + if (!active) + return status.mutate("ACTIVE", { onError: (err) => toast.error(err.message) }); + status.reset(); + setConfirming(true); + }} + disabled={status.isPending} + > + {active ? "Deactivate" : "Reactivate"} + + status.mutate("INACTIVE", { onSuccess: () => setConfirming(false) })} + > + Its members lose access until it is reactivated. + + + ); +} diff --git a/web/src/features/core/allocations/queries.ts b/web/src/features/core/allocations/queries.ts index 6745aff99..d9193891c 100644 --- a/web/src/features/core/allocations/queries.ts +++ b/web/src/features/core/allocations/queries.ts @@ -48,6 +48,7 @@ import { setAllocationResources, submitChangeRequest, } from "./api"; +import { setAllocationStatus } from "./api"; import type { AllocationMembership, CreateAllocationPayload, @@ -135,6 +136,14 @@ export function useDeleteAllocation() { }); } +export function useSetAllocationStatus(allocationId: string) { + const client = useQueryClient(); + return useMutation({ + mutationFn: (status: "ACTIVE" | "INACTIVE") => setAllocationStatus(allocationId, status), + onSuccess: () => client.invalidateQueries({ queryKey: allocationKeys.all }), + }); +} + export function useSetAllocationResources(allocationId: string) { const client = useQueryClient(); return useMutation({ diff --git a/web/src/mocks/handlers/allocations.ts b/web/src/mocks/handlers/allocations.ts index 43e9c1440..f824b3401 100644 --- a/web/src/mocks/handlers/allocations.ts +++ b/web/src/mocks/handlers/allocations.ts @@ -132,6 +132,16 @@ export const allocationsHandlers = [ return HttpResponse.json(found); }), + http.put<{ id: string }, Pick>( + "*/api/v1/compute-allocations/:id/status", + async ({ params, request }) => { + const found = allocations.find((a) => a.id === String(params.id)); + if (!found) return HttpResponse.json({ error: "allocation not found" }, { status: 404 }); + found.status = (await request.json()).status; + return HttpResponse.json(found); + }, + ), + http.get<{ id: string }>("*/api/v1/compute-allocations/:id/resources", ({ params }) => { const id = String(params.id); return HttpResponse.json(resourcesByAlloc[id] ?? []); From 34d468670e96af398bd359866def9f43a67dc44f Mon Sep 17 00:00:00 2001 From: Yasith Jayawardana Date: Sat, 21 Nov 2026 17:03:21 -0500 Subject: [PATCH 2/2] Guard deletes of active allocations --- api/core.openapi.yaml | 7 +++++++ docs/storage.md | 2 +- internal/server/allocation.go | 1 + pkg/service/compute_allocation.go | 17 ++++++++++------- .../compute_allocation_integration_test.go | 9 +++++++++ pkg/service/storage_integration_test.go | 3 ++- .../allocations/components/AllocationDetail.tsx | 4 ++-- 7 files changed, 32 insertions(+), 11 deletions(-) diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index 643b78a1f..f2aac973c 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -3292,6 +3292,13 @@ paths: error: type: string type: object + "409": + description: Conflict + schema: + properties: + error: + type: string + type: object security: - BearerAuth: [] summary: Delete a compute allocation diff --git a/docs/storage.md b/docs/storage.md index 0a59a0f4d..28e7fde77 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -59,7 +59,7 @@ Core makes or changes storages and publishes `storage::create` for each, a paren |---|---| | An allocation or membership is set `INACTIVE` | Retires the storages it gave | | An account is deleted | Retires its `{user}` and member storages | -| An allocation is deleted | Retires its `{allocation}` and member storages | +| An `INACTIVE` allocation is deleted | Its retired storages stay `pending_deletion` | | A user is deleted, or a connector stops holding them | Retires their `{name}` storages | Making storages also retires those of the same holders the targets no longer give, so a sweep retires every storage diff --git a/internal/server/allocation.go b/internal/server/allocation.go index 6ff92b45f..4c6647281 100644 --- a/internal/server/allocation.go +++ b/internal/server/allocation.go @@ -76,6 +76,7 @@ func (s *Server) getComputeAllocation(w http.ResponseWriter, r *http.Request) { // @Param id path string true "Compute allocation ID" // @Success 204 "No Content" // @Failure 404 {object} object{error=string} +// @Failure 409 {object} object{error=string} // @Router /compute-allocations/{id} [delete] func (s *Server) deleteComputeAllocation(w http.ResponseWriter, r *http.Request) { if err := s.svc.DeleteComputeAllocation(r.Context(), r.PathValue("id")); err != nil { diff --git a/pkg/service/compute_allocation.go b/pkg/service/compute_allocation.go index 7112a6eda..ac3d9e266 100644 --- a/pkg/service/compute_allocation.go +++ b/pkg/service/compute_allocation.go @@ -216,14 +216,17 @@ func (s *Service) DeleteComputeAllocation(ctx context.Context, id string) error if id == "" { return fmt.Errorf("%w: compute allocation id is required", ErrInvalidInput) } - alloc, err := s.allocs.FindByID(ctx, id) - if err != nil { - return fmt.Errorf("lookup compute allocation: %w", err) - } - if alloc == nil { - return ErrNotFound - } if err := s.inTx(ctx, func(tx *sql.Tx) error { + alloc, err := s.allocs.FindByIDTx(ctx, tx, id, store.UpdateLock) + if err != nil { + return fmt.Errorf("lookup compute allocation: %w", err) + } + if alloc == nil { + return ErrNotFound + } + if alloc.Status == models.ACTIVE { + return fmt.Errorf("%w: compute allocation %q is active, set it INACTIVE first", ErrInUse, id) + } if err := s.allocs.Delete(ctx, tx, id); err != nil { return err } diff --git a/pkg/service/compute_allocation_integration_test.go b/pkg/service/compute_allocation_integration_test.go index 7cc5ce203..d88e64a44 100644 --- a/pkg/service/compute_allocation_integration_test.go +++ b/pkg/service/compute_allocation_integration_test.go @@ -46,3 +46,12 @@ func TestUpdateComputeAllocationStatus_RecordsDiff(t *testing.T) { t.Fatalf("status DELETED: %v, want ErrInvalidInput", err) } } + +func TestDeleteComputeAllocation_RefusedWhileActive(t *testing.T) { + database := setupTestDB(t) + svc := newTestService(database) + _, allocID := newClusterAllocation(t, svc, seedUser(t, database, uuid.NewString()+"@example.edu")) + if err := svc.DeleteComputeAllocation(ctx(), allocID); !errors.Is(err, ErrInUse) { + t.Fatalf("delete active allocation: %v, want ErrInUse", err) + } +} diff --git a/pkg/service/storage_integration_test.go b/pkg/service/storage_integration_test.go index 810fb6bba..c1300a24f 100644 --- a/pkg/service/storage_integration_test.go +++ b/pkg/service/storage_integration_test.go @@ -164,7 +164,8 @@ func TestStorageLifecycle(t *testing.T) { if err := svc.UpdateStorage(ctx(), byPath()[siblingPath].ID, 1, &until, "", "admin"); !errors.Is(err, ErrNotFound) { t.Errorf("quota on a storage without one of its own: got %v, want ErrNotFound", err) } - err = errors.Join(svc.DeleteComputeClusterUser(ctx(), cu.ID), svc.DeleteComputeAllocation(ctx(), sibling.ID)) + _, err = svc.UpdateComputeAllocationStatus(ctx(), sibling.ID, models.INACTIVE) + err = errors.Join(err, svc.DeleteComputeClusterUser(ctx(), cu.ID), svc.DeleteComputeAllocation(ctx(), sibling.ID)) if got := byPath(); err != nil || got["/home/jdoe"].Status != "pending_deletion" || got[siblingPath].Status != "pending_deletion" || got["/home/jdoe"].ComputeClusterUserID != nil || got[siblingPath].AllocationID != nil { t.Fatalf("deleting the account and an allocation: err=%v got=%+v, want theirs retired and unlinked", err, got) diff --git a/web/src/features/core/allocations/components/AllocationDetail.tsx b/web/src/features/core/allocations/components/AllocationDetail.tsx index 40b1e1462..34920234f 100644 --- a/web/src/features/core/allocations/components/AllocationDetail.tsx +++ b/web/src/features/core/allocations/components/AllocationDetail.tsx @@ -74,8 +74,8 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { name={allocation.name} mutation={remove} redirectTo="/allocations" - allowed={can.allocationsWrite} - reason={requires("allocationsWrite")} + allowed={can.allocationsWrite && allocation.status !== "ACTIVE"} + reason={can.allocationsWrite ? "Deactivate it first" : requires("allocationsWrite")} > Its members, resources and usage records are deleted with it. This cannot be undone.