From ada76931d8231a83ff15667ccec652b06bd793d4 Mon Sep 17 00:00:00 2001 From: Evgeny Anatskiy Date: Thu, 7 Dec 2017 20:04:55 +0100 Subject: [PATCH] add weighted random webhook pick --- client/galaxy/scripts/layout/menu.js | 2 +- client/galaxy/scripts/mvc/webhooks.js | 24 +++++++++++++++++++++--- client/galaxy/scripts/onload.js | 2 +- lib/galaxy/webhooks/__init__.py | 1 + 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/client/galaxy/scripts/layout/menu.js b/client/galaxy/scripts/layout/menu.js index 149b7ff040f..5134db2fae6 100644 --- a/client/galaxy/scripts/layout/menu.js +++ b/client/galaxy/scripts/layout/menu.js @@ -109,7 +109,7 @@ var Collection = Backbone.Collection.extend({ type: "masthead", callback: function (webhooks) { $(document).ready(() => { - webhooks.each((model) => { + webhooks.each(model => { var webhook = model.toJSON(); if (webhook.activate) { var obj = { diff --git a/client/galaxy/scripts/mvc/webhooks.js b/client/galaxy/scripts/mvc/webhooks.js index 5d7141c6e25..6f0dbc135a5 100644 --- a/client/galaxy/scripts/mvc/webhooks.js +++ b/client/galaxy/scripts/mvc/webhooks.js @@ -20,8 +20,7 @@ const WebhookView = Backbone.View.extend({ data.reset(filterType(data, options.type)); if (data.length > 0) { - const index = _.random(0, data.length - 1); - this.render(data.at(index)); + this.render(weightedRandomPick(data)); } } }); @@ -49,7 +48,26 @@ const load = options => { }; function filterType (data, type) { - return _.filter(data.models, item => item.get('type').indexOf(type) !== -1); + return data.models.filter(item => item.get('type').indexOf(type) !== -1); +} + +function weightedRandomPick (data) { + const weights = data.pluck('weight'); + const sum = weights.reduce((a, b) => a + b); + + const normalizedWeightsMap = new Map(); + weights.forEach((weight, index) => { + normalizedWeightsMap.set(index, parseFloat((weight / sum).toFixed(2))); + }); + + const table = []; + for (const [index, weight] of normalizedWeightsMap) { + for (let i = 0; i < weight * 100; i++) { + table.push(index); + } + } + + return data.at(table[Math.floor(Math.random() * table.length)]); } export default { diff --git a/client/galaxy/scripts/onload.js b/client/galaxy/scripts/onload.js index 75fda90eed5..8c40283700b 100644 --- a/client/galaxy/scripts/onload.js +++ b/client/galaxy/scripts/onload.js @@ -183,7 +183,7 @@ $(document).ready(() => { Webhooks.load({ type: "onload", callback: function (webhooks) { - webhooks.each((model) => { + webhooks.each(model => { var webhook = model.toJSON(); if (webhook.activate && webhook.script) { Utils.appendScriptStyle(webhook); diff --git a/lib/galaxy/webhooks/__init__.py b/lib/galaxy/webhooks/__init__.py index 2a5420016a5..061d7372106 100644 --- a/lib/galaxy/webhooks/__init__.py +++ b/lib/galaxy/webhooks/__init__.py @@ -27,6 +27,7 @@ class Webhook(object): 'id': self.id, 'type': self.type, 'activate': self.activate, + 'weight': self.weight, 'styles': self.styles, 'script': self.script, 'config': self.config,