Skip to content

Commit b32707e

Browse files
committed
feat: add build service override state
1 parent d0c0773 commit b32707e

7 files changed

Lines changed: 704 additions & 26 deletions

File tree

‎src/app/api/v2/builds/[uuid]/services/route.ts‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { NextRequest } from 'next/server';
1919
import { createApiHandler } from 'server/lib/createApiHandler';
2020
import { errorResponse, successResponse } from 'server/lib/response';
2121
import OverrideService, {
22+
ServiceOverrideNotEditableError,
2223
ServiceOverrideNotFoundError,
2324
type ServiceOverridePatchInput,
2425
} from 'server/services/override';
@@ -40,12 +41,12 @@ function validateServiceOverride(value: unknown, index: number): ServiceOverride
4041
return new Error(`serviceOverrides[${index}] must be an object`);
4142
}
4243

43-
const serviceName = value.serviceName;
44+
const name = value.name;
4445
const hasActive = hasOwn(value, 'active');
4546
const hasBranchOrExternalUrl = hasOwn(value, 'branchOrExternalUrl');
4647

47-
if (typeof serviceName !== 'string' || serviceName.length === 0) {
48-
return new Error(`serviceOverrides[${index}].serviceName must be a non-empty string`);
48+
if (typeof name !== 'string' || name.length === 0) {
49+
return new Error(`serviceOverrides[${index}].name must be a non-empty string`);
4950
}
5051

5152
if (!hasActive && !hasBranchOrExternalUrl) {
@@ -61,7 +62,7 @@ function validateServiceOverride(value: unknown, index: number): ServiceOverride
6162
}
6263

6364
return {
64-
serviceName,
65+
name,
6566
...(hasActive ? { active: value.active as boolean } : {}),
6667
...(hasBranchOrExternalUrl ? { branchOrExternalUrl: value.branchOrExternalUrl as string } : {}),
6768
};
@@ -95,7 +96,7 @@ function validateServiceOverride(value: unknown, index: number): ServiceOverride
9596
* content:
9697
* application/json:
9798
* schema:
98-
* $ref: '#/components/schemas/BuildOverrideUpdateSuccessResponse'
99+
* $ref: '#/components/schemas/UpdateBuildServiceOverridesSuccessResponse'
99100
* '400':
100101
* description: Invalid request body.
101102
* content:
@@ -136,7 +137,7 @@ const patchHandler = async (req: NextRequest, { params }: { params: { uuid: stri
136137
const override = new OverrideService();
137138
const build = await override.db.models.Build.query()
138139
.findOne({ uuid: params.uuid })
139-
.withGraphFetched('[pullRequest, deploys.[service, deployable]]');
140+
.withGraphFetched('[pullRequest, environment.[defaultServices, optionalServices], deploys.[service, deployable]]');
140141

141142
if (!build) {
142143
return errorResponse(new Error(`Build with UUID ${params.uuid} not found`), { status: 404 }, req);
@@ -150,13 +151,26 @@ const patchHandler = async (req: NextRequest, { params }: { params: { uuid: stri
150151
serviceOverrides,
151152
runUuid: nanoid(),
152153
});
154+
const updatedBuild = await override.db.models.Build.query()
155+
.findOne({ uuid: params.uuid })
156+
.withGraphFetched('[environment.[defaultServices, optionalServices], deploys.[service, deployable]]');
153157

154-
return successResponse(result, { status: 200 }, req);
158+
if (!updatedBuild) {
159+
return errorResponse(new Error(`Build with UUID ${params.uuid} not found`), { status: 404 }, req);
160+
}
161+
162+
const updatedServiceOverrides = await override.getServiceOverrideStates(updatedBuild, updatedBuild.deploys || []);
163+
164+
return successResponse({ serviceOverrides: updatedServiceOverrides, queued: result.queued }, { status: 200 }, req);
155165
} catch (error) {
156166
if (error instanceof ServiceOverrideNotFoundError) {
157167
return errorResponse(error, { status: 404 }, req);
158168
}
159169

170+
if (error instanceof ServiceOverrideNotEditableError) {
171+
return errorResponse(error, { status: 400 }, req);
172+
}
173+
160174
throw error;
161175
}
162176
};

‎src/server/services/__tests__/build.test.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const mockIsFeatureEnabled = jest.fn();
2323
const mockQueueAdd = jest.fn();
2424
const mockCleanupDeploy = jest.fn();
2525
const mockDeleteServiceRows = jest.fn();
26+
const mockGetServiceOverrideStates = jest.fn();
2627

2728
jest.mock('server/lib/dependencies', () => ({
2829
defaultDb: {},
@@ -142,6 +143,13 @@ jest.mock('server/services/webhook', () => ({
142143
})),
143144
}));
144145

146+
jest.mock('server/services/override', () => ({
147+
__esModule: true,
148+
default: jest.fn().mockImplementation(() => ({
149+
getServiceOverrideStates: (...args: any[]) => mockGetServiceOverrideStates(...args),
150+
})),
151+
}));
152+
145153
jest.mock('server/lib/fastly', () =>
146154
jest.fn().mockImplementation(() => ({
147155
getServiceDashboardUrl: jest.fn(),
@@ -245,6 +253,95 @@ describe('BuildService build response queries', () => {
245253
expect(query.findOne).toHaveBeenCalledWith({ uuid: 'sample-build' });
246254
expect(query.select.mock.calls[0]).toEqual(expect.arrayContaining(['commentRuntimeEnv', 'commentInitEnv']));
247255
});
256+
257+
test('attaches service override edit state to deploys when loading a build by UUID', async () => {
258+
const build = {
259+
id: 10,
260+
uuid: 'sample-build',
261+
deploys: [
262+
{
263+
uuid: 'api-sample-build',
264+
deployable: { name: 'api' },
265+
},
266+
{
267+
uuid: 'internal-sample-build',
268+
deployable: { name: 'internal' },
269+
},
270+
],
271+
};
272+
const buildForServiceOverrides = {
273+
id: 10,
274+
uuid: 'sample-build',
275+
deploys: [{ uuid: 'api-sample-build' }],
276+
};
277+
const query: any = {
278+
findOne: jest.fn(() => query),
279+
select: jest.fn(() => query),
280+
withGraphFetched: jest.fn(() => query),
281+
modifyGraph: jest.fn(() => query),
282+
then: (resolve: (value: any) => void, reject: (reason: unknown) => void) =>
283+
Promise.resolve(build).then(resolve, reject),
284+
};
285+
const serviceOverrideQuery: any = {
286+
findOne: jest.fn(() => serviceOverrideQuery),
287+
select: jest.fn(() => serviceOverrideQuery),
288+
withGraphFetched: jest.fn(() => serviceOverrideQuery),
289+
then: (resolve: (value: any) => void, reject: (reason: unknown) => void) =>
290+
Promise.resolve(buildForServiceOverrides).then(resolve, reject),
291+
};
292+
const buildService = new BuildService(
293+
{
294+
models: {
295+
Build: {
296+
query: jest.fn().mockReturnValueOnce(query).mockReturnValueOnce(serviceOverrideQuery),
297+
},
298+
},
299+
} as any,
300+
{} as any,
301+
{} as any,
302+
createQueueManager() as any
303+
);
304+
mockGetServiceOverrideStates.mockResolvedValueOnce([
305+
{
306+
name: 'api',
307+
active: true,
308+
branchOrExternalUrl: 'feature/api',
309+
status: 'deployed',
310+
statusMessage: null,
311+
updatedAt: '2026-05-08T12:00:00.000Z',
312+
group: 'default',
313+
editable: true,
314+
},
315+
]);
316+
317+
await expect(buildService.getBuildByUUID('sample-build')).resolves.toBe(build);
318+
319+
expect(serviceOverrideQuery.findOne).toHaveBeenCalledWith({ id: 10 });
320+
expect(serviceOverrideQuery.withGraphFetched).toHaveBeenCalledWith(
321+
'[environment.[defaultServices, optionalServices], deploys.[service, deployable]]'
322+
);
323+
expect(mockGetServiceOverrideStates).toHaveBeenCalledWith(
324+
buildForServiceOverrides,
325+
buildForServiceOverrides.deploys
326+
);
327+
expect(build.deploys).toEqual([
328+
{
329+
uuid: 'api-sample-build',
330+
deployable: { name: 'api' },
331+
serviceOverride: {
332+
name: 'api',
333+
branchOrExternalUrl: 'feature/api',
334+
group: 'default',
335+
editable: true,
336+
},
337+
},
338+
{
339+
uuid: 'internal-sample-build',
340+
deployable: { name: 'internal' },
341+
serviceOverride: null,
342+
},
343+
]);
344+
});
248345
});
249346

250347
describe('BuildService failure boundaries', () => {

0 commit comments

Comments
 (0)