Skip to content

Commit

Permalink
Merge pull request #7 from axelerant/fix-env-action-timeout
Browse files Browse the repository at this point in the history
fix timeout issue and improve error handling
  • Loading branch information
zeshanziya authored Sep 25, 2024
2 parents 2ba2c1a + 29c92d4 commit 70f8251
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 4 deletions.
7 changes: 7 additions & 0 deletions .changeset/fast-rats-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@axelerant/backstage-plugin-platformsh-backend': patch
'@axelerant/backstage-plugin-platformsh-common': patch
'@axelerant/backstage-plugin-platformsh': patch
---

Use a polling mechanism to check the environment action status to fix timeout issue and improve error handling.
21 changes: 19 additions & 2 deletions plugins/platformsh-backend/src/PlatformshHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ export class PlatformshHelper {
action: EnvironmentMethods,
) {
let successMsg = '';
let activityId = '';
try {
const environment = await this.getEnvironment(
project_id,
Expand All @@ -193,11 +194,12 @@ export class PlatformshHelper {

if (action === 'delete') {
await environment.delete();
successMsg = `Environment ${action}d successfully!`;
} else if (action in actionMap) {
const activity = await actionMap[action]();
await activity.wait();
activityId = activity.id;
successMsg = `Action ${action} for environment ${env_id} has started and will finish soon.`;
}
successMsg = `Environment ${action}d successfully!`;
} catch (error) {
let errorMsg = '';
if (error instanceof Error) {
Expand All @@ -216,6 +218,7 @@ export class PlatformshHelper {
return {
valid: 1,
message: successMsg,
activityId: activityId,
};
}

Expand Down Expand Up @@ -254,4 +257,18 @@ export class PlatformshHelper {
valid: 1,
};
}

async getEnvironmentActivity(
project_id: string,
env_id: string,
activity_id: string,
) {
const client = await this.getClient();
const activity = await client.getEnvironmentActivity(
project_id,
encodeURIComponent(env_id),
activity_id,
);
return activity;
}
}
25 changes: 25 additions & 0 deletions plugins/platformsh-backend/src/service/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,31 @@ export async function createRouter(
},
);

router.post(
'/activity/:id/status',
async (
req: Request<
{ id: string },
{},
{ environmentId: string; projectId: string }
>,
res,
) => {
try {
const activity = await platformshHelper.getEnvironmentActivity(
req.body.projectId,
req.body.environmentId,
req.params.id,
);
console.log(activity, activity.isComplete());
res.json({ result: { completed: activity.isComplete() } });
} catch (error) {
logger.error(`Unable to get activity status: ${error}`);
res.status(500).json({ error: 'Unable to get activity status' });
}
},
);

const middleware = MiddlewareFactory.create({ logger, config });

router.use(middleware.error());
Expand Down
7 changes: 7 additions & 0 deletions plugins/platformsh-common/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type EnvironmentActionResponse = {
actionResult: {
valid: number;
message: string;
activityId: string;
};
};
};
Expand All @@ -54,3 +55,9 @@ export type EnvironmentMethods =
| 'activate'
| 'deactivate'
| 'delete';

export type EnvironmentActivityStatusResponse = {
result: {
completed: boolean;
};
};
44 changes: 43 additions & 1 deletion plugins/platformsh/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from '@backstage/core-plugin-api';
import {
EnvironmentActionResponse,
EnvironmentActivityStatusResponse,
ListProjectsResponse,
PlatformshEnvironment,
PlatformshProject,
Expand All @@ -21,6 +22,11 @@ export interface PlatformshApi {
environmentId: string,
action: string,
): Promise<EnvironmentActionResponse>;
pollForActivityCompletion(
projectId: string,
environmentId: string,
acticityId: string,
): Promise<void>;
}

export const platformshApiRef = createApiRef<PlatformshApi>({
Expand Down Expand Up @@ -52,7 +58,12 @@ export class PlatformshClient implements PlatformshApi {
);

if (!response.ok) {
const errorBody = await response.json();
let errorBody;
try {
errorBody = await response.json();
} catch {
errorBody = {};
}

const errorMessage = errorBody?.error?.message || 'An error occurred';
const errorName = errorBody?.error?.name || 'Error';
Expand Down Expand Up @@ -94,4 +105,35 @@ export class PlatformshClient implements PlatformshApi {
},
);
}

async pollForActivityCompletion(
projectId: string,
environmentId: string,
activityId: string,
): Promise<void> {
return new Promise((resolve, reject) => {
const poll = setInterval(async () => {
try {
const {
result: { completed },
} = await this.fetchApiData<EnvironmentActivityStatusResponse>(
`/activity/${activityId}/status`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ environmentId, projectId }),
},
);

if (completed) {
clearInterval(poll);
resolve();
}
} catch (error) {
clearInterval(poll);
reject(error);
}
}, 5000);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ describe('ProjectDetailsCard', () => {
getProjectInfo: jest.fn(),
getProjectEnvironments: jest.fn(),
doEnvironmentAction: jest.fn(),
pollForActivityCompletion: jest.fn(),
};

const permissionApi: jest.Mocked<typeof permissionApiRef.T> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,19 @@ export const EnvironmentsCard = ({ projectId }: { projectId: string }) => {
if (actionResult.valid) {
alertApi.post({
message: actionResult.message,
severity: 'success',
severity: actionResult.activityId ? 'info' : 'success',
});
if (actionResult.activityId) {
await platformshApi.pollForActivityCompletion(
projectId,
env_id,
actionResult.activityId,
);
alertApi.post({
message: `Environment ${action}d successfully!`,
severity: 'success',
});
}
loadProjectEnvironments();
} else {
alertApi.post({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('ProjectDetailsCard', () => {
getProjectInfo: jest.fn(),
getProjectEnvironments: jest.fn(),
doEnvironmentAction: jest.fn(),
pollForActivityCompletion: jest.fn(),
};

const Wrapper = ({ children }: { children?: React.ReactNode }) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe('EntityTabComponent', () => {
getProjectInfo: jest.fn(),
getProjectEnvironments: jest.fn(),
doEnvironmentAction: jest.fn(),
pollForActivityCompletion: jest.fn(),
};

const Wrapper = ({ children }: { children?: React.ReactNode }) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe('PlatformshPageComponent', () => {
getProjectInfo: jest.fn(),
getProjectEnvironments: jest.fn(),
doEnvironmentAction: jest.fn(),
pollForActivityCompletion: jest.fn(),
};

const Wrapper = ({ children }: { children?: React.ReactNode }) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ describe('ProjectsComponent', () => {
getProjectInfo: jest.fn(),
getProjectEnvironments: jest.fn(),
doEnvironmentAction: jest.fn(),
pollForActivityCompletion: jest.fn(),
};

const Wrapper = ({ children }: { children?: React.ReactNode }) => (
Expand Down

0 comments on commit 70f8251

Please sign in to comment.