Skip to content

Commit

Permalink
feat(server): server should periodically delete old builds (#471)
Browse files Browse the repository at this point in the history
  • Loading branch information
koh110 committed Oct 18, 2020
1 parent bf6a83d commit c324f3f
Show file tree
Hide file tree
Showing 9 changed files with 300 additions and 25 deletions.
13 changes: 13 additions & 0 deletions packages/server/src/api/storage/sql/sql.js
Expand Up @@ -456,6 +456,19 @@ class SqlStorageMethod {
}
}

/**
* @param {Date} runAt
* @return {Promise<LHCI.ServerCommand.Build[]>}
*/
async findBuildsBeforeTimestamp(runAt) {
const {buildModel} = this._sql();
const oldBuilds = await buildModel.findAll({
where: {runAt: {[Sequelize.Op.lte]: runAt}},
order: [['runAt', 'ASC']],
});
return oldBuilds;
}

/**
* @param {string} projectId
* @param {string} buildId
Expand Down
9 changes: 9 additions & 0 deletions packages/server/src/api/storage/storage-method.js
Expand Up @@ -148,6 +148,15 @@ class StorageMethod {
throw new Error('Unimplemented');
}

/**
* @param {Date} runAt
* @return {Promise<LHCI.ServerCommand.Build[]>}
*/
// eslint-disable-next-line no-unused-vars
async findBuildsBeforeTimestamp(runAt) {
throw new Error('Unimplemented');
}

/**
* @param {string} projectId
* @param {string} buildId
Expand Down
74 changes: 74 additions & 0 deletions packages/server/src/cron/delete-old-builds.js
@@ -0,0 +1,74 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/

'use strict';

const {CronJob} = require('cron');
const {normalizeCronSchedule} = require('./utils');

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
* @param {number} maxAgeInDays
* @param {Date} now
* @return {Promise<void>}
*/
async function deleteOldBuilds(storageMethod, maxAgeInDays, now = new Date()) {
if (!maxAgeInDays || !Number.isInteger(maxAgeInDays) || maxAgeInDays <= 0) {
throw new Error('Invalid range');
}

const DAY_IN_MS = 24 * 60 * 60 * 1000;
const cutoffTime = new Date(Date.now() - maxAgeInDays * DAY_IN_MS);
const oldBuilds = await storageMethod.findBuildsBeforeTimestamp(cutoffTime);
for (const {projectId, id} of oldBuilds) {
await storageMethod.deleteBuild(projectId, id);
}
}

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
* @param {LHCI.ServerCommand.Options} options
* @return {void}
*/
function startDeleteOldBuildsCron(storageMethod, options) {
if (options.storage.storageMethod !== 'sql' || !options.deleteOldBuildsCron) {
return;
}

if (!options.deleteOldBuildsCron.schedule || !options.deleteOldBuildsCron.maxAgeInDays) {
throw new Error('Cannot configure schedule');
}

const log =
options.logLevel === 'silent'
? () => {}
: msg => process.stdout.write(`${new Date().toISOString()} - ${msg}\n`);

let inProgress = false;

const {schedule, maxAgeInDays} = options.deleteOldBuildsCron;

const cron = new CronJob(normalizeCronSchedule(schedule), () => {
if (inProgress) {
log(`Deleting old builds still in progress. Skipping...`);
return;
}
inProgress = true;
log(`Starting delete old builds`);
deleteOldBuilds(storageMethod, maxAgeInDays, new Date())
.then(() => {
log(`Successfully delete old builds`);
})
.catch(err => {
log(`Delete old builds failure: ${err.message}`);
})
.finally(() => {
inProgress = false;
});
});
cron.start();
}
module.exports = {startDeleteOldBuildsCron, deleteOldBuilds};
26 changes: 1 addition & 25 deletions packages/server/src/cron/psi-collect.js
Expand Up @@ -8,31 +8,7 @@
const {CronJob} = require('cron');
const {getGravatarUrlFromEmail} = require('@lhci/utils/src/build-context');
const PsiRunner = require('@lhci/utils/src/psi-runner.js');

/**
* @param {string} schedule
* @return {string}
*/
function normalizeCronSchedule(schedule) {
if (typeof schedule !== 'string') {
throw new Error(`Schedule must be provided`);
}

if (process.env.OVERRIDE_SCHEDULE_FOR_TEST) {
return process.env.OVERRIDE_SCHEDULE_FOR_TEST;
}

const parts = schedule.split(/\s+/).filter(Boolean);
if (parts.length !== 5) {
throw new Error(`Invalid cron format, expected <minutes> <hours> <day> <month> <day of week>`);
}

if (parts[0] === '*') {
throw new Error(`Cron schedule "${schedule}" is too frequent`);
}

return ['0', ...parts].join(' ');
}
const {normalizeCronSchedule} = require('./utils');

/**
* @param {LHCI.ServerCommand.StorageMethod} storageMethod
Expand Down
33 changes: 33 additions & 0 deletions packages/server/src/cron/utils.js
@@ -0,0 +1,33 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/

'use strict';

/**
* @param {string} schedule
* @return {string}
*/
function normalizeCronSchedule(schedule) {
if (typeof schedule !== 'string') {
throw new Error(`Schedule must be provided`);
}

if (process.env.OVERRIDE_SCHEDULE_FOR_TEST) {
return process.env.OVERRIDE_SCHEDULE_FOR_TEST;
}

const parts = schedule.split(/\s+/).filter(Boolean);
if (parts.length !== 5) {
throw new Error(`Invalid cron format, expected <minutes> <hours> <day> <month> <day of week>`);
}

if (parts[0] === '*') {
throw new Error(`Cron schedule "${schedule}" is too frequent`);
}

return ['0', ...parts].join(' ');
}
module.exports = {normalizeCronSchedule};
2 changes: 2 additions & 0 deletions packages/server/src/server.js
Expand Up @@ -18,6 +18,7 @@ const createProjectsRouter = require('./api/routes/projects.js');
const StorageMethod = require('./api/storage/storage-method.js');
const {errorMiddleware, createBasicAuthMiddleware} = require('./api/express-utils.js');
const {startPsiCollectCron} = require('./cron/psi-collect.js');
const {startDeleteOldBuildsCron} = require('./cron/delete-old-builds');
const version = require('../package.json').version;

