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
217 changes: 217 additions & 0 deletions src/app/api/v2/builds/[uuid]/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
/**
* Copyright 2026 Lifecycle contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { NextRequest } from 'next/server';

const mockGetBuildByUUID = jest.fn();
const mockQueueAdd = jest.fn();
const mockFindOne = jest.fn();
const mockWithGraphFetched = jest.fn();
const mockValidateUuid = jest.fn();
const mockUpdateBuildUuid = jest.fn();

jest.mock('nanoid', () => ({
nanoid: jest.fn(() => 'run-uuid'),
}));

jest.mock('server/lib/logger', () => ({
getLogger: jest.fn(() => ({
error: jest.fn(),
info: jest.fn(),
})),
LogStage: {
BUILD_QUEUED: 'build_queued',
},
}));

jest.mock('server/services/build', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
getBuildByUUID: (...args: unknown[]) => mockGetBuildByUUID(...args),
resolveAndDeployBuildQueue: {
add: (...args: unknown[]) => mockQueueAdd(...args),
},
})),
}));

jest.mock('server/services/override', () => {
class BuildUuidValidationError extends Error {
constructor(message: string) {
super(message);
this.name = 'BuildUuidValidationError';
}
}

return {
__esModule: true,
BuildUuidValidationError,
default: jest.fn().mockImplementation(() => ({
db: {
models: {
Build: {
query: jest.fn(() => ({
findOne: (...args: unknown[]) => mockFindOne(...args),
})),
},
},
},
validateUuid: (...args: unknown[]) => mockValidateUuid(...args),
updateBuildUuid: (...args: unknown[]) => mockUpdateBuildUuid(...args),
})),
};
});

import { GET, PATCH } from './route';

function makeRequest(body?: Record<string, unknown>): NextRequest {
return {
json: jest.fn().mockResolvedValue(body || {}),
headers: new Headers([['x-request-id', 'req-test']]),
nextUrl: new URL('http://localhost/api/v2/builds/current-build'),
} as unknown as NextRequest;
}

describe('/api/v2/builds/[uuid]', () => {
beforeEach(() => {
jest.clearAllMocks();
mockFindOne.mockReturnValue({
withGraphFetched: mockWithGraphFetched,
});
mockValidateUuid.mockResolvedValue({ valid: true });
mockUpdateBuildUuid.mockResolvedValue({
build: {
id: 42,
uuid: 'new-build',
},
deploysUpdated: 3,
});
});

it('GET returns a build by UUID', async () => {
mockGetBuildByUUID.mockResolvedValueOnce({
id: 42,
uuid: 'current-build',
});

const response = await GET(makeRequest(), {
params: {
uuid: 'current-build',
},
});
const body = await response.json();

expect(response.status).toBe(200);
expect(mockGetBuildByUUID).toHaveBeenCalledWith('current-build');
expect(body.data).toEqual({
id: 42,
uuid: 'current-build',
});
});

it('PATCH validates and updates the build UUID', async () => {
const build = {
id: 42,
uuid: 'current-build',
pullRequest: {
deployOnUpdate: true,
},
};
mockWithGraphFetched.mockResolvedValueOnce(build);

const response = await PATCH(makeRequest({ uuid: 'new-build' }), {
params: {
uuid: 'current-build',
},
});
const body = await response.json();

expect(response.status).toBe(200);
expect(mockFindOne).toHaveBeenCalledWith({ uuid: 'current-build' });
expect(mockWithGraphFetched).toHaveBeenCalledWith('pullRequest');
expect(mockValidateUuid).toHaveBeenCalledWith('new-build', 42);
expect(mockUpdateBuildUuid).toHaveBeenCalledWith(build, 'new-build');
expect(mockQueueAdd).toHaveBeenCalledWith('resolve-deploy', {
buildId: 42,
runUUID: 'run-uuid',
correlationId: 'req-test',
});
expect(body.data).toEqual({
id: 42,
uuid: 'new-build',
});
});

it('PATCH rejects unavailable UUIDs before updating', async () => {
mockWithGraphFetched.mockResolvedValueOnce({
id: 42,
uuid: 'current-build',
});
mockValidateUuid.mockResolvedValueOnce({
valid: false,
error: 'UUID is not available',
});

const response = await PATCH(makeRequest({ uuid: 'existing-build' }), {
params: {
uuid: 'current-build',
},
});
const body = await response.json();

expect(response.status).toBe(400);
expect(body.error.message).toBe('UUID is not available');
expect(mockUpdateBuildUuid).not.toHaveBeenCalled();
expect(mockQueueAdd).not.toHaveBeenCalled();
});

it('PATCH returns 404 when the build does not exist', async () => {
mockWithGraphFetched.mockResolvedValueOnce(null);

const response = await PATCH(makeRequest({ uuid: 'new-build' }), {
params: {
uuid: 'missing-build',
},
});

expect(response.status).toBe(404);
expect(mockValidateUuid).not.toHaveBeenCalled();
expect(mockUpdateBuildUuid).not.toHaveBeenCalled();
});

it('PATCH rejects missing UUID bodies and no-op UUID changes', async () => {
const missingUuidResponse = await PATCH(makeRequest({}), {
params: {
uuid: 'current-build',
},
});
expect(missingUuidResponse.status).toBe(400);

mockWithGraphFetched.mockResolvedValueOnce({
id: 42,
uuid: 'current-build',
});

const sameUuidResponse = await PATCH(makeRequest({ uuid: 'current-build' }), {
params: {
uuid: 'current-build',
},
});

expect(sameUuidResponse.status).toBe(400);
expect(mockValidateUuid).not.toHaveBeenCalled();
expect(mockUpdateBuildUuid).not.toHaveBeenCalled();
});
});
105 changes: 104 additions & 1 deletion src/app/api/v2/builds/[uuid]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { nanoid } from 'nanoid';
import { NextRequest } from 'next/server';
import { createApiHandler } from 'server/lib/createApiHandler';
import { getLogger, LogStage } from 'server/lib/logger';
import { errorResponse, successResponse } from 'server/lib/response';
import BuildService from 'server/services/build';
import OverrideService, { BuildUuidValidationError } from 'server/services/override';

interface UpdateBuildUuidRequest {
uuid?: unknown;
}

/**
* @openapi
* /api/v2/builds/{uuid}:
Expand Down Expand Up @@ -44,7 +52,7 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
const build = await buildService.getBuildByUUID(params.uuid);

if (!build) {
return errorResponse(`Build with UUID ${params.uuid} not found`, { status: 404 }, req);
return errorResponse(new Error(`Build with UUID ${params.uuid} not found`), { status: 404 }, req);
}

return successResponse(
Expand All @@ -56,4 +64,99 @@ const getHandler = async (req: NextRequest, { params }: { params: { uuid: string
);
};

/**
* @openapi
* /api/v2/builds/{uuid}:
* patch:
* summary: Update a build UUID
* description: Updates a build UUID and the related deployable and deploy UUID fields.
* tags:
* - Builds
* operationId: updateBuildUUID
* parameters:
* - in: path
* name: uuid
* required: true
* schema:
* type: string
* description: The current UUID of the build to update.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/UpdateBuildUUIDRequest'
* responses:
* '200':
* description: Updated build object.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/UpdateBuildUUIDSuccessResponse'
* '400':
* description: Invalid or unavailable UUID.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
* '404':
* description: Build not found.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
* '500':
* description: Server error.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
*/
const patchHandler = async (req: NextRequest, { params }: { params: { uuid: string } }) => {
const body = (await req.json().catch(() => null)) as UpdateBuildUuidRequest | null;
const newUuid = body?.uuid;

if (!newUuid || typeof newUuid !== 'string') {
return errorResponse(new Error('uuid is required'), { status: 400 }, req);
}

const override = new OverrideService();
const build = await override.db.models.Build.query().findOne({ uuid: params.uuid }).withGraphFetched('pullRequest');

if (!build) {
return errorResponse(new Error(`Build with UUID ${params.uuid} not found`), { status: 404 }, req);
}

if (newUuid === build.uuid) {
return errorResponse(new Error('UUID must be different'), { status: 400 }, req);
}

const validation = await override.validateUuid(newUuid, build.id);
if (!validation.valid) {
return errorResponse(new Error(validation.error || 'Invalid UUID'), { status: 400 }, req);
}

try {
const result = await override.updateBuildUuid(build, newUuid);

if (build.pullRequest?.deployOnUpdate) {
getLogger({ stage: LogStage.BUILD_QUEUED }).info('Triggering redeploy after UUID update');
await new BuildService().resolveAndDeployBuildQueue.add('resolve-deploy', {
buildId: build.id,
runUUID: nanoid(),
correlationId: req.headers.get('x-request-id') || `api-build-update-${Date.now()}`,
});
}

return successResponse(result.build, { status: 200 }, req);
} catch (error) {
if (error instanceof BuildUuidValidationError) {
return errorResponse(error, { status: 400 }, req);
}

throw error;
}
};

