|
| 1 | +const got = (...args) => import('got').then(({default: got}) => got(...args)); |
| 2 | +const config = require('config'); |
| 3 | +const {Mutex, withTimeout, E_TIMEOUT} = require('async-mutex'); |
| 4 | +const apiKeys = require('./apiKey'); |
| 5 | +const path = require("path"); |
| 6 | +const logger = require('../logger').logger; |
| 7 | + |
| 8 | +const GET_LOCATIONS = 'http://www.webpagetest.org/getLocations.php?f=json'; |
| 9 | + |
| 10 | +class LocationSelector { |
| 11 | + constructor() { |
| 12 | + if (!LocationSelector.instance) { |
| 13 | + this.cachedAllLocations = []; |
| 14 | + this.location = config.get('wtp.locationSelector.defaultLocation'); |
| 15 | + this.lastUpdated = null; |
| 16 | + this.mutex = withTimeout(new Mutex(), config.get('wtp.locationSelector.updateTimeout') * 1000); |
| 17 | + LocationSelector.instance = this; |
| 18 | + } |
| 19 | + return LocationSelector.instance; |
| 20 | + } |
| 21 | + |
| 22 | + isExpired() { |
| 23 | + const now = Date.now(); |
| 24 | + return (!this.lastUpdated || (now - this.lastUpdated) > config.get('wtp.locationSelector.cacheTtl') * 1000); |
| 25 | + } |
| 26 | + |
| 27 | + async fetchLocations() { |
| 28 | + let options = { |
| 29 | + method: "GET", |
| 30 | + url: GET_LOCATIONS, |
| 31 | + headers: {'User-Agent': 'WebSpeedTest', 'X-WPT-API-KEY': apiKeys.getRandom()}, |
| 32 | + }; |
| 33 | + let response; |
| 34 | + let rollBarMsg = {}; |
| 35 | + try { |
| 36 | + response = await got(options); |
| 37 | + const {statusCode, body} = response; |
| 38 | + let bodyJson = JSON.parse(body); |
| 39 | + rollBarMsg = {thirdPartyErrorCode: response.statusCode, file: path.basename((__filename))}; |
| 40 | + if (statusCode !== 200) { |
| 41 | + rollBarMsg.thirdPartyErrorBody = bodyJson; |
| 42 | + logger.error('WPT returned bad status', rollBarMsg); |
| 43 | + return; |
| 44 | + } |
| 45 | + return bodyJson.data; |
| 46 | + } catch (error) { |
| 47 | + logger.critical('Error fetching WTP locations', JSON.stringify(error, Object.getOwnPropertyNames(error))); |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + getLocationScore(loc) { |
| 52 | + // no instances running, hopefully they will be spin up for our request? |
| 53 | + if (this.getLocationCapacity(loc) == 0) { |
| 54 | + return 1; |
| 55 | + } |
| 56 | + |
| 57 | + let metrics = loc.PendingTests; |
| 58 | + return (metrics.HighPriority + metrics.Testing) / (metrics.Idle + metrics.Testing) |
| 59 | + } |
| 60 | + |
| 61 | + getLocationCapacity(loc) { |
| 62 | + return loc.PendingTests.Idle + loc.PendingTests.Testing; |
| 63 | + } |
| 64 | + |
| 65 | + getBestLocationId(locations) { |
| 66 | + let selected = locations.reduce((acc, cur) => { |
| 67 | + // if nothing to compare to, use current value |
| 68 | + if (!acc) { |
| 69 | + return cur; |
| 70 | + } |
| 71 | + |
| 72 | + // if acc less loaded |
| 73 | + if (acc.score < cur.score) { |
| 74 | + return acc; |
| 75 | + } |
| 76 | + |
| 77 | + // if cur less loaded |
| 78 | + if (acc.score > cur.score) { |
| 79 | + return cur; |
| 80 | + } |
| 81 | + |
| 82 | + // if same load on acc and cur |
| 83 | + // then choose the one with bigger capacity (Idle + Testing) |
| 84 | + return this.getLocationCapacity(acc) > this.getLocationCapacity(cur) ? acc : cur; |
| 85 | + }); |
| 86 | + |
| 87 | + return selected.location; |
| 88 | + } |
| 89 | + |
| 90 | + async updateLocations() { |
| 91 | + const newLocations = await this.fetchLocations(); |
| 92 | + if (!newLocations) { |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + const filtered = Object.keys(newLocations) |
| 97 | + .filter(key => key.includes("_US_")) // we only want US-based instances |
| 98 | + .reduce((arr, key) => { |
| 99 | + return [...arr, newLocations[key]]; |
| 100 | + }, []); |
| 101 | + |
| 102 | + if (filtered.length === 0) { |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + // enrich locations with our internal score |
| 107 | + filtered.forEach((loc) => { |
| 108 | + loc.score = this.getLocationScore(loc); |
| 109 | + }); |
| 110 | + |
| 111 | + this.location = this.getBestLocationId(filtered); |
| 112 | + this.cachedAllLocations = filtered; |
| 113 | + this.lastUpdated = Date.now(); |
| 114 | + }; |
| 115 | + |
| 116 | + async getLocation() { |
| 117 | + if (this.isExpired()) { |
| 118 | + try { |
| 119 | + await this.mutex.runExclusive(async () => { |
| 120 | + if (this.isExpired()) { |
| 121 | + await this.updateLocations(); |
| 122 | + } |
| 123 | + }); |
| 124 | + } catch (e) { |
| 125 | + if (e === E_TIMEOUT) { |
| 126 | + logger.error('Locations update is taking too long', e); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + return this.location; |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +const instance = new LocationSelector(); |
| 136 | +module.exports = instance; |
0 commit comments