Skip to content
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

Await all promises #121

Merged
merged 1 commit into from
Sep 18, 2024
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
19 changes: 18 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,25 @@ module.exports = {
},
'import/external-module-folders': ['node_modules'],
},
parser: '@typescript-eslint/parser',
plugins: ['prettier', '@typescript-eslint', '@atlaskit/design-system'],
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: ['./tsconfig.json', './ui/tsconfig.json'],
},
rules: {
'@typescript-eslint/no-misused-promises': [
'error',
{
checksVoidReturn: false,
},
],
'@typescript-eslint/no-floating-promises': 'error',
},
},
],
rules: {
'max-len': [
'warn',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ jest.mock('../../../client/gitlab');
jest.mock('../../../services/insert-metric-values');
jest.mock('../../../utils/has-deployment-after-28days');

jest.spyOn(global.console, 'error').mockImplementation(() => ({}));

const mockedGetEnvironments = mocked(getEnvironments);
const mockedGetDeployment = mocked(getDeployment);
const mockedSendEventsToCompass = mocked(sendEventToCompass);
Expand All @@ -40,6 +42,7 @@ const MOCK_DEPLOYMENT_EVENT = generateDeploymentEvent();
const MOCK_ENVIRONMENTS_EVENT = generateEnvironmentEvent();
const PROJECT_ID = 123;
const MOCK_DATE = Date.parse('2022-01-29T01:15:42.960Z');
const MOCK_ERROR = new Error('Unexpected Error');

const generateMockDeploymentInput = (
environment = CompassDeploymentEventEnvironmentCategory.Production,
Expand Down Expand Up @@ -108,11 +111,26 @@ describe('GitLab deployment event', () => {

mockedGetEnvironments.mockResolvedValue([MOCK_PRODUCTION_ENVIRONMENT_EVENT]);

await expect(handleDeploymentEvent(MOCK_PRD_DEPLOYMENT_EVENT, TEST_TOKEN, MOCK_CLOUD_ID)).rejects.toThrow(
'Environment with name "prd" not found',
await handleDeploymentEvent(MOCK_PRD_DEPLOYMENT_EVENT, TEST_TOKEN, MOCK_CLOUD_ID);

expect(console.error).toHaveBeenCalledWith(
'Error while sending deployment event to Compass',
new Error('Environment with name "prd" not found'),
);
});

it('failed sending deployment event', async () => {
const MOCK_DEPLOYMENT_EVENT_INPUT = generateMockDeploymentInput();

mockedGetEnvironments.mockResolvedValue([MOCK_ENVIRONMENTS_EVENT]);
mockedGetDeployment.mockResolvedValue(MOCK_DEPLOYMENT_EVENT_INPUT);

mockedSendEventsToCompass.mockRejectedValue(MOCK_ERROR);

await handleDeploymentEvent(MOCK_DEPLOYMENT_EVENT, TEST_TOKEN, MOCK_CLOUD_ID);
expect(console.error).toHaveBeenCalledWith('Error while sending deployment event to Compass', MOCK_ERROR);
});

describe('when isSendStagingEventsEnabled', () => {
beforeEach(() => {
jest.spyOn(featureFlagService, 'isSendStagingEventsEnabled').mockReturnValue(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@ export const handleDeploymentEvent = async (
environment,
project: { id: projectId },
} = event;
const environments = await getProjectEnvironments(projectId, groupToken);
try {
const environments = await getProjectEnvironments(projectId, groupToken);

const environmentTier = await getEnvironmentTier(environments, environment);
const environmentTier = await getEnvironmentTier(environments, environment);

if (
environmentTier === EnvironmentTier.PRODUCTION ||
(isSendStagingEventsEnabled() && environmentTier === EnvironmentTier.STAGING)
) {
const deployment = await getDeployment(event, groupToken, environmentTier, cloudId);
await sendEventToCompass(deployment);
if (
environmentTier === EnvironmentTier.PRODUCTION ||
(isSendStagingEventsEnabled() && environmentTier === EnvironmentTier.STAGING)
) {
const deployment = await getDeployment(event, groupToken, environmentTier, cloudId);
await sendEventToCompass(deployment);
}
} catch (e) {
console.error('Error while sending deployment event to Compass', e);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ jest.mock('../../../services/mergeRequest', () => ({
}));
jest.mock('../../../services/insert-metric-values');

jest.spyOn(global.console, 'error').mockImplementation(() => ({}));

const mockedGetTrackingBranchName = mocked(getTrackingBranchName);
const mockedGetLastMergedMergeRequests = mocked(getLastMergedMergeRequests);
const mockedGetOpenMergeRequests = mocked(getOpenMergeRequests);
Expand All @@ -34,6 +36,7 @@ const MOCK_METRIC_INPUT = generateMetricInput([
generateMetric(BuiltinMetricDefinitions.PULL_REQUEST_CYCLE_TIME_AVG_LAST_10),
generateMetric(BuiltinMetricDefinitions.OPEN_PULL_REQUESTS, 2),
]);
const MOCK_ERROR = new Error('Unexpected Error');

describe('Gitlab merge request', () => {
it('handles merge request event', async () => {
Expand All @@ -45,4 +48,16 @@ describe('Gitlab merge request', () => {

expect(mockedInsertMetricValues).toHaveBeenCalledWith(MOCK_METRIC_INPUT, MOCK_CLOUD_ID);
});

it('failed inserting merge request event', async () => {
mockedGetTrackingBranchName.mockResolvedValue(MOCK_MERGE_REQUEST_EVENT.project.default_branch);
mockedGetLastMergedMergeRequests.mockResolvedValue(mergeRequests);
mockedGetOpenMergeRequests.mockResolvedValue(mergeRequests);

mockedInsertMetricValues.mockRejectedValue(MOCK_ERROR);

await handleMergeRequestEvent(MOCK_MERGE_REQUEST_EVENT, TEST_TOKEN, MOCK_CLOUD_ID);

expect(console.error).toHaveBeenCalledWith('Error while inserting merge requests metric values', MOCK_ERROR);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,33 @@ export const handleMergeRequestEvent = async (
project: { id, default_branch: defaultBranch },
object_attributes: { target_branch: targetBranch },
} = event;
const trackingBranch = await getTrackingBranchName(groupToken, id, defaultBranch);
try {
const trackingBranch = await getTrackingBranchName(groupToken, id, defaultBranch);

if (trackingBranch === targetBranch) {
const [cycleTime, openMergeRequestsCount] = await Promise.all([
getMRCycleTime(groupToken, id, trackingBranch),
getOpenMergeRequestsCount(groupToken, id, trackingBranch),
]);
if (trackingBranch === targetBranch) {
const [cycleTime, openMergeRequestsCount] = await Promise.all([
getMRCycleTime(groupToken, id, trackingBranch),
getOpenMergeRequestsCount(groupToken, id, trackingBranch),
]);

const metricInput = {
projectID: id.toString(),
metrics: [
{
metricAri: BuiltinMetricDefinitions.PULL_REQUEST_CYCLE_TIME_AVG_LAST_10,
value: cycleTime,
timestamp: new Date().toISOString(),
},
{
metricAri: BuiltinMetricDefinitions.OPEN_PULL_REQUESTS,
value: openMergeRequestsCount,
timestamp: new Date().toISOString(),
},
],
};
await insertMetricValues(metricInput, cloudId);
const metricInput = {
projectID: id.toString(),
metrics: [
{
metricAri: BuiltinMetricDefinitions.PULL_REQUEST_CYCLE_TIME_AVG_LAST_10,
value: cycleTime,
timestamp: new Date().toISOString(),
},
{
metricAri: BuiltinMetricDefinitions.OPEN_PULL_REQUESTS,
value: openMergeRequestsCount,
timestamp: new Date().toISOString(),
},
],
};
await insertMetricValues(metricInput, cloudId);
}
} catch (e) {
console.error('Error while inserting merge requests metric values', e);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ jest.mock('../../../client/gitlab');
jest.mock('../../../services/compute-event-and-metrics');
jest.mock('../../../services/insert-metric-values');

jest.spyOn(global.console, 'error').mockImplementation(() => ({}));

const MOCK_ERROR = new Error('Unexpected Error');

describe('Gitlab events', () => {
const event = generatePipelineEvent();

Expand Down Expand Up @@ -73,4 +77,14 @@ describe('Gitlab events', () => {
);
expect(insertMetricValuesMock).not.toBeCalled();
});

it('failed sending pipeline events', async () => {
getTrackingBranchNameMock.mockResolvedValue(event.project.default_branch);

sendEventToCompassMock.mockRejectedValue(MOCK_ERROR);

await handlePipelineEvent(event, TEST_TOKEN, MOCK_CLOUD_ID);

expect(console.error).toHaveBeenCalledWith('Error while sending pipeline event to Compass', MOCK_ERROR);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@ export const handlePipelineEvent = async (event: PipelineEvent, groupToken: stri
project: { id: projectId, default_branch: defaultBranch },
object_attributes: { ref },
} = event;
try {
const trackingBranch = await getTrackingBranchName(groupToken, projectId, defaultBranch);

const trackingBranch = await getTrackingBranchName(groupToken, projectId, defaultBranch);
if (!isEventForTrackingBranch(event, trackingBranch)) {
console.log({
message: 'Received push event for non-tracking branch. Ignoring event',
});
return;
}

if (!isEventForTrackingBranch(event, trackingBranch)) {
console.log({
message: 'Received push event for non-tracking branch. Ignoring event',
});
return;
await sendEventToCompass(webhookPipelineEventToCompassBuildEvent(event, cloudId));
console.log('Build event sent for pipeline.');
} catch (e) {
console.error('Error while sending pipeline event to Compass', e);
}

await sendEventToCompass(webhookPipelineEventToCompassBuildEvent(event, cloudId));
console.log('Build event sent for pipeline.');
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ jest.mock('../../../services/sync-component-with-file', () => {
});

jest.mock('../../../services/get-tracking-branch');
jest.spyOn(global.console, 'error').mockImplementation(() => ({}));

const MOCK_ERROR = new Error('Unexpected Error');

describe('Gitlab push events', () => {
const event = generatePushEvent();
Expand Down Expand Up @@ -205,4 +208,19 @@ describe('Gitlab push events', () => {

expect(removals).toBeCalledWith(mockUnlinkComponentDataWithoutExternalAliasesToRemove[0]);
});

it('failed handling push event ', async () => {
getNonDefaultBranchNameMock.mockResolvedValue(event.project.default_branch);
findConfigChanges.mockResolvedValue({
componentsToCreate: [],
componentsToUpdate: [],
componentsToUnlink: mockComponentsToUnlinkWithoutExternalAliasesToRemove,
});

removals.mockRejectedValue(MOCK_ERROR);

await handlePushEvent(event, TEST_TOKEN, MOCK_CLOUD_ID);

expect(console.error).toBeCalledWith('Error while handling push event', MOCK_ERROR);
});
});
108 changes: 56 additions & 52 deletions src/entry/webtriggers/gitlab-event-handlers/handle-push-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,64 +7,68 @@ import { unlinkComponentFromFile } from '../../../client/compass';
import { EXTERNAL_SOURCE } from '../../../constants';

export const handlePushEvent = async (event: PushEvent, groupToken: string, cloudId: string): Promise<void> => {
const trackingBranch = await getTrackingBranchName(groupToken, event.project.id, event.project.default_branch);
try {
const trackingBranch = await getTrackingBranchName(groupToken, event.project.id, event.project.default_branch);

if (!isEventForTrackingBranch(event, trackingBranch)) {
console.log('Received push event for non-tracking branch. Ignoring event');
return;
}
if (!isEventForTrackingBranch(event, trackingBranch)) {
console.log('Received push event for non-tracking branch. Ignoring event');
return;
}

console.log('Received push event for tracking branch. Processing event');
console.log('Received push event for tracking branch. Processing event');

const { componentsToCreate, componentsToUpdate, componentsToUnlink } = await findConfigAsCodeFileChanges(
event,
groupToken,
);
const { componentsToCreate, componentsToUpdate, componentsToUnlink } = await findConfigAsCodeFileChanges(
event,
groupToken,
);

if (componentsToCreate.length === 0 && componentsToUpdate.length === 0 && componentsToUnlink.length === 0) {
console.log('No config as code file updates in push event');
return;
}
if (componentsToCreate.length === 0 && componentsToUpdate.length === 0 && componentsToUnlink.length === 0) {
console.log('No config as code file updates in push event');
return;
}

console.log('Performing config as code file updates', {
createdFiles: componentsToCreate.length,
updatedFiles: componentsToUpdate.length,
removedFiles: componentsToUnlink.length,
});
console.log('Performing config as code file updates', {
createdFiles: componentsToCreate.length,
updatedFiles: componentsToUpdate.length,
removedFiles: componentsToUnlink.length,
});

const componentSyncDetails: ComponentSyncDetails = {
token: groupToken,
event,
trackingBranch,
cloudId,
};
const componentSyncDetails: ComponentSyncDetails = {
token: groupToken,
event,
trackingBranch,
cloudId,
};

const creates = componentsToCreate.map((componentPayload) =>
syncComponent(componentPayload, componentSyncDetails, {
configFileAction: ConfigFileActions.CREATE,
newPath: componentPayload.filePath,
deduplicationId: event.project.id.toString(),
}),
);
const updates = componentsToUpdate.map((componentPayload) =>
syncComponent(componentPayload, componentSyncDetails, {
configFileAction: ConfigFileActions.UPDATE,
newPath: componentPayload.filePath,
oldPath: componentPayload.previousFilePath,
deduplicationId: event.project.id.toString(),
}),
);
const creates = componentsToCreate.map((componentPayload) =>
syncComponent(componentPayload, componentSyncDetails, {
configFileAction: ConfigFileActions.CREATE,
newPath: componentPayload.filePath,
deduplicationId: event.project.id.toString(),
}),
);
const updates = componentsToUpdate.map((componentPayload) =>
syncComponent(componentPayload, componentSyncDetails, {
configFileAction: ConfigFileActions.UPDATE,
newPath: componentPayload.filePath,
oldPath: componentPayload.previousFilePath,
deduplicationId: event.project.id.toString(),
}),
);

const removals = componentsToUnlink.map((componentToUnlink) =>
unlinkComponentFromFile({
cloudId,
filePath: componentToUnlink.filePath,
componentId: componentToUnlink.componentYaml.id,
deduplicationId: componentToUnlink.deduplicationId,
additionalExternalAliasesToRemove: componentToUnlink.shouldRemoveExternalAlias
? [{ externalId: event.project.id.toString(), externalSource: EXTERNAL_SOURCE }]
: [],
}),
);
await Promise.all([...creates, ...updates, ...removals]);
const removals = componentsToUnlink.map((componentToUnlink) =>
unlinkComponentFromFile({
cloudId,
filePath: componentToUnlink.filePath,
componentId: componentToUnlink.componentYaml.id,
deduplicationId: componentToUnlink.deduplicationId,
additionalExternalAliasesToRemove: componentToUnlink.shouldRemoveExternalAlias
? [{ externalId: event.project.id.toString(), externalSource: EXTERNAL_SOURCE }]
: [],
}),
);
await Promise.all([...creates, ...updates, ...removals]);
} catch (e) {
console.error('Error while handling push event', e);
}
};
Loading
Loading