-
Notifications
You must be signed in to change notification settings - Fork 4
feat: load balance test location in WPT (DELO-4766) #95
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
Merged
lukaszczerpak-cloudinary
merged 12 commits into
master
from
DELO-4766-load-balance-test-location-in-wpt
Dec 9, 2024
Merged
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ae7b227
deps updates
lukaszczerpak-cloudinary 5359fd7
refactor
lukaszczerpak-cloudinary aad4f4c
feat: select least loaded WPT location on new test run (DELO-4766)
lukaszczerpak-cloudinary a15f154
calculate score early and expose it via API
lukaszczerpak-cloudinary 2fff543
- improved selection algorithm
lukaszczerpak-cloudinary 643741a
- changed caching default for locations
lukaszczerpak-cloudinary 4ec766a
formatting
lukaszczerpak-cloudinary 5c26475
make location selector attributes configurable
lukaszczerpak-cloudinary 82c9d78
updates
lukaszczerpak-cloudinary 9af7764
typo
lukaszczerpak-cloudinary 4f6448c
reverted version as it will be changed by release-please
lukaszczerpak-cloudinary 49ad2c3
updated as per review suggestion
lukaszczerpak-cloudinary File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,13 @@ | ||
| "use strict"; | ||
|
|
||
| const config = require('config'); | ||
|
|
||
| function get() { | ||
| const apiKeys = config.get('wtp.apiKey').split(','); | ||
| const apiKey = apiKeys[Math.floor(Math.random() * apiKeys.length)]; | ||
| return apiKey; | ||
| } | ||
|
|
||
| module.exports = { | ||
| get | ||
| }; |
This file contains hidden or 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,136 @@ | ||
| const got = (...args) => import('got').then(({default: got}) => got(...args)); | ||
| const config = require('config'); | ||
| const {Mutex, withTimeout, E_TIMEOUT} = require('async-mutex'); | ||
| const apiKeys = require('./apiKey'); | ||
| const path = require("path"); | ||
| const logger = require('../logger').logger; | ||
|
|
||
| const GET_LOCATIONS = 'http://www.webpagetest.org/getLocations.php?f=json'; | ||
|
|
||
| class LocationSelector { | ||
| constructor() { | ||
| if (!LocationSelector.instance) { | ||
| this.cachedAllLocations = []; | ||
| this.location = config.get('wtp.locationSelector.defaultLocation'); | ||
| this.lastUpdated = null; | ||
| this.mutex = withTimeout(new Mutex(), config.get('wtp.locationSelector.updateTimeout') * 1000); | ||
| LocationSelector.instance = this; | ||
| } | ||
| return LocationSelector.instance; | ||
| } | ||
|
|
||
| isExpired() { | ||
| const now = Date.now(); | ||
| return (!this.lastUpdated || (now - this.lastUpdated) > config.get('wtp.locationSelector.cacheTtl') * 1000); | ||
| } | ||
|
|
||
| async fetchLocations() { | ||
| let options = { | ||
| method: "GET", | ||
| url: GET_LOCATIONS, | ||
| headers: {'User-Agent': 'WebSpeedTest', 'X-WPT-API-KEY': apiKeys.get()}, | ||
| }; | ||
| let response; | ||
| let rollBarMsg = {}; | ||
| try { | ||
| response = await got(options); | ||
| const {statusCode, body} = response; | ||
| let bodyJson = JSON.parse(body); | ||
| rollBarMsg = {thirdPartyErrorCode: response.statusCode, file: path.basename((__filename))}; | ||
| if (statusCode !== 200) { | ||
| rollBarMsg.thirdPartyErrorBody = bodyJson; | ||
| logger.error('WPT returned bad status', rollBarMsg); | ||
| return; | ||
| } | ||
| return bodyJson.data; | ||
| } catch (error) { | ||
| logger.critical('Error fetching WTP locations', JSON.stringify(error, Object.getOwnPropertyNames(error))); | ||
| } | ||
| }; | ||
|
|
||
| getLocationScore(loc) { | ||
| // no instances running, hopefully they will be spin up for our request? | ||
| if (this.getLocationCapacity(loc) == 0) { | ||
| return 1; | ||
| } | ||
|
|
||
| let metrics = loc.PendingTests; | ||
| return (metrics.HighPriority + metrics.Testing) / (metrics.Idle + metrics.Testing) | ||
| } | ||
|
|
||
| getLocationCapacity(loc) { | ||
| return loc.PendingTests.Idle + loc.PendingTests.Testing; | ||
| } | ||
|
|
||
| getBestLocationId(locations) { | ||
| let selected = locations.reduce((acc, cur) => { | ||
| // if nothing to compare to, use current value | ||
| if (!acc) { | ||
| return cur; | ||
| } | ||
|
|
||
| // if acc less loaded | ||
| if (acc.score < cur.score) { | ||
| return acc; | ||
| } | ||
|
|
||
| // if cur less loaded | ||
| if (acc.score > cur.score) { | ||
| return cur; | ||
| } | ||
|
|
||
| // if same load on acc and cur | ||
| // then choose the one with bigger capacity (Idle + Testing) | ||
| return this.getLocationCapacity(acc) > this.getLocationCapacity(cur) ? acc : cur; | ||
| }); | ||
|
|
||
| return selected.location; | ||
| } | ||
|
|
||
| async updateLocations() { | ||
| const newLocations = await this.fetchLocations(); | ||
| if (!newLocations) { | ||
| return | ||
| } | ||
|
|
||
| const filtered = Object.keys(newLocations) | ||
| .filter(key => key.includes("_US_")) // we only want US-based instances | ||
| .reduce((arr, key) => { | ||
| return [...arr, newLocations[key]]; | ||
| }, []); | ||
|
|
||
| if (filtered.length === 0) { | ||
| return | ||
| } | ||
|
|
||
| // enrich locations with our internal score | ||
| filtered.forEach((loc) => { | ||
| loc.score = this.getLocationScore(loc); | ||
| }); | ||
|
|
||
| this.location = this.getBestLocationId(filtered); | ||
| this.cachedAllLocations = filtered; | ||
| this.lastUpdated = Date.now(); | ||
| }; | ||
|
|
||
| async getLocation() { | ||
| if (this.isExpired()) { | ||
| try { | ||
| await this.mutex.runExclusive(async () => { | ||
| if (this.isExpired()) { | ||
| await this.updateLocations(); | ||
| } | ||
| }); | ||
| } catch (e) { | ||
| if (e === E_TIMEOUT) { | ||
| logger.error('Locations update is taking too long', e); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return this.location; | ||
| } | ||
| } | ||
|
|
||
| const instance = new LocationSelector(); | ||
| module.exports = instance; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe to keep the semantics of
keywe could renamegettogetRandom()orgetKey()if random is just an implementation detail..There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
thanks, corrected as per suggestion