const DIST_FOLDER = path.join(__dirname, '../dist');
Expand Down Expand Up @@ -55,6 +56,7 @@ async function createApp(options) {
app.use(errorMiddleware);

startPsiCollectCron(storageMethod, options);
startDeleteOldBuildsCron(storageMethod, options);

return {app, storageMethod};
}
Expand Down
138 changes: 138 additions & 0 deletions packages/server/test/cron/delete-old-builds.test.js
@@ -0,0 +1,138 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/
'use strict';

/* eslint-env jest */

/** @type {jest.MockInstance} */
let cronJob = jest.fn().mockReturnValue({start: () => {}});
jest.mock('cron', () => ({
CronJob: function(...args) {
// use this indirection because we have to invoke it with `new` and it's harder to mock assertions
return cronJob(...args);
},
}));

const {
startDeleteOldBuildsCron,
deleteOldBuilds,
} = require('../../src/cron/delete-old-builds.js');

describe('cron/delete-old-builds', () => {
/** @type {{ findBuildsBeforeTimestamp: jest.MockInstance, deleteBuild: jest.MockInstance}} */
let storageMethod;
beforeEach(() => {
storageMethod = {
findBuildsBeforeTimestamp: jest.fn().mockResolvedValue([]),
deleteBuild: jest.fn().mockResolvedValue({}),
};

cronJob = jest.fn().mockReturnValue({
start: () => {},
});
});
describe('.deleteOldBuilds', () => {
it.each([undefined, null, -1, new Date()])(
'should throw for invalid range (%s)',
async range => {
await expect(deleteOldBuilds(storageMethod, range)).rejects.toMatchObject({
message: 'Invalid range',
});
}
);

it('should collect', async () => {
storageMethod.deleteBuild.mockClear();
const deleteObjects = [{id: 'id-1', projectId: 'pid-1'}, {id: 'id-2', projectId: 'pid-2'}];
storageMethod.findBuildsBeforeTimestamp.mockResolvedValue(deleteObjects);
await deleteOldBuilds(storageMethod, 30, new Date('2019-01-01'));
expect(storageMethod.deleteBuild).toHaveBeenCalledTimes(deleteObjects.length);

expect(storageMethod.deleteBuild.mock.calls).toMatchObject([
['pid-1', 'id-1'],
['pid-2', 'id-2'],
]);
});
});

describe('.startDeleteOldBuildsCron', () => {
it.each([
[
'storageMethod is not sql',
{
storage: {
storageMethod: 'notsql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
maxAgeInDays: 30,
},
},
],
[
'no deleteOldBuilds options',
{
storage: {storageMethod: 'sql'},
},
],
])('should not schedule a cron job (%s)', (_, options) => {
startDeleteOldBuildsCron(storageMethod, options);
expect(cronJob).toHaveBeenCalledTimes(0);
});
it.each([
[
'no schedule',
{
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
maxAgeInDays: 30,
},
},
],
[
'no dateRagne',
{
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
},
},
],
])('should throw for invalid options (%s)', (_, options) => {
expect(() => startDeleteOldBuildsCron(storageMethod, options)).toThrow(/Cannot configure/);
});
it('should throw for invalid schedule', () => {
const options = {
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '* * *',
maxAgeInDays: 30,
},
};
expect(() => startDeleteOldBuildsCron(storageMethod, options)).toThrow(
/Invalid cron format/
);
});
it('should schedule a cron job', () => {
startDeleteOldBuildsCron(storageMethod, {
storage: {
storageMethod: 'sql',
},
deleteOldBuildsCron: {
schedule: '0 * * * *',
maxAgeInDays: 30,
},
});
expect(cronJob).toHaveBeenCalledTimes(1);
});
});
});
26 changes: 26 additions & 0 deletions packages/server/test/cron/utils.test.js
@@ -0,0 +1,26 @@
/**
* @license Copyright 2020 Google Inc. All Rights Reserved.
* 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.
*/
'use strict';

/* eslint-env jest */

const {normalizeCronSchedule} = require('../../src/cron/utils.js');

describe('cron/utils', () => {
describe('.normalizeCronSchedule()', () => {
it('should validate string', () => {
expect(() => normalizeCronSchedule(1)).toThrow(/Schedule must be provided/);
});

it('should validate cron job', () => {
expect(() => normalizeCronSchedule('* * * * *')).toThrow(/too frequent/);
});

it('should validate invalid format', () => {
expect(() => normalizeCronSchedule('* * *')).toThrow(/Invalid cron format/);
});
});
});
4 changes: 4 additions & 0 deletions types/server.d.ts
Expand Up @@ -184,6 +184,10 @@ declare global {
psiApiEndpoint?: string;
sites: Array<PsiCollectEntry>;
};
deleteOldBuildsCron?: {
schedule: string;
maxAgeInDays: number;
}
basicAuth?: {
username?: string;
password?: string;
Expand Down

0 comments on commit c324f3f

Please sign in to comment.