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
70 changes: 70 additions & 0 deletions src/app/api/v2/schema/validate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { NextRequest } from 'next/server';
import { createApiHandler } from 'server/lib/createApiHandler';
import { errorResponse, successResponse } from 'server/lib/response';
import BuildService from 'server/services/build';

/**
* @openapi
* /api/v2/schema/validate:
* get:
* summary: Validate lifecycle schema
* description: Validates the lifecycle schema from a specified GitHub repository and branch.
* tags:
* - Schema
* operationId: validateLifecycleSchema
* parameters:
* - in: query
* name: repo
* schema:
* type: string
* required: true
* description: The GitHub repository in the format "owner/repo".
* - in: query
* name: branch
* schema:
* type: string
* required: true
* description: The branch name in the repository.
* responses:
* '200':
* description: A paginated list of builds.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ValidateLifecycleSchemaSuccessResponse'
* '400':
* description: Bad request
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
* '500':
* description: Server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
*/
const getHandler = async (req: NextRequest) => {
const { searchParams } = req.nextUrl;
const buildService = new BuildService();

const repo = searchParams.get('repo');
const branch = searchParams.get('branch');

if (![repo, branch].every((val) => typeof val === 'string' && val.trim() !== '')) {
return errorResponse('Invalid repo or branch in request body', { status: 400 }, req);
}

const schemaValidation = await buildService.validateLifecycleSchema(repo, branch);

return successResponse(
schemaValidation,
{
status: 200,
},
req
);
};

export const GET = createApiHandler(getHandler);
17 changes: 13 additions & 4 deletions src/server/services/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ import _ from 'lodash';
import { QUEUE_NAMES } from 'shared/config';
import { LifecycleError } from 'server/lib/errors';
import rootLogger from 'server/lib/logger';
import { ParsingError } from 'server/lib/yamlConfigParser';
import { ValidationError } from 'server/lib/yamlConfigValidator';
import { ParsingError, YamlConfigParser } from 'server/lib/yamlConfigParser';
import { ValidationError, YamlConfigValidator } from 'server/lib/yamlConfigValidator';

import Fastly from 'server/lib/fastly';
import { constructBuildLinks, determineIfFastlyIsUsed, insertBuildLink } from 'shared/utils';
Expand All @@ -43,6 +43,7 @@ import { redisClient } from 'server/lib/dependencies';
import { generateGraph } from 'server/lib/dependencyGraph';
import GlobalConfigService from './globalConfig';
import { paginate, PaginationMetadata, PaginationParams } from 'server/lib/paginate';
import { getYamlFileContentFromBranch } from 'server/lib/github';

const logger = rootLogger.child({
filename: 'services/build.ts',
Expand Down Expand Up @@ -172,10 +173,10 @@ export default class BuildService extends BaseService {
async getBuildByUUID(uuid: string): Promise<Build | null> {
const build = await this.db.models.Build.query()
.findOne({ uuid })
.select('id', 'uuid', 'status', 'namespace', 'createdAt', 'updatedAt')
.select('id', 'uuid', 'status', 'namespace', 'manifest', 'sha', 'createdAt', 'updatedAt')
.withGraphFetched('[pullRequest, deploys.[deployable]]')
.modifyGraph('pullRequest', (b) => {
b.select('id', 'title', 'fullName', 'githubLogin', 'pullRequestNumber', 'branchName');
b.select('id', 'title', 'fullName', 'githubLogin', 'pullRequestNumber', 'branchName', 'status', 'labels');
})
.modifyGraph('deploys', (b) => {
b.select('id', 'uuid', 'status', 'active', 'deployableId');
Expand All @@ -187,6 +188,14 @@ export default class BuildService extends BaseService {
return build;
}

async validateLifecycleSchema(repo: string, branch: string): Promise<{ valid: boolean }> {
const content = (await getYamlFileContentFromBranch(repo, branch)) as string;
const parser = new YamlConfigParser();
const config = parser.parseYamlConfigFromString(content);
const isValid = new YamlConfigValidator().validate(config?.version, config);
return { valid: isValid };
}

/**
* Returns namespace of a build based on either id or uuid.
*/
Expand Down
44 changes: 42 additions & 2 deletions src/shared/openApiSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export const openApiSpecificationForV2Api: OAS3Options = {
type: 'object',
properties: {
id: { type: 'integer' },
sha: { type: 'string', example: 'a1b2c3d4e5f6g7h8i9j0' },
manifest: { type: 'string', example: 'version: 1.0.0\nservices:\n web:\n image: myapp:web\n' },
uuid: { type: 'string', example: 'white-poetry-596195' },
status: { $ref: '#/components/schemas/BuildStatus' },
namespace: { type: 'string', example: 'env-white-poetry-596195' },
Expand All @@ -114,7 +116,18 @@ export const openApiSpecificationForV2Api: OAS3Options = {
items: { $ref: '#/components/schemas/Deploy' },
},
},
required: ['id', 'uuid', 'status', 'namespace', 'createdAt', 'updatedAt', 'pullRequest', 'deploys'],
required: [
'id',
'uuid',
'status',
'namespace',
'manifest',
'sha',
'createdAt',
'updatedAt',
'pullRequest',
'deploys',
],
},

/**
Expand Down Expand Up @@ -155,9 +168,14 @@ export const openApiSpecificationForV2Api: OAS3Options = {
fullName: { type: 'string', example: 'goodrx/lifecycle' },
githubLogin: { type: 'string', example: 'lifecycle-bot' },
pullRequestNumber: { type: 'integer', example: 42 },
status: { type: 'string', example: 'open' },
branchName: { type: 'string', example: 'feature/new-feature' },
labels: {
type: 'array',
items: { type: 'string', example: 'lifecycle-deploy!' },
},
},
required: ['id', 'title', 'fullName', 'githubLogin', 'pullRequestNumber', 'branchName'],
required: ['id', 'title', 'fullName', 'githubLogin', 'pullRequestNumber', 'branchName', 'status', 'labels'],
},

/**
Expand Down Expand Up @@ -194,6 +212,28 @@ export const openApiSpecificationForV2Api: OAS3Options = {
},
],
},

/**
* @description The specific success response for the GET /schema/validate endpoint.
*/
ValidateLifecycleSchemaSuccessResponse: {
allOf: [
{ $ref: '#/components/schemas/SuccessApiResponse' },
{
type: 'object',
properties: {
data: {
type: 'object',
properties: {
valid: { type: 'boolean' },
},
required: ['valid'],
},
},
required: ['data'],
},
],
},
},
},
},
Expand Down