export const GET = createApiHandler(getHandler);
export const PATCH = createApiHandler(patchHandler);
9 changes: 7 additions & 2 deletions src/pages/api/v1/builds/[uuid]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { nanoid } from 'nanoid';
import { NextApiRequest, NextApiResponse } from 'next/types';
import { withLogContext, getLogger, LogStage } from 'server/lib/logger';
import BuildService from 'server/services/build';
import OverrideService from 'server/services/override';
import OverrideService, { BuildUuidValidationError } from 'server/services/override';

async function retrieveBuild(req: NextApiRequest, res: NextApiResponse) {
try {
Expand Down Expand Up @@ -80,7 +80,7 @@ async function updateBuild(req: NextApiRequest, res: NextApiResponse, correlatio
return res.status(400).json({ error: 'UUID must be different' });
}

const validation = await override.validateUuid(newUuid);
const validation = await override.validateUuid(newUuid, build.id);
if (!validation.valid) {
getLogger().debug(`UUID validation failed: error=${validation.error}`);
return res.status(400).json({ error: validation.error });
Expand All @@ -103,6 +103,11 @@ async function updateBuild(req: NextApiRequest, res: NextApiResponse, correlatio
},
});
} catch (error) {
if (error instanceof BuildUuidValidationError) {
getLogger().debug(`UUID validation failed: error=${error.message}`);
return res.status(400).json({ error: error.message });
}

getLogger({ error }).error(`API: UUID update failed newUuid=${newUuid}`);
return res.status(500).json({ error: 'An unexpected error occurred' });
}
Expand Down
Loading
Loading