Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
satazor committed May 27, 2013
0 parents commit 9f75762
Show file tree
Hide file tree
Showing 9 changed files with 698 additions and 0 deletions.
54 changes: 54 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so

# OS generated files #
######################
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
Desktop.ini
.Spotlight-V100
.Trashes
._*

# NetBeans #
############
nbsettings/
nbproject/
nbbuild/
nbdist/
nbactions.xml
nb-configuration.xml

# Textmate #
############
*.tmproj
*.tmproject
tmtags

# VIM #
#######
.*.sw[a-z]
*.un~
Session.vim

# Sublime TextEditor #
######################
*.sublime-project

# Eclipse #
######################
/.project
/.settings

# Node #
######################
node_modules
npm-debug.*
63 changes: 63 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"predef": [
"console",
"require",
"define",
"describe",
"it",
"before",
"beforEach",
"after",
"afterEach"
],

"node": true,
"devel": true,

"bitwise": true,
"curly": true,
"eqeqeq": true,
"forin": false,
"immed": true,
"latedef": false,
"newcap": true,
"noarg": true,
"noempty": false,
"nonew": true,
"plusplus": false,
"regexp": true,
"undef": true,
"unused": true,
"quotmark": "single",
"strict": true,
"trailing": true,

"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"es5": false,
"esnext": false,
"evil": false,
"expr": false,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": false,
"laxcomma": false,
"loopfunc": true,
"multistr": false,
"onecase": true,
"regexdash": false,
"scripturl": false,
"smarttabs": false,
"shadow": false,
"sub": false,
"supernew": false,
"validthis": false,

"nomen": false,
"onevar": false,
"white": true
}
4 changes: 4 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
language: node_js
node_js:
- "0.10"
- "0.8"
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2012 IndigoUnited

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
86 changes: 86 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# p-throttler
---

[![Build Status](https://secure.travis-ci.org/IndigoUnited/node-p-throttler.png)](http://travis-ci.org/IndigoUnited/node-p-throttler.png)

A promise based throttler responsible for limiting execution of parallel tasks.
The number of parallel tasks may be limited and configured per type.


## Installation

`$ npm install p-throttler`


## API

### #create(defaultConcurrency, types)

Constructs a new throttler.

The `defaultConcurrency` is the default maximum concurrent functions being run (-1 to specify no limits).
The `types` allows you to specify different concurrencies for different types.

Example:

```js
var throttler = PThrottler.create(15, { // or new PThrottler()
'network_io': 10,
'disk_io': 50
});
```


### .enqueue(func, [type]): Promise

Enqueues a function to be ran. The function is expected to return a promise or a value.
The returned promise is resolved when the function finishes execution.

The `type` argument is optional and can be a `string` or an array of `strings`.
Use it to specify the type(s) associated with the function.

The function will run as soon as a free slot is available for every `type`.
If no `type` is passed or is unknown, the `defaultConcurrency` is used.

The execution order is guaranteed for functions enqueued with the exact same `type` argument.

Example:

```js

var method = function () {
return Q.resolve('foo');
};

var throttler = PThrottler.create(15, {
'foo': 1,
'bar': 2
});

// Single type
throttler.enqueue(function () {
return method();
}, 'foo')
.then(function (value) {
console.log(value); // foo
});

// Multiple type
throttler.enqueue(function () {
return method();
}, ['foo', 'bar'])
.then(function (value) {
console.log(value); // foo
});


### .abort(): Promise

Aborts all current work being done.
Returns a promise that is resolved when the current running functions finish to execute.
Any function that was in the queue waiting to be ran is removed immediately.


## License

Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
153 changes: 153 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
'use strict';

var Q = require('q');
var arrayRemove = require('./lib/arrayRemove');

function PThrottler(defaultConcurrency, types) {
this._defaultConcurrency = typeof defaultConcurrency === 'number' ? defaultConcurrency : 10;

// Initialize some needed properties
this._queue = {};
this._slots = types || {};
this._executing = [];
}

// -----------------

PThrottler.prototype.enqueue = function (func, type) {
var deferred = Q.defer();
var types;
var entry;

type = type || '';
types = Array.isArray(type) ? type : [type];
entry = {
func: func,
types: types,
deferred: deferred
};

// Add the entry to all the types queues
types.forEach(function (type) {
var queue = this._queue[type] = this._queue[type] || [];
queue.push(entry);
}, this);

// Process the entry shortly later so that handlers can be attached to the returned promise
Q.fcall(this._processEntry.bind(this, entry));

return deferred.promise;
};

PThrottler.prototype.abort = function () {
var promises;

// Empty the whole queue
Object.keys(this._queue).forEach(function (type) {
this._queue[type] = [];
}, this);

// Wait for all pending functions to finish
promises = this._executing.map(function (entry) {
return entry.deferred.promise;
});

return Q.allResolved(promises)
.then(function () {}); // Resolve with no value
};

// -----------------

PThrottler.prototype._processQueue = function (type) {
var queue = this._queue[type];
var length = queue ? queue.length : 0;
var x;

for (x = 0; x < length; ++x) {
if (this._processEntry(queue[x])) {
break;
}
}
};

PThrottler.prototype._processEntry = function (entry) {
var allFree = entry.types.every(this._hasSlot, this);
var promise;

// If there is a free slot for every type
if (allFree) {
// For each type
entry.types.forEach(function (type) {
// Remove entry from the queue
arrayRemove(this._queue[type], entry);
// Take slot
this._takeSlot(type);
}, this);

// Execute the function
this._executing.push(entry);
promise = entry.func();
if (typeof promise.then === 'undefined') {
promise = Q.resolve(promise);
}

promise.then(
this._onResolve.bind(this, entry, true),
this._onResolve.bind(this, entry, false)
);
}

return allFree;
};


PThrottler.prototype._onResolve = function (entry, ok, result) {
// Resolve/reject the deferred based on success/error of the promise
if (ok) {
entry.deferred.resolve(result);
} else {
entry.deferred.reject(result);
}

// Remove it from the executing list
arrayRemove(this._executing, entry);

// Free up slots for every type
entry.types.forEach(this._freeSlot, this);

// Find candidates for the free slots of each type
entry.types.forEach(this._processQueue, this);
};

PThrottler.prototype._hasSlot = function (type) {
var freeSlots = this._slots[type];

if (freeSlots == null) {
freeSlots = this._defaultConcurrency;
}

return freeSlots > 0;
};

PThrottler.prototype._takeSlot = function (type) {
if (this._slots[type] == null) {
this._slots[type] = this._defaultConcurrency;
} else if (!this._slots[type]) {
throw new Error('No free slots');
}

// Decrement the free slots
--this._slots[type];
};

PThrottler.prototype._freeSlot = function (type) {
if (this._slots[type] != null) {
++this._slots[type];
}
};

PThrottler.create = function (defaultConcurrency, types) {
return new PThrottler(defaultConcurrency, types);
};

module.exports = PThrottler;
Loading

0 comments on commit 9f75762

Please sign in to comment.