Skip to content
Open
Show file tree
Hide file tree
Changes from 12 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
7 changes: 7 additions & 0 deletions .changeset/calm-zebras-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@openchoreo/backstage-plugin-openchoreo-ci': patch
'@openchoreo/backstage-plugin-openchoreo-ci-backend': patch
'@openchoreo/backstage-plugin-openchoreo-workflows': patch
---

Fix workflow run deletion to properly validate ownership and handle empty 204 responses.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@ site
e2e-test-report/


.backstage-db/
.backstage-db/
21 changes: 21 additions & 0 deletions plugins/openchoreo-ci-backend/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,27 @@ export async function createRouter({
);
});

router.delete('/workflow-run', requireAuth, async (req, res) => {
const { componentName, projectName, namespaceName, runName } = req.query;

if (!componentName || !projectName || !namespaceName || !runName) {
throw new InputError(
'componentName, projectName, namespaceName and runName are required query parameters',
);
}

const userToken = getUserTokenFromRequest(req);

await workflowService.deleteWorkflowRun(
namespaceName as string,
projectName as string,
componentName as string,
runName as string,
userToken,
);
res.status(204).end();
});

router.get('/workflow-run', async (req, res) => {
const { componentName, projectName, namespaceName, runName } = req.query;

Expand Down
46 changes: 46 additions & 0 deletions plugins/openchoreo-ci-backend/src/services/WorkflowService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,52 @@ export class WorkflowService {
}
}

async deleteWorkflowRun(
namespaceName: string,
projectName: string,
componentName: string,
runName: string,
token?: string,
): Promise<void> {
this.logger.info(
`Deleting workflow run: ${runName} for component: ${componentName} in project: ${projectName}, namespace: ${namespaceName}`,
);

try {
await this.getWorkflowRun(
namespaceName,
projectName,
componentName,
runName,
token,
);

const client = createOpenChoreoApiClient({
baseUrl: this.baseUrl,
token,
logger: this.logger,
});

const { data, error, response } = await client.DELETE(
'/api/v1/namespaces/{namespaceName}/workflowruns/{runName}',
{
params: {
path: { namespaceName, runName },
},
},
);

assertApiResponse({ data, error, response }, 'delete workflow run');

this.logger.debug(`Successfully deleted workflow run: ${runName}`);
} catch (error) {
this.logger.error(
`Failed to delete workflow run ${runName} in namespace ${namespaceName}: ${error}`,
);
throw error;
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
* Fetch JSONSchema for a specific component workflow
*/
Expand Down
50 changes: 50 additions & 0 deletions plugins/openchoreo-ci/src/api/OpenChoreoCiClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { OpenChoreoCiClient } from './OpenChoreoCiClient';

describe('OpenChoreoCiClient', () => {
let client: OpenChoreoCiClient;
let mockFetchApi: any;
let mockDiscoveryApi: any;

beforeEach(() => {
mockFetchApi = {
fetch: jest.fn(),
};
mockDiscoveryApi = {
getBaseUrl: jest.fn().mockResolvedValue('http://localhost:7007/api/openchoreo'),
};

client = new OpenChoreoCiClient(mockDiscoveryApi, mockFetchApi);
});

describe('apiFetch', () => {
it('should return undefined for 204 No Content', async () => {
mockFetchApi.fetch.mockResolvedValue({
ok: true,
status: 204,
json: jest.fn().mockImplementation(() => Promise.reject(new Error('Should not be called'))),
});

// We access the private apiFetch method indirectly through a public method
// that calls it, like deleteWorkflowRun
const result = await client.deleteWorkflowRun('dev-ns', 'my-project', 'api-service', 'build-2');

expect(result).toBeUndefined();
expect(mockFetchApi.fetch).toHaveBeenCalledWith(
'http://localhost:7007/api/openchoreo/workflow-run?namespaceName=dev-ns&projectName=my-project&componentName=api-service&runName=build-2',
expect.objectContaining({ method: 'DELETE' })
);
});

it('should parse json for 200 OK', async () => {
mockFetchApi.fetch.mockResolvedValue({
ok: true,
status: 200,
json: jest.fn().mockResolvedValue({ name: 'build-2' }),
});

const result = await client.fetchWorkflowSchema('dev-ns', 'my-workflow');

expect(result).toEqual({ name: 'build-2' });
});
});
});
16 changes: 16 additions & 0 deletions plugins/openchoreo-ci/src/api/OpenChoreoCiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ export class OpenChoreoCiClient implements OpenChoreoCiClientApi {
throw new Error(`API request failed (${response.status}): ${errorText}`);
}

if (response.status === 204) {
return undefined as unknown as T;
}

return response.json();
}

Expand Down Expand Up @@ -237,4 +241,16 @@ export class OpenChoreoCiClient implements OpenChoreoCiClientApi {
const entries = (await response.json()) as WorkflowRunEventEntry[];
return entries;
}

async deleteWorkflowRun(
namespaceName: string,
projectName: string,
componentName: string,
runName: string,
): Promise<void> {
return this.apiFetch<void>('/workflow-run', {
method: 'DELETE',
params: { namespaceName, projectName, componentName, runName },
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
}
8 changes: 8 additions & 0 deletions plugins/openchoreo-ci/src/api/OpenChoreoCiClientApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ export interface OpenChoreoCiClientApi {
step: string,
hasLiveObservability: boolean,
): Promise<WorkflowRunEventEntry[]>;

/** Delete a specific workflow run */
deleteWorkflowRun(
namespaceName: string,
projectName: string,
componentName: string,
runName: string,
): Promise<void>;
}

// ============================================
Expand Down
78 changes: 76 additions & 2 deletions plugins/openchoreo-ci/src/components/RunsTab/RunsTab.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { RunsTab } from './RunsTab';
import type { ModelsBuild } from '@openchoreo/backstage-plugin-common';
import { TestApiProvider } from '@backstage/test-utils';
import { openChoreoCiClientApiRef } from '../../api/OpenChoreoCiClientApi';

// ---- Mocks ----

Expand All @@ -24,7 +26,7 @@ jest.mock('../../hooks', () => ({
}));

jest.mock('@backstage/core-components', () => ({
Table: ({ title, data, columns, emptyContent, onRowClick }: any) => (
Table: ({ title, data, columns, emptyContent, onRowClick, actions }: any) => (
<div data-testid="table">
<div data-testid="table-title">{title}</div>
{data.length === 0 ? (
Expand All @@ -45,6 +47,19 @@ jest.mock('@backstage/core-components', () => ({
</span>
) : null,
)}
{actions?.map((action: any, k: number) => (
<button
key={`action-${k}`}
title={action.tooltip}
data-testid={`action-${action.tooltip}-${i}`}
onClick={(e) => {
e.stopPropagation();
action.onClick(e, row);
}}
>
{action.tooltip}
</button>
))}
</div>
))}
</div>
Expand Down Expand Up @@ -78,6 +93,16 @@ const builds: ModelsBuild[] = [
},
];

const mockCiClient = {
deleteWorkflowRun: jest.fn(),
};

Comment thread
coderabbitai[bot] marked this conversation as resolved.
import { alertApiRef } from '@backstage/core-plugin-api';

const mockAlertApi = {
post: jest.fn(),
};

function renderTab(
overrides: Partial<React.ComponentProps<typeof RunsTab>> = {},
) {
Expand All @@ -90,7 +115,16 @@ function renderTab(
};

return {
...render(<RunsTab {...defaultProps} {...overrides} />),
...render(
<TestApiProvider
apis={[
[openChoreoCiClientApiRef, mockCiClient],
[alertApiRef, mockAlertApi],
]}
>
<RunsTab {...defaultProps} {...overrides} />
</TestApiProvider>
),
props: { ...defaultProps, ...overrides },
};
}
Expand Down Expand Up @@ -180,4 +214,44 @@ describe('RunsTab', () => {

expect(onRefresh).toHaveBeenCalled();
});
it('calls deleteWorkflowRun and onRefresh when delete action is confirmed', async () => {
const user = userEvent.setup();
const onRefresh = jest.fn();
mockCiClient.deleteWorkflowRun.mockResolvedValue(undefined);

renderTab({ onRefresh });

// Open dialog
await user.click(screen.getByTestId('action-Delete Run-0'));

expect(screen.getByText('Are you sure you want to delete workflow run "build-2"?')).toBeInTheDocument();

// Click confirm in the dialog
await user.click(screen.getByRole('button', { name: 'Delete' }));

expect(mockCiClient.deleteWorkflowRun).toHaveBeenCalledWith(
'dev-ns',
'my-project',
'api-service',
'build-2'
);
expect(onRefresh).toHaveBeenCalled();
});

it('shows error alert when delete action fails', async () => {
const user = userEvent.setup();
const onRefresh = jest.fn();
mockCiClient.deleteWorkflowRun.mockRejectedValue(new Error('Network error'));

renderTab({ onRefresh });

await user.click(screen.getByTestId('action-Delete Run-0'));
await user.click(screen.getByRole('button', { name: 'Delete' }));

expect(mockAlertApi.post).toHaveBeenCalledWith({
message: 'Failed to delete run: Error: Network error',
severity: 'error',
});
expect(onRefresh).not.toHaveBeenCalled();
});
});
Loading
Loading