Skip to content
This repository has been archived by the owner on Jan 25, 2020. It is now read-only.

[issue-3] Implemented Sumologic Api throttling #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
coverage/
.nyc_output/
node_modules/
13 changes: 10 additions & 3 deletions lib/job.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
const events = require('events');
const http = require('got');
const qs = require('querystring');
const throttledQueue = require('throttled-queue');

const throttle = throttledQueue(4, 1000); // At most make 240 request every minute.

class Job extends events.EventEmitter {
constructor(auth, query, from, to, timeZone) {
Expand Down Expand Up @@ -35,7 +38,7 @@ class Job extends events.EventEmitter {
body: JSON.stringify({ query, from, to, timeZone })
}, this.options);

http.post('https://api.sumologic.com/api/v1/search/jobs', options)
this.throttleReq(http.post('https://api.sumologic.com/api/v1/search/jobs', options))
.then((response) => {
this.searchJobId = response.headers.location;
this.options.headers.cookie = response.headers['set-cookie'];
Expand All @@ -56,6 +59,10 @@ class Job extends events.EventEmitter {
});
}

throttleReq(req) {
return new Promise(resolve => { throttle(() => { resolve(req) }); });
}

onceCreated() {
if (this.searchJobId) return Promise.resolve();
return new Promise((resolve) => this.once('created', () => setTimeout(resolve, 1000)));
Expand Down Expand Up @@ -96,7 +103,7 @@ class Job extends events.EventEmitter {
attempts++;

return this.onceCreated()
.then(() => http.get(this.searchJobId, this.options))
.then(() => this.throttleReq(http.get(this.searchJobId, this.options)))
.then((response) => Object.assign(this.status, response.body))
.then((status) => {
if (status.messageCount > 0) this.emit('messages');
Expand All @@ -117,7 +124,7 @@ class Job extends events.EventEmitter {
attempts++;

return this.waitForResults(type)
.then(() => http.get(url, this.options))
.then(() => this.throttleReq(http.get(url, this.options)))
.then((response) => {
this[`${type}Fields`] = response.body.fields;
this[`${type}Offset`] = this[`${type}Offset`] + response.body[`${type}s`].length;
Expand Down
Loading