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
56 changes: 48 additions & 8 deletions src/server/lib/github/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {
getPullRequest,
getPullRequestByRepositoryFullName,
getPullRequestLabels,
addPullRequestLabels,
removePullRequestLabel,
getRepositoryByFullName,
getSHAForBranch,
getShaForDeploy,
Expand All @@ -38,7 +40,6 @@ import {
getYamlFileContentFromPullRequest,
listBranchesForRepo,
listInstallationRepositories,
updatePullRequestLabels,
verifyWebhookSignature,
} from 'server/lib/github';
import * as client from 'server/lib/github/client';
Expand Down Expand Up @@ -357,24 +358,24 @@ describe('repository and pull-request API wrappers', () => {
).rejects.toThrow('Unable to create or update pull request comment');
});

test('replaces pull-request labels and preserves provider errors', async () => {
const request = mockClient(jest.fn().mockResolvedValue({ data: [{ name: 'ready' }] }));
test('adds pull-request labels without replacing existing ones and preserves provider errors', async () => {
const request = mockClient(jest.fn().mockResolvedValue({ data: [{ name: 'existing' }, { name: 'ready' }] }));
await expect(
updatePullRequestLabels({
addPullRequestLabels({
installationId: 19,
pullRequestNumber: 7,
fullName: 'org/repo',
labels: ['ready'],
})
).resolves.toEqual({ data: [{ name: 'ready' }] });
expect(request).toHaveBeenCalledWith('PUT /repos/org/repo/issues/7/labels', {
).resolves.toEqual({ data: [{ name: 'existing' }, { name: 'ready' }] });
expect(request).toHaveBeenCalledWith('POST /repos/org/repo/issues/7/labels', {
data: { labels: ['ready'] },
});

const failure = new Error('label update failed');
const failure = new Error('label add failed');
mockClient(jest.fn().mockRejectedValue(failure));
await expect(
updatePullRequestLabels({
addPullRequestLabels({
installationId: 19,
pullRequestNumber: 7,
fullName: 'org/repo',
Expand All @@ -383,6 +384,45 @@ describe('repository and pull-request API wrappers', () => {
).rejects.toBe(failure);
});

test('removes a single URL-encoded pull-request label', async () => {
const request = mockClient(jest.fn().mockResolvedValue({ data: [] }));
await expect(
removePullRequestLabel({ installationId: 19, pullRequestNumber: 7, fullName: 'org/repo', label: 'deploy now!' })
).resolves.toEqual({ data: [] });
expect(request).toHaveBeenCalledWith('DELETE /repos/org/repo/issues/7/labels/deploy%20now!');

await removePullRequestLabel({
installationId: 19,
pullRequestNumber: 7,
fullName: 'org/repo',
label: 'team/infra',
});
expect(request).toHaveBeenCalledWith('DELETE /repos/org/repo/issues/7/labels/team%2Finfra');
});

test('treats a missing label as already removed but preserves other provider errors', async () => {
mockClient(jest.fn().mockRejectedValue(Object.assign(new Error('Label does not exist'), { status: 404 })));
await expect(
removePullRequestLabel({ installationId: 19, pullRequestNumber: 7, fullName: 'org/repo', label: 'deploy' })
).resolves.toBeNull();
expect(getLogger).toHaveBeenCalledWith({
repo: 'org/repo',
pr: 7,
label: 'deploy',
message: 'Label does not exist',
});
expect((getLogger as jest.Mock)().warn).toHaveBeenCalledWith(
'GitHub: label remove returned 404, treating as already removed'
);
expect((getLogger as jest.Mock)().error).not.toHaveBeenCalledWith('GitHub: label remove failed');

const failure = Object.assign(new Error('forbidden'), { status: 403 });
mockClient(jest.fn().mockRejectedValue(failure));
await expect(
removePullRequestLabel({ installationId: 19, pullRequestNumber: 7, fullName: 'org/repo', label: 'deploy' })
).rejects.toBe(failure);
});

test('normalizes pull-request fetch failures', async () => {
(cacheRequest as jest.Mock).mockRejectedValue({});
await expect(getPullRequest('org', 'repo', 7, 19)).rejects.toThrow('Unable to retrieve pull request');
Expand Down
44 changes: 39 additions & 5 deletions src/server/lib/github/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export async function createOrUpdatePullRequestComment({
}
}

export async function updatePullRequestLabels({
export async function addPullRequestLabels({
installationId,
pullRequestNumber,
fullName,
Expand All @@ -146,9 +146,8 @@ export async function updatePullRequestLabels({
labels: string[];
}) {
try {
const client = await createOctokitClient({ installationId, caller: 'updatePullRequestLabels' });
const requestUrl = `PUT /repos/${fullName}/issues/${pullRequestNumber}/labels`;
return await client.request(requestUrl, {
const client = await createOctokitClient({ installationId, caller: 'addPullRequestLabels' });
return await client.request(`POST /repos/${fullName}/issues/${pullRequestNumber}/labels`, {
data: { labels },
});
} catch (error) {
Expand All @@ -157,7 +156,42 @@ export async function updatePullRequestLabels({
repo: fullName,
pr: pullRequestNumber,
labels: labels.toString(),
}).error('GitHub: labels update failed');
}).error('GitHub: labels add failed');
throw error;
}
}

export async function removePullRequestLabel({
installationId,
pullRequestNumber,
fullName,
label,
}: {
installationId: number;
pullRequestNumber: number;
fullName: string;
label: string;
}) {
try {
const client = await createOctokitClient({ installationId, caller: 'removePullRequestLabel' });
return await client.request(
`DELETE /repos/${fullName}/issues/${pullRequestNumber}/labels/${encodeURIComponent(label)}`
);
} catch (error) {
// GitHub answers 404 when the label is already gone, which is the state we wanted. A missing
// issue or lost app access also 404s, so keep it visible.
if (error?.status === 404) {
getLogger({ repo: fullName, pr: pullRequestNumber, label, message: error?.message }).warn(
'GitHub: label remove returned 404, treating as already removed'
);
return null;
}
getLogger({
error,
repo: fullName,
pr: pullRequestNumber,
label,
}).error('GitHub: label remove failed');
throw error;
}
}
Expand Down
82 changes: 62 additions & 20 deletions src/server/services/__tests__/label.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ const mockLogger = {
const mockWithLogContext = jest.fn((_context, callback) => callback());
const mockUpdateLogContext = jest.fn();
const mockWaitForColumnValue = jest.fn();
const mockUpdatePullRequestLabels = jest.fn();
const mockAddPullRequestLabels = jest.fn();
const mockRemovePullRequestLabel = jest.fn();
const mockGetPullRequestLabels = jest.fn();
const mockGetDeployLabel = jest.fn();
const mockRegisterQueue = jest.fn();

Expand Down Expand Up @@ -52,7 +54,9 @@ jest.mock('shared/utils', () => ({
}));

jest.mock('server/lib/github', () => ({
updatePullRequestLabels: (input: unknown) => mockUpdatePullRequestLabels(input),
addPullRequestLabels: (input: unknown) => mockAddPullRequestLabels(input),
removePullRequestLabel: (input: unknown) => mockRemovePullRequestLabel(input),
getPullRequestLabels: (input: unknown) => mockGetPullRequestLabels(input),
}));

jest.mock('server/lib/utils', () => ({
Expand Down Expand Up @@ -121,10 +125,12 @@ describe('LabelService.processLabelQueue', () => {
jest.clearAllMocks();
mockGetDeployLabel.mockResolvedValue('deploy');
mockWaitForColumnValue.mockResolvedValue({ commentId: 101 });
mockUpdatePullRequestLabels.mockResolvedValue(undefined);
mockAddPullRequestLabels.mockResolvedValue(undefined);
mockRemovePullRequestLabel.mockResolvedValue(undefined);
mockGetPullRequestLabels.mockResolvedValue([]);
});

it('adds the deploy label and propagates the queued logging context', async () => {
it('adds only the deploy label and propagates the queued logging context', async () => {
const { service, findById, withGraphFetched } = createService();

await service.processLabelQueue(job() as any);
Expand All @@ -136,12 +142,13 @@ describe('LabelService.processLabelQueue', () => {
expect(findById).toHaveBeenCalledWith(8);
expect(withGraphFetched).toHaveBeenCalledWith('[repository, build]');
expect(mockUpdateLogContext).toHaveBeenCalledWith({ buildUuid: 'build-uuid' });
expect(mockUpdatePullRequestLabels).toHaveBeenCalledWith({
expect(mockAddPullRequestLabels).toHaveBeenCalledWith({
installationId: 22,
pullRequestNumber: 17,
fullName: 'goodrx/lifecycle',
labels: ['existing', 'deploy'],
labels: ['deploy'],
});
expect(mockRemovePullRequestLabel).not.toHaveBeenCalled();
expect(mockLogger.info).toHaveBeenCalledWith('Label: added label=deploy');
});

Expand All @@ -150,30 +157,65 @@ describe('LabelService.processLabelQueue', () => {

await service.processLabelQueue(job({ labels: ['existing', 'deploy'] }) as any);

expect(mockUpdatePullRequestLabels).not.toHaveBeenCalled();
expect(mockAddPullRequestLabels).not.toHaveBeenCalled();
expect(mockLogger.debug).toHaveBeenCalledWith('Deploy label "deploy" already exists on PR, skipping update');
});

it('removes every configured deploy label while preserving unrelated labels', async () => {
it('removes each configured deploy label currently on the PR without touching other labels', async () => {
mockGetPullRequestLabels.mockResolvedValue(['deploy', 'keep', 'deploy-stg', 'also-keep']);
const { service, getLabels } = createService();

await service.processLabelQueue(
job({ action: 'disable', labels: ['deploy', 'keep', 'deploy-stg', 'also-keep'] }) as any
);
await service.processLabelQueue(job({ action: 'disable', labels: [] }) as any);

expect(getLabels).toHaveBeenCalledTimes(1);
expect(mockUpdatePullRequestLabels).toHaveBeenCalledWith(
expect.objectContaining({ labels: ['keep', 'also-keep'] })
);
expect(mockRemovePullRequestLabel.mock.calls.map(([input]) => input)).toEqual([
{ installationId: 22, pullRequestNumber: 17, fullName: 'goodrx/lifecycle', label: 'deploy' },
{ installationId: 22, pullRequestNumber: 17, fullName: 'goodrx/lifecycle', label: 'deploy-stg' },
]);
expect(mockAddPullRequestLabels).not.toHaveBeenCalled();
expect(mockLogger.info).toHaveBeenCalledWith('Label: removed label=deploy');
});

it('leaves labels unchanged when no deploy labels are configured', async () => {
it('makes no GitHub calls on disable when no deploy labels are configured', async () => {
const { service } = createService({ labelsConfig: { deploy: undefined } as any });

await service.processLabelQueue(job({ action: 'disable', labels: ['keep'] }) as any);

expect(mockUpdatePullRequestLabels).toHaveBeenCalledWith(expect.objectContaining({ labels: ['keep'] }));
expect(mockGetPullRequestLabels).not.toHaveBeenCalled();
expect(mockRemovePullRequestLabel).not.toHaveBeenCalled();
expect(mockAddPullRequestLabels).not.toHaveBeenCalled();
});

it('removes nothing on disable when the PR carries no deploy label', async () => {
mockGetPullRequestLabels.mockResolvedValue(['keep', 'dependencies']);
const { service } = createService();

await service.processLabelQueue(job({ action: 'disable', labels: ['keep', 'dependencies', 'deploy'] }) as any);

expect(mockRemovePullRequestLabel).not.toHaveBeenCalled();
});

it('propagates a failed label lookup on disable so the job retries', async () => {
const failure = new Error('labels unavailable');
mockGetPullRequestLabels.mockRejectedValue(failure);
const { service } = createService();

await expect(service.processLabelQueue(job({ action: 'disable', labels: ['deploy'] }) as any)).rejects.toBe(
failure
);
expect(mockRemovePullRequestLabel).not.toHaveBeenCalled();
});

it('stops removing deploy labels at the first GitHub failure so the job retries', async () => {
const failure = new Error('github unavailable');
mockRemovePullRequestLabel.mockRejectedValueOnce(failure);
mockGetPullRequestLabels.mockResolvedValue(['deploy', 'deploy-stg']);
const { service } = createService();

await expect(
service.processLabelQueue(job({ action: 'disable', labels: ['deploy', 'deploy-stg'] }) as any)
).rejects.toBe(failure);
expect(mockRemovePullRequestLabel).toHaveBeenCalledTimes(1);
});

it('waits for a Mission Control comment before updating labels when requested', async () => {
Expand All @@ -184,7 +226,7 @@ describe('LabelService.processLabelQueue', () => {

expect(mockWaitForColumnValue).toHaveBeenCalledWith(pullRequest, 'commentId', 60, 5000);
expect(mockLogger.warn).not.toHaveBeenCalled();
expect(mockUpdatePullRequestLabels).toHaveBeenCalledTimes(1);
expect(mockAddPullRequestLabels).toHaveBeenCalledTimes(1);
});

it('continues the label update but records a timeout when the comment never appears', async () => {
Expand All @@ -197,7 +239,7 @@ describe('LabelService.processLabelQueue', () => {
expect(mockLogger.warn).toHaveBeenCalledWith(
'Timeout waiting for comment_id while updating labels after 5 minutes'
);
expect(mockUpdatePullRequestLabels).toHaveBeenCalledTimes(1);
expect(mockAddPullRequestLabels).toHaveBeenCalledTimes(1);
});

it('does not wait when the comment is already persisted', async () => {
Expand All @@ -212,7 +254,7 @@ describe('LabelService.processLabelQueue', () => {
const { service } = createService({ pullRequest: null as any });

await expect(service.processLabelQueue(job() as any)).rejects.toThrow('Pull request with id 8 not found');
expect(mockUpdatePullRequestLabels).not.toHaveBeenCalled();
expect(mockAddPullRequestLabels).not.toHaveBeenCalled();
expect(mockLogger.error).toHaveBeenCalledWith(expect.any(Object), 'Failed to process label job for PR 8');
});

Expand All @@ -225,7 +267,7 @@ describe('LabelService.processLabelQueue', () => {

it('propagates GitHub update failures after recording the failed job', async () => {
const failure = new Error('github unavailable');
mockUpdatePullRequestLabels.mockRejectedValue(failure);
mockAddPullRequestLabels.mockRejectedValue(failure);
const { service } = createService();

await expect(service.processLabelQueue(job() as any)).rejects.toBe(failure);
Expand Down
Loading
Loading