Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: compare records to previous commit when base branch not exist #83

Merged
merged 1 commit into from
Jan 22, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@
"env-var": "^7.0.1",
"fastify": "^3.19.1",
"fastify-cors": "^6.0.2",
"mongodb": "^4.2.2"
"mongodb": "^4.3.1"
},
"devDependencies": {
"@types/bytes": "^3.1.0",
"@types/fastify-cors": "^2.1.0",
"dotenv": "^10.0.0",
"nodemon": "^2.0.7",
"rimraf": "^3.0.2",
"ts-json-schema-generator": "^0.94.1",
"ts-node": "^10.2.0",
"vercel": "^21.3.3"
"vercel": "^21.3.3",
"typescript": "^4.3.5"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

exports[`consts snapshot 1`] = `
Object {
"BaseRecordCompareTo": Object {
"LatestCommit": "LATEST_COMMIT",
"PreviousCommit": "PREVIOUS_COMMIT",
},
"CommitRecordsQueryResolution": Object {
"All": "all",
"Days": "days",
Expand Down
5 changes: 5 additions & 0 deletions service/src/consts/commitRecords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ export enum CommitRecordsQueryResolution {
Weeks = 'weeks',
Months = 'months',
}

export enum BaseRecordCompareTo {
PreviousCommit = 'PREVIOUS_COMMIT',
LatestCommit = 'LATEST_COMMIT',
}
24 changes: 22 additions & 2 deletions service/src/consts/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,16 @@ export const GetCommitRecordRequestSchema = {
$id: '#/definitions/GetCommitRecordRequestSchema',
type: 'object',
properties: {
query: {},
query: {
type: 'object',
properties: {
compareTo: {
$ref: '#/definitions/BaseRecordCompareTo',
default: 'PREVIOUS_COMMIT',
},
},
additionalProperties: false,
},
params: {
type: 'object',
properties: {
Expand All @@ -230,17 +239,24 @@ export const GetCommitRecordRequestSchema = {
},
commitRecordId: {
type: 'string',
pattern: '^[0-9a-fA-F]{24}$',
},
},
required: ['commitRecordId', 'projectId'],
additionalProperties: false,
},
headers: {},
},
required: ['params'],
required: ['params', 'query'],
additionalProperties: false,
};

export const BaseRecordCompareTo = {
$id: '#/definitions/BaseRecordCompareTo',
type: 'string',
enum: ['PREVIOUS_COMMIT', 'LATEST_COMMIT'],
};

export const GetCommitRecordsQuery = {
$id: '#/definitions/GetCommitRecordsQuery',
type: 'object',
Expand All @@ -257,6 +273,10 @@ export const GetCommitRecordsQuery = {
subProject: {
type: 'string',
},
olderThan: {
type: 'string',
format: 'date-time',
},
},
required: ['branch'],
additionalProperties: false,
Expand Down
46 changes: 28 additions & 18 deletions service/src/controllers/commitRecordsController.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createCommitRecord, getCommitRecords, getCommitRecord } from '../framework/mongo';
import { checkAuthHeaders } from './utils/auth';
import { generateLinkToReport } from '../utils/linkUtils';
import { BaseRecordCompareTo } from '../consts/commitRecords';

import type {
FastifyValidatedRoute,
Expand Down Expand Up @@ -32,26 +33,29 @@ export const createCommitRecordController: FastifyValidatedRoute<CreateCommitRec
return;
}

const record = await createCommitRecord(projectId, body);

req.log.info({ recordId: record.id }, 'commit record created');

let baseRecord: CommitRecord | undefined;

if (body.baseBranch) {
try {
baseRecord = (
await getCommitRecords(projectId, { branch: body.baseBranch, subProject: body.subProject, latest: true })
)?.[0];

if (baseRecord) {
req.log.info({ baseRecordId: baseRecord.id }, 'baseRecord fetched');
}
} catch (err) {
req.log.error({ err }, 'Error while fetching base branch');
try {
baseRecord = (
await getCommitRecords(projectId, {
branch: body.baseBranch ?? body.branch,
subProject: body.subProject,
latest: true,
olderThan: new Date(record.creationDate),
})
)?.[0];

if (baseRecord) {
req.log.info({ baseRecordId: baseRecord.id }, 'base record found');
}
} catch (err) {
req.log.error({ err }, 'Error while fetching base record');
}

const record = await createCommitRecord(projectId, body);

req.log.info({ recordId: record.id }, 'commit record created');

const response: CreateCommitRecordResponse = {
record,
baseRecord,
Expand All @@ -66,6 +70,7 @@ export const getCommitRecordWithBaseController: FastifyValidatedRoute<GetCommitR
res
) => {
const { projectId, commitRecordId } = req.params;
const { compareTo = BaseRecordCompareTo.PreviousCommit } = req.query;

const record = await getCommitRecord({ projectId, commitRecordId });

Expand All @@ -75,9 +80,14 @@ export const getCommitRecordWithBaseController: FastifyValidatedRoute<GetCommitR
return;
}

const baseRecord = record.baseBranch
? (await getCommitRecords(projectId, { branch: record.baseBranch, latest: true }))?.[0]
: undefined;
const baseRecord = (
await getCommitRecords(projectId, {
branch: record.baseBranch ?? record.branch,
subProject: record.subProject,
latest: true,
olderThan: compareTo === BaseRecordCompareTo.PreviousCommit ? new Date(record.creationDate) : undefined,
})
)?.[0];

const response: BaseCommitRecordResponse = { record, baseRecord };

Expand Down
2 changes: 1 addition & 1 deletion service/src/controllers/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export async function checkAuthHeaders(
} catch (err) {
let errorMsg = 'forbidden';

if (err.status === 404) {
if ((err as any).status === 404) {
errorMsg = `GitHub action ${runId} not found for ${owner}/${repo}`;
log.warn({ projectId }, 'workflow not found');
} else {
Expand Down
26 changes: 18 additions & 8 deletions service/src/framework/mongo.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { MongoClient, ReadPreference, Db, ObjectId, WithId, MongoClientOptions, ReturnDocument } from 'mongodb';
import { MongoClient, ReadPreference, Db, ObjectId, WithId, MongoClientOptions, ReturnDocument, Filter } from 'mongodb';
import { mongoUrl, mongoDbName, nodeEnv, mongoDbUser, mongoDbPassword } from './env';
import { CommitRecordsQueryResolution } from '../consts/commitRecords';

import type { CommitRecordPayload, CommitRecord } from 'bundlemon-utils';
import type { GetCommitRecordsQuery } from '../types/schemas';
import type { ProjectApiKey } from '../types';

interface CommitRecordDB extends WithId<CommitRecordPayload> {
interface CommitRecordDB extends CommitRecordPayload {
projectId: string;
creationDate: Date;
}

interface ProjectDB extends WithId<void> {
interface ProjectDB {
apiKey: ProjectApiKey;
creationDate: Date;
}
Expand Down Expand Up @@ -79,7 +79,7 @@ export const getProjectApiKeyHash = async (projectId: string): Promise<string |
return data?.apiKey?.hash;
};

const commitRecordDBToResponse = (record: CommitRecordDB): CommitRecord => {
const commitRecordDBToResponse = (record: WithId<CommitRecordDB>): CommitRecord => {
const { _id, creationDate, ...restRecord } = record;

return { id: _id.toHexString(), creationDate: creationDate.toISOString(), ...restRecord };
Expand Down Expand Up @@ -164,17 +164,24 @@ const resolutions: Record<

export async function getCommitRecords(
projectId: string,
{ branch, latest, resolution, subProject }: GetCommitRecordsQuery
{ branch, latest, resolution, subProject, olderThan }: GetCommitRecordsQuery
): Promise<CommitRecord[]> {
const commitRecordsCollection = await getCommitRecordsCollection();

let records: CommitRecordDB[] = [];
let creationDateFilter: Filter<Pick<CommitRecordDB, 'creationDate'>> | undefined = undefined;

if (olderThan) {
creationDateFilter = { creationDate: { $lt: olderThan } };
}

let records: WithId<CommitRecordDB>[] = [];

if (resolution && resolution !== CommitRecordsQueryResolution.All) {
records = await commitRecordsCollection
.aggregate<CommitRecordDB>([
.aggregate<WithId<CommitRecordDB>>([
{
$match: {
...creationDateFilter,
projectId,
branch,
subProject,
Expand Down Expand Up @@ -210,7 +217,10 @@ export async function getCommitRecords(
.toArray();
} else {
records = await commitRecordsCollection
.find({ projectId, branch: branch, subProject }, { sort: { creationDate: -1 }, limit: latest ? 1 : MAX_RECORDS })
.find(
{ ...creationDateFilter, projectId, branch: branch, subProject },
{ sort: { creationDate: -1 }, limit: latest ? 1 : MAX_RECORDS }
)
.toArray();
}

Expand Down