forked from GoogleChrome/lighthouse-ci
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(server): server should periodically delete old builds (GoogleChr…
- Loading branch information
1 parent
da359ee
commit d06378f
Showing
9 changed files
with
300 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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/); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters