• Stars
    star
    320
  • Rank 131,126 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Async call limit

Bagpipe

You are the bagpiper.

Introduction

It is convenient for us to use asynchrony or concurrency to promote our business speed in Node. However, if the amount of concurrency is too large, our server may not support it, and we'll need to limit its amount. The HTTP module contains http.Agent to control the amount of sockets our asynchronous API has packaged (usually) in advance. It is not realistic to change the inner API agent; let’s realize it on our own logical layer.

Installation

$ npm install bagpipe

API

The APIs exposed by Bagpipe only include constructor and instance methods push.

Under original status, we may execute concurrent calls like this, forming 100 concurrent asynchronous invokes:

for (var i = 0; i < 100; i++) {
  async(function () {
    // Asynchronous call
  });
}

If need to limit concurrency, what is your solution?

Solution from Bagpipe:

var Bagpipe = require('bagpipe');
// Sets the max concurrency as 10
var bagpipe = new Bagpipe(10);
for (var i = 0; i < 100; i++) {
  bagpipe.push(async, function () {
    // execute asynchronous callback
  });
}

Yes. The invoke method only splits method, parameter and callback, then delivers it to bagpipe through push.

How does Bagpipe compare with your anticipated solution?

Options

  • refuse, when queue is fulled, bagpipe will refuse the new async call and execute the callback with a TooMuchAsyncCallError exception. default false.
  • timeout, setting global ansyn call timeout. If async call doesn't complete in time, will execute the callback with BagpipeTimeoutError exception. default null.

Principles

Bagpipe delivers invoke into inner queue through push. If active invoke amount is less than max concurrent, it will be popped and executed directly, or it will stay in the queue. When an asynchronous invoke ends, a invoke in the head of the queue will be popped and executed, such that assures active asynchronous invoke amount no larger than restricted value.

When the queue length is larger than 1, Bagpipe object will fire its full event, which delivers the queue length value. The value helps to assess business performance. For example:

bagpipe.on('full', function (length) {
  console.warn(`Button system cannot deal on time, queue jam, current queue length is: ${length}`);
});

If queue length more than limit, you can set the refuse option to decide continue in queue or refuse call. The refuse default false. If set as true, the TooMuchAsyncCallError exception will pass to callback directly:

var bagpipe = new BagPipe(10, {
  refuse: true
});

If complete the async call is unexpected, the queue will not balanced. Set the timeout, let the callback executed with the BagpipeTimeoutError exception:

var bagpipe = new BagPipe(10, {
  timeout: 1000
});

Module status

The unit testing status: Build Status.

Best Practices

  • Ensure that the last parameter of the asynchronous invoke is callback.
  • Listen to the full event, adding your business performance assessment.
  • Current asynchronous method has not supported context yet. Ensure that there is no this reference in asynchronous method. If there is this reference in asynchronous method, please use bind pass into correct context.
  • Asynchronous invoke should process method to deal with timeout, it should ensure the invoke will return in a certain time no matter whether the business has been finished or not.

Real case

When you want to traverse file directories, asynchrony can ensure full use of IO. You can invoke thousands of file reading easily. But, system file descriptors are limited. If disobedient, read this article again when occurring errors as follows.

Error: EMFILE, too many open files

Someone may consider dealing it with synchronous method. But, when synchronous, CPU and IO cannot be used concurrently, performance is an indefeasible index under certain condition. You can enjoy concurrent easily, as well as limit concurrent with Bagpipe.

var bagpipe = new Bagpipe(10);

var files = ['Here are many files'];
for (var i = 0; i < files.length; i++) {
  // fs.readFile(files[i], 'utf-8', function (err, data) {
  bagpipe.push(fs.readFile, files[i], 'utf-8', function (err, data) {
    // won’t occur error because of too many file descriptors
    // well done
  });
}

License

Released under the license of MIT, welcome to enjoy open source.

More Repositories

1

fks

前端技能汇总 Frontend Knowledge Structure
JavaScript
17,918
star
2

eventproxy

An implementation of task/event based asynchronous pattern.
JavaScript
2,965
star
3

anywhere

Running static file server anywhere / 随启随用的静态文件服务器
JavaScript
981
star
4

doxmate

文档伴侣
CSS
829
star
5

diveintonode_examples

《深入浅出Node.js》的相关代码
JavaScript
418
star
6

ping

一个您会喜欢的基于Node的Web开发框架。【学习研究所用,请勿用于生产环境】
JavaScript
387
star
7

loader

Assets loader.
JavaScript
137
star
8

api-doc-service

Node API Documentation Service
JavaScript
126
star
9

bufferhelper

Concat buffer correctly and easily.
JavaScript
122
star
10

drama

Mobile Web App startup framework/前身为V5
JavaScript
98
star
11

shenjs

深JS上的分享《Node Profiler》
JavaScript
69
star
12

jsconfcn2016

JavaScript
67
star
13

compiler

《编译原理》一书一个简单的语法制导翻译器(JavaScript版本)
JavaScript
55
star
14

ghost

Node Front-end automation test framework
JavaScript
54
star
15

httpx

http(s) module with power.
JavaScript
46
star
16

unittesting

单元测试示例模块
JavaScript
40
star
17

stone-lang

《两周自制脚本语言》学习
Java
36
star
18

para

Parallel README
JavaScript
32
star
19

diveintonode_figures

