From 4acc0e22c8d26744aac4e6191b6587ffdd592d85 Mon Sep 17 00:00:00 2001 From: Matchu Date: Tue, 2 Jul 2013 14:10:24 -0700 Subject: [PATCH] bulk pet loader rate limits itself --- app/assets/javascripts/pets/bulk.js | 27 +++++++++++++++++++++------ config/locales/en.yml | 5 +++-- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/app/assets/javascripts/pets/bulk.js b/app/assets/javascripts/pets/bulk.js index b3838659..98e2e62d 100644 --- a/app/assets/javascripts/pets/bulk.js +++ b/app/assets/javascripts/pets/bulk.js @@ -115,7 +115,10 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug'); $(document.body).addClass('js'); bulk_load_queue = new (function BulkLoadQueue() { - var pets = [], url = form.attr('action') + '.json'; + var RECENTLY_SENT_INTERVAL_IN_SECONDS = 60; + var RECENTLY_SENT_MAX = 10; + var pets = [], url = form.attr('action') + '.json', + recently_sent_count = 0, loading = false; function Pet(name) { var el = $('#bulk-pets-submission-template').tmpl({pet_name: name}). @@ -124,12 +127,12 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug'); this.load = function () { el.removeClass('waiting').addClass('loading'); var response_el = el.find('span.response'); + pets.shift(); + loading = true; $.ajax({ complete: function (data) { - pets.shift(); - if(pets.length) { - pets[0].load(); - } + loading = false; + loadNextIfReady(); }, data: {name: name}, dataType: 'json', @@ -146,6 +149,12 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug'); type: 'post', url: url }); + + recently_sent_count++; + setTimeout(function () { + recently_sent_count--; + loadNextIfReady(); + }, RECENTLY_SENT_INTERVAL_IN_SECONDS * 1000); } } @@ -154,7 +163,13 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug'); if(name.length) { var pet = new Pet(name); pets.push(pet); - if(pets.length == 1) pet.load(); + if(pets.length == 1) loadNextIfReady(); + } + } + + function loadNextIfReady() { + if(!loading && recently_sent_count < RECENTLY_SENT_MAX && pets.length) { + pets[0].load(); } } })(); diff --git a/config/locales/en.yml b/config/locales/en.yml index 791c9f03..8c52b9ae 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -750,8 +750,9 @@ en: header: Model pets in bulk explanation: Got a lot of pets to model? Just keep typing them into the box below, - or even paste in a whole list of names, one name per line. Thanks for - your help! + or even paste in a whole list of names, one name per line. We'll + stagger them over time to keep our servers happy. Thanks for your + help! submit: Load pet add: Add clear: Clear