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
57 changes: 57 additions & 0 deletions src/server/lib/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
constructEcrRepoPath,
waitUntil,
enableKillSwitch,
isLifecycleLabel,
hasDeployLabel,
hasDisabledLabel,
hasStatusCommentLabel,
Expand Down Expand Up @@ -331,6 +332,62 @@ describe('enableKillSwitch', () => {
});
});

describe('isLifecycleLabel', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('returns true for a deploy label', async () => {
const result = await isLifecycleLabel('lifecycle-deploy!');
expect(result).toBe(true);
});

test('returns true for a custom deploy label', async () => {
const result = await isLifecycleLabel('custom-deploy!');
expect(result).toBe(true);
});

test('returns true for a disabled label', async () => {
const result = await isLifecycleLabel('lifecycle-disabled!');
expect(result).toBe(true);
});

test('returns true for a keep label', async () => {
const result = await isLifecycleLabel('lifecycle-keep!');
expect(result).toBe(true);
});

test('returns true for a status comments label', async () => {
const result = await isLifecycleLabel('lifecycle-status-comments!');
expect(result).toBe(true);
});

test('returns false for a non-lifecycle label', async () => {
const result = await isLifecycleLabel('ready-for-review');
expect(result).toBe(false);
});

test('returns false for an empty string', async () => {
const result = await isLifecycleLabel('');
expect(result).toBe(false);
});

test('returns false for null', async () => {
const result = await isLifecycleLabel(null as any);
expect(result).toBe(false);
});

test('returns false for undefined', async () => {
const result = await isLifecycleLabel(undefined as any);
expect(result).toBe(false);
});

test('is case-insensitive', async () => {
const result = await isLifecycleLabel('Lifecycle-Deploy!');
expect(result).toBe(true);
});
});

describe('hasDeployLabel', () => {
afterEach(() => {
jest.clearAllMocks();
Expand Down
12 changes: 12 additions & 0 deletions src/server/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,18 @@ export const isStaging = () => {
return ENVIRONMENT === 'staging';
};

export const isLifecycleLabel = async (label: string): Promise<boolean> => {
if (!label) return false;
const labelsConfig = await GlobalConfigService.getInstance().getLabels();
const allLifecycleLabels = [
...(labelsConfig.deploy || []),
...(labelsConfig.disabled || []),
...(labelsConfig.keep || []),
...(labelsConfig.statusComments || []),
];
return allLifecycleLabels.includes(label.toLowerCase());
};

export const hasDeployLabel = async (labels: string[]): Promise<boolean> => {
if (!labels || labels.length === 0) return false;
const labelsConfig = await GlobalConfigService.getInstance().getLabels();
Expand Down
207 changes: 207 additions & 0 deletions src/server/services/__tests__/github.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ import { PushEvent } from '@octokit/webhooks-types';

mockRedisClient();

const mockIsLifecycleLabel = jest.fn();
const mockHasDeployLabel = jest.fn();
const mockEnableKillSwitch = jest.fn();
const mockIsStaging = jest.fn().mockReturnValue(false);

jest.mock('server/lib/utils', () => ({
...jest.requireActual('server/lib/utils'),
isLifecycleLabel: (...args) => mockIsLifecycleLabel(...args),
hasDeployLabel: (...args) => mockHasDeployLabel(...args),
enableKillSwitch: (...args) => mockEnableKillSwitch(...args),
isStaging: (...args) => mockIsStaging(...args),
}));

jest.mock('server/lib/logger', () => ({
getLogger: jest.fn(() => ({
error: jest.fn(),
Expand Down Expand Up @@ -313,3 +326,197 @@ describe('Github Service - handlePushWebhook', () => {
});
});
});

describe('Github Service - handleLabelWebhook', () => {
let githubService: Github;
let mockDb: any;
let mockQueueManager: any;

const createMockLabelWebhookBody = ({
action = 'labeled',
changedLabel = 'ready-for-review',
allLabels = [{ name: 'ready-for-review' }],
githubPullRequestId = 1001,
status = 'open',
} = {}) => ({
action,
label: { name: changedLabel },
pull_request: {
id: githubPullRequestId,
labels: allLabels,
state: status,
},
});

const createMockPullRequest = (overrides: any = {}) => ({
id: 1,
deployOnUpdate: false,
githubLogin: 'test-user',
fullName: 'org/repo',
branchName: 'feature-branch',
build: { id: 10, uuid: 'build-uuid' },
repository: { id: 5 },
$fetchGraph: jest.fn().mockResolvedValue(undefined),
$query: jest.fn().mockReturnValue({
patch: jest.fn().mockResolvedValue(undefined),
first: jest.fn().mockResolvedValue(undefined),
}),
...overrides,
});

beforeEach(() => {
jest.clearAllMocks();

mockDb = {
models: {
PullRequest: {
findOne: jest.fn().mockResolvedValue(null),
},
},
services: {
BuildService: {
deleteBuild: jest.fn().mockResolvedValue(undefined),
resolveAndDeployBuildQueue: {
add: jest.fn().mockResolvedValue(undefined),
},
},
BotUser: {
isBotUser: jest.fn().mockResolvedValue(false),
},
},
};

mockQueueManager = {
registerQueue: jest.fn().mockReturnValue({
add: jest.fn(),
process: jest.fn(),
on: jest.fn(),
}),
};

githubService = new Github(mockDb, {}, {}, mockQueueManager);
});

test('should skip processing when changed label is not a lifecycle label', async () => {
mockIsLifecycleLabel.mockResolvedValue(false);

const body = createMockLabelWebhookBody({
changedLabel: 'ready-for-review',
allLabels: [{ name: 'lifecycle-deploy!' }, { name: 'ready-for-review' }],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('ready-for-review');
expect(mockDb.models.PullRequest.findOne).not.toHaveBeenCalled();
expect(mockDb.services.BuildService.resolveAndDeployBuildQueue.add).not.toHaveBeenCalled();
expect(mockDb.services.BuildService.deleteBuild).not.toHaveBeenCalled();
});

test('should skip processing for donotmerge label', async () => {
mockIsLifecycleLabel.mockResolvedValue(false);

const body = createMockLabelWebhookBody({
changedLabel: 'donotmerge',
allLabels: [{ name: 'lifecycle-deploy!' }, { name: 'donotmerge' }],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('donotmerge');
expect(mockDb.models.PullRequest.findOne).not.toHaveBeenCalled();
});

test('should process webhook when deploy label is added', async () => {
mockIsLifecycleLabel.mockResolvedValue(true);
mockHasDeployLabel.mockResolvedValue(true);
mockEnableKillSwitch.mockResolvedValue(false);

const mockPr = createMockPullRequest({ deployOnUpdate: true });
mockDb.models.PullRequest.findOne.mockResolvedValue(mockPr);

const body = createMockLabelWebhookBody({
action: 'labeled',
changedLabel: 'lifecycle-deploy!',
allLabels: [{ name: 'lifecycle-deploy!' }],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('lifecycle-deploy!');
expect(mockDb.models.PullRequest.findOne).toHaveBeenCalled();
expect(mockDb.services.BuildService.resolveAndDeployBuildQueue.add).toHaveBeenCalledWith(
'resolve-deploy',
expect.objectContaining({ buildId: 10 })
);
});

test('should delete build when deploy label is removed', async () => {
mockIsLifecycleLabel.mockResolvedValue(true);
mockHasDeployLabel.mockResolvedValue(false);
mockEnableKillSwitch.mockResolvedValue(false);

const mockPr = createMockPullRequest({ deployOnUpdate: false });
mockDb.models.PullRequest.findOne.mockResolvedValue(mockPr);

const body = createMockLabelWebhookBody({
action: 'unlabeled',
changedLabel: 'lifecycle-deploy!',
allLabels: [],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('lifecycle-deploy!');
expect(mockDb.services.BuildService.deleteBuild).toHaveBeenCalledWith(mockPr.build);
});

test('should delete build when disabled label is added', async () => {
mockIsLifecycleLabel.mockResolvedValue(true);
mockHasDeployLabel.mockResolvedValue(true);
mockEnableKillSwitch.mockResolvedValue(true);

const mockPr = createMockPullRequest({ deployOnUpdate: false });
mockDb.models.PullRequest.findOne.mockResolvedValue(mockPr);

const body = createMockLabelWebhookBody({
action: 'labeled',
changedLabel: 'lifecycle-disabled!',
allLabels: [{ name: 'lifecycle-deploy!' }, { name: 'lifecycle-disabled!' }],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('lifecycle-disabled!');
expect(mockDb.services.BuildService.deleteBuild).toHaveBeenCalledWith(mockPr.build);
});

test('should return early when PR is not found in database', async () => {
mockIsLifecycleLabel.mockResolvedValue(true);
mockDb.models.PullRequest.findOne.mockResolvedValue(null);

const body = createMockLabelWebhookBody({
changedLabel: 'lifecycle-deploy!',
allLabels: [{ name: 'lifecycle-deploy!' }],
});

await githubService.handleLabelWebhook(body);

expect(mockDb.services.BuildService.resolveAndDeployBuildQueue.add).not.toHaveBeenCalled();
expect(mockDb.services.BuildService.deleteBuild).not.toHaveBeenCalled();
});

test('should handle case-insensitive label names', async () => {
mockIsLifecycleLabel.mockResolvedValue(false);

const body = createMockLabelWebhookBody({
changedLabel: 'Ready-For-Review',
allLabels: [{ name: 'lifecycle-deploy!' }, { name: 'Ready-For-Review' }],
});

await githubService.handleLabelWebhook(body);

expect(mockIsLifecycleLabel).toHaveBeenCalledWith('ready-for-review');
expect(mockDb.models.PullRequest.findOne).not.toHaveBeenCalled();
});
});
10 changes: 9 additions & 1 deletion src/server/services/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import * as github from 'server/lib/github';
import { Environment, Repository, Build, PullRequest } from 'server/models';
import { LifecycleYamlConfigOptions } from 'server/models/yaml/types';
import { createOrUpdateGithubDeployment, deleteGithubDeploymentAndEnvironment } from 'server/lib/github/deployments';
import { enableKillSwitch, isStaging, hasDeployLabel } from 'server/lib/utils';
import { enableKillSwitch, isStaging, hasDeployLabel, isLifecycleLabel } from 'server/lib/utils';
import { redisClient } from 'server/lib/dependencies';

export default class GithubService extends Service {
Expand Down Expand Up @@ -196,10 +196,18 @@ export default class GithubService extends Service {
handleLabelWebhook = async (body) => {
const {
action,
label: changedLabel,
pull_request: { id: githubPullRequestId, labels, state: status },
} = body;
let pullRequest: PullRequest, build: Build, _repository: Repository;
try {
const changedLabelName = changedLabel?.name?.toLowerCase();
const isLifecycle = await isLifecycleLabel(changedLabelName);
if (!isLifecycle) {
getLogger().info(`Label: skipping non-lifecycle label=${changedLabelName} action=${action}`);
return;
}

// this is a hacky way to force deploy by adding a label
const labelNames = labels.map(({ name }) => name.toLowerCase()) || [];
const shouldDeploy = isStaging() && labelNames.includes(FallbackLabels.DEPLOY_STG);
Expand Down