《深入浅出Node.js》书稿配图
28
star
20

using_list

What companies are using Node.js in China
28
star
21

vue2js

Compile a .vue file to .js file
JavaScript
26
star
22

dependparser

自动分析项目中的依赖项
JavaScript
25
star
23

jacksontian.github.com

My homepage http://html5ify.com
CSS
24
star
24

modulelint

modulelint检测您的模块是否优秀
JavaScript
23
star
25

markbook

用Markdown写书。
CSS
22
star
26

o_o

(o_o):HTTP/HTTPS代理工具
JavaScript
22
star
27

loader-builder

Loader's builder
JavaScript
22
star
28

limitablemap

The limitable map, for avoid memory leak issue.
JavaScript
21
star
29

boolex

Bool Expression
JavaScript
21
star
30

kimi

The Node.js client and CLI for Moonshot AI(Kimi).
JavaScript
20
star
31

diveintonode_site

《深入浅出Node.js》书稿配套网站
18
star
32

slidemate

JavaScript
17
star
33

node_ci

A NodeJS MVC Framework (Like CodeIgniter).
JavaScript
15
star
34

ipod

ipod
JavaScript
15
star
35

sync_package

Sync NPM package from remote registry to local.
JavaScript
14
star
36

itodo

TODO list
JavaScript
14
star
37

plusplus

I need a better Underscore in Node.js
JavaScript
13
star
38

re-captcha

recaptcha验证码中间件
JavaScript
13
star
39

doxco

Documentation generator, docco for dox
CSS
13
star
40

waterfall

See Demo http://jacksontian.github.com/waterfall/
JavaScript
12
star
41

nounou

Node.js process deamon.
JavaScript
12
star
42

spritemate

Sprite Mate
JavaScript
12
star
43

tensorflow-node

JavaScript
10
star
44

fawave_mobile

JavaScript
10
star
45

kitx

A Node.js toolkit.
JavaScript
10
star
46

memeda

JavaScript
9
star
47

leakchecker

A tool for check the memory leak.
JavaScript
9
star
48

jsconfcn2017

8
star
49

gesture

触屏手势库,基于Winter和Zepto.js完成
JavaScript
8
star
50

nodejsctl

Shell
8
star
51

yixin

易信公众平台SDK(Node)。请右转使用微信模块:
8
star
52

dingbot

DingTalk Group Bot for Node.js
JavaScript
8
star
53

landscape

Tiny front-end framework.
JavaScript
7
star
54

eventbase

EventBase
JavaScript
7
star
55

hitaxi

我要叫车 [我要车-乘客][我有空-司机]
JavaScript
7
star
56

ebnf-parser

JavaScript
6
star
57

v

可视化资料库
5
star
58

hookx

Hook(x) with Power.
JavaScript
5
star
59

nakupenda

Learning OS
C
5
star
60

loader-connect

Loader middleware for connect
JavaScript
5
star
61

pool

Pool Stream
JavaScript
5
star
62

forward

Forward request
JavaScript
5
star
63

iquery

select('*').from('table').where('1 = 1').groupBy('column').orderBy('count DESC').limit(0, 100)
JavaScript
5
star
64

skyline

JavaScript
5
star
65

_footprint

A JavaScript template
JavaScript
4
star
66

context-ex

Context Expression
JavaScript
4
star
67

alpha

Node API search
JavaScript
4
star
68

mah-jong

JavaScript
4
star
69

JacksonTian

3
star
70

protobuf2

JavaScript
3
star
71

writing

Press markdown
CSS
3
star
72

v5_weibo

JavaScript
3
star
73

iwalk

Walk dictionary
JavaScript
3
star
74

V5UI

UI widget library
JavaScript
3
star
75

loader-koa

Loader for Koa
JavaScript
3
star
76

streamx

Ultimate stream for ES6
JavaScript
3
star
77

gyp_mirror

Python
3
star
78

readx

Read stream like sync call
JavaScript
3
star
79

rtf-parser

Rich Text Format
3
star
80

tinywork

Just do a little tiny work for Promises
JavaScript
3
star
81

gocov

A better test coverage reporter than go tool cover.
JavaScript
3
star
82

panel

一个可以替代iScroll的面板
JavaScript
2
star
83

Understanding-Computation

《计算的本质》学习
JavaScript
2
star
84

elemento

WebComponent
JavaScript
2
star
85

suncity

LBS App. Build with NodeJS & MongoDB. Named as SunCity.
JavaScript
2
star
86

math_for_kids

数学学习小项目。
HTML
2
star
87

cpu_alert

高 CPU 占用进程告警器
JavaScript
2
star
88

node-webdav-client

CalDAV client
JavaScript
2
star
89

gogo

HTML
2
star
90

footprint

A very very small logger.
JavaScript
2
star
91

columnpress

Markdown blog
Smarty
2
star
92

tallybook

我的记账本应用
JavaScript
2
star
93

user-agent

User Agent String for mock client
JavaScript
2
star
94

tiny-function

JavaScript
2
star
95

julia-set

JavaScript
1
star
96

doxmategen_site

Used host doxmate documents
HTML
1
star
97

koa-forward

forward for koa
JavaScript
1
star
98

arch_mate

JavaScript
1
star
99

little.js

http://www.crockford.com/javascript/little.html
JavaScript
1
star
100

super-init-myegg

JavaScript
1
star