• Stars
    star
    131
  • Rank 270,290 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 month ago

Reviews

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

Repository Details

Sharing Connection among Multi-Process Nodejs

cluster-client

Sharing Connection among Multi-Process Nodejs

NPM version CI Test coverage Known Vulnerabilities npm download

As we know, each Node.js process runs in a single thread. Usually, we split a single process into multiple processes to take advantage of multi-core systems. On the other hand, it brings more system overhead, sush as maintaining more TCP connections between servers.

This module is designed to share connections among multi-process Nodejs.

Theory

  • Inspired by Leader/Follower pattern.
  • Allow ONLY one process "the Leader" to communicate with server. Other processes "the Followers" act as "Proxy" client, and forward all requests to Leader.
  • The Leader is selected by "Port Competition". Every process try to listen on a certain port (for example 7777), but ONLY one can occupy the port, then it becomes the Leader, the others become Followers.
  • TCP socket connections are maintained between Leader and Followers. And I design a simple communication protocol to exchange data between them.
  • If old Leader dies, one of processes will be selected as the new Leader.

Diagram

normal (without using cluster client)

+--------+   +--------+
| Client |   | Client |   ...
+--------+   +--------+
    |  \     /   |
    |    \ /     |
    |    / \     |
    |  /     \   |
+--------+   +--------+
| Server |   | Server |   ...
+--------+   +--------+

using cluster-client

             +-------+
             | start |
             +---+---+
                 |
        +--------+---------+
      __| port competition |__
win /   +------------------+  \ lose
   /                           \
+--------+     tcp conn     +----------+
| Leader |<---------------->| Follower |
+--------+                  +----------+
    |
+--------+
| Client |
+--------+
    |  \
    |    \
    |      \
    |        \
+--------+   +--------+
| Server |   | Server |   ...
+--------+   +--------+

Protocol

  • Packet structure
 0       1       2               4                                                              12
 +-------+-------+---------------+---------------------------------------------------------------+
 |version|req/res|    reserved   |                          request id                           |
 +-------------------------------+-------------------------------+-------------------------------+
 |           timeout             |   connection object length    |   application object length   |
 +-------------------------------+---------------------------------------------------------------+
 |         conn object (JSON format)  ...                    |            app object             |
 +-----------------------------------------------------------+                                   |
 |                                          ...                                                  |
 +-----------------------------------------------------------------------------------------------+
  • Protocol Type
    • Register Channel
    • Subscribe/Publish
    • Invoke
  • Sequence diagram
 +----------+             +---------------+          +---------+
 | Follower |             |  local server |          |  Leader |
 +----------+             +---------------+          +---------+
      |     register channel     |       assign to        |
      + -----------------------> |  --------------------> |
      |                          |                        |
      |                                subscribe          |
      + ------------------------------------------------> |
      |       subscribe result                            |
      | <------------------------------------------------ +
      |                                                   |
      |                                 invoke            |
      + ------------------------------------------------> |
      |          invoke result                            |
      | <------------------------------------------------ +
      |                                                   |

Install

npm install cluster-client --save

Node.js >= 6.0.0 required

Usage

'use strict';

const co = require('co');
const Base = require('sdk-base');
const cluster = require('cluster-client');

/**
 * Client Example
 */
class YourClient extends Base {
  constructor(options) {
    super(options);

    this.options = options;
    this.ready(true);
  }

  subscribe(reg, listener) {
    // subscribe logic
  }

  publish(reg) {
    // publish logic
  }

  * getData(id) {
    // invoke api
  }

  getDataCallback(id, cb) {
    // ...
  }

  getDataPromise(id) {
    // ...
  }
}

// create some client instances, but only one instance will connect to server
const client_1 = cluster(YourClient)
  .delegate('getData')
  .delegate('getDataCallback')
  .delegate('getDataPromise')
  .create({ foo: 'bar' });
const client_2 = cluster(YourClient)
  .delegate('getData')
  .delegate('getDataCallback')
  .delegate('getDataPromise')
  .create({ foo: 'bar' });
const client_3 = cluster(YourClient)
  .delegate('getData')
  .delegate('getDataCallback')
  .delegate('getDataPromise')
  .create({ foo: 'bar' });

// subscribe information
client_1.subscribe('some thing', result => console.log(result));
client_2.subscribe('some thing', result => console.log(result));
client_3.subscribe('some thing', result => console.log(result));

// publish data
client_2.publish('some data');

// invoke method
client_3.getDataCallback('some thing', (err, val) => console.log(val));
client_2.getDataPromise('some thing').then(val => console.log(val));

co(function*() {
  const ret = yield client_1.getData('some thing');
  console.log(ret);
}).catch(err => console.error(err));

API

  • delegate(from, to): create delegate method, from is the method name your want to create, and to have 6 possible values: [ subscribe, unSubscribe, publish, invoke, invokeOneway, close ], and the default value is invoke
  • override(name, value): override one property
  • create(…) create the client instance
  • close(client) close the client
  • APIClientBase a base class to help you create your api client

Best Practice

  1. DataClient
  • Only provider data API, interact with server and maintain persistent connections etc.
  • No need to concern cluster issue
  1. APIClient
  • Using cluster-client to wrap DataClient
  • Put your bussiness logic here

DataClient

const Base = require('sdk-base');

class DataClient extends Base {
  constructor(options) {
    super(options);
    this.ready(true);
  }

  subscribe(info, listener) {
    // subscribe data from server
  }

  publish(info) {
    // publish data to server
  }

  * getData(id) {
    // asynchronous API
  }
}

APIClient

const DataClient = require('./your-data-client');
const { APIClientBase } = require('cluster-client');

class APIClient extends APIClientBase {
  constructor(options) {
    super(options);
    this._cache = new Map();
  }
  get DataClient() {
    return DataClient;
  }
  get delegates() {
    return {
      getData: 'invoke',
    };
  }
  get clusterOptions() {
    return {
      name: 'MyClient',
    };
  }
  subscribe(...args) {
    return this._client.subscribe(...args);
  }
  publish(...args) {
    return this._client.publish(...args);
  }
  * getData(id) {
    // write your business logic & use data client API
    if (this._cache.has(id)) {
      return this._cache.get(id);
    }
    const data = yield this._client.getData(id);
    this._cache.set(id, data);
    return datal
  }
}
|------------------------------------------------|
| APIClient                                      |
|       |----------------------------------------|
|       | ClusterClient                          |
|       |      |---------------------------------|
|       |      | DataClient                      |
|-------|------|---------------------------------|

For more information, you can refer to the discussion

MIT

Contributors


gxcsoccer


fengmk2


shaoshuai0102


killagu


semantic-release-bot


atian25


leoner


mansonchor


sinkhaha


limitMe

This project follows the git-contributor spec, auto updated at Tue Jun 20 2023 12:29:14 GMT+0800.

More Repositories

1

utility

A collection of useful utilities.
TypeScript
1,239
star
2

parameter

A parameter verify tools.
JavaScript
727
star
3

urllib

Request HTTP(s) URLs in a complex world.
TypeScript
725
star
4

agentkeepalive

Support keepalive http agent.
JavaScript
571
star
5

emoji

emoji: This library allows the handling and conversion of Emoji in Javascript.
HTML
502
star
6

weibo

weibo nodejs sdk
JavaScript
489
star
7

compressing

Everything you need for compressing and uncompressing
JavaScript
424
star
8

detect-port

Node.js module to detect available ports of the system.
JavaScript
376
star
9

qn

Another qiniu http://docs.qiniu.com/api/ API client for Node.js.
JavaScript
274
star
10

graceful

Graceful exit when `uncaughtException` emit, base on `process.on('uncaughtException')`.
JavaScript
249
star
11

address

Get current machine IP and MAC address.
TypeScript
228
star
12

autod

Auto generate dependencies and devDependencies by parse the project file.
JavaScript
205
star
13

js-to-java

easy way to wrap js object to java object
JavaScript
201
star
14

common-bin

Abstraction bin tool
JavaScript
189
star
15

hessian.js

js hessian binary web service protocol, support communicate with java
JavaScript
183
star
16

mm

An simple but flexible mock(or say stub) package, mock mate
JavaScript
158
star
17

cfork

cluster fork and restart easy way
JavaScript
156
star
18

formstream

multipart/form-data encoded stream, helper for file upload.
JavaScript
145
star
19

urlencode

encodeURIComponent with charset
TypeScript
142
star
20

webcamera

网鑡ζˆͺε›Ύε·₯ε…· (by phantomjs)
JavaScript
124
star
21

is-type-of

complete type checking for node
TypeScript
122
star
22

coffee

Test command line on Node.js
JavaScript
97
star
23

clet

Command Line E2E Testing
JavaScript
76
star
24

byte

Input Buffer and Output Buffer, just like Java ByteBuffer
JavaScript
76
star
25

sdk-base

a base class for sdk with default error handler
JavaScript
62
star
26

china-mobile-phone-regexp

The regular expressions for China mobile phone number.
JavaScript
60
star
27

mz-modules

Same as `mz`, but wrap modules in the world rather than core API.
JavaScript
56
star
28

thunkify-wrap

a more powerful thunkify
JavaScript
55
star
29

ots

This project no longer maintained, please use https://github.com/ali-sdk/ots2 instead.
JavaScript
48
star
30

urllib-sync

sync http request
JavaScript
44
star
31

stream-wormhole

Pipe ReadStream to a wormhole
TypeScript
42
star
32

copy-to

copy an object's properties to another one
JavaScript
41
star
33

optimized

Detect a function can be optimized or not.
JavaScript
41
star
34

runscript

Run script easy!
JavaScript
41
star
35

await-stream-ready

a promise waiting stream ready
JavaScript
34
star
36

charset

Get the content charset from header and html content-type.
JavaScript
34
star
37

ab

A benchmark tool.
JavaScript
33
star
38

npm-updater

Prompt update of npm package
JavaScript
32
star
39

java.io

A Node.js implement of "java.io.InputObjectStream.readObject()" and "java.io.OutputObjectStream.writeObject()"
JavaScript
31
star
40

humanize-ms

transform humanize time to ms
JavaScript
30
star
41

graceful-process

graceful exit process even parent exit on SIGKILL.
JavaScript
29
star
42

node-murmurhash

murmurhash, support utf8 Buffer
JavaScript
27
star
43

sendmessage

Send a cross process message if message channel is connected.
JavaScript
27
star
44

shameimaru

Shameimaru Aya likes to traverse node_modules and capture the tree.
JavaScript
26
star
45

ready-callback

Launch server after all async task ready
TypeScript
26
star
46

tcp-base

TCP client base
JavaScript
25
star
47

serialize-json

A serialize algorithm for JSON
JavaScript
23
star
48

js-remoting-for-apache-dubbo

dubbo protocol implement
JavaScript
22
star
49

loading

loading dir files as module to an object
JavaScript
20
star
50

zookeeper-cluster-client

Sharing one zookeeper connection among Multi-Process on Node.js
JavaScript
20
star
51

tnpm

JavaScript
19
star
52

enable

Detect es6 features enable or not.
JavaScript
19
star
53

last-commit-log

Node.js module to get the last git commit information - mostly to be used by CI/CD and building phase.
JavaScript
19
star
54

jdwp

Java Debug Wire Protocol
JavaScript
18
star
55

time-profile

Measuring execution time of functions
JavaScript
16
star
56

qps

High performance qps counter
JavaScript
15
star
57

cluster-reload

Easy and safe reload your workers.
JavaScript
14
star
58

await-first

Wait the first event in a set of event pairs, then clean up after itself.
JavaScript
14
star
59

buffer-type

Detect content-type from Buffer data.
JavaScript
14
star
60

pedding

Just pedding for callback.
JavaScript
13
star
61

should2assert

A tool to help you migrating from should to assert
JavaScript
13
star
62

save-file-atomic

Save anything to file atomic
JavaScript
13
star
63

wt

wt: Simple dir watcher, support events
JavaScript
13
star
64

zlogger

The last console logger
JavaScript
12
star
65

logfilestream

Log stream, including auto rolling feature, support multiprocess `append` write at the same time.
JavaScript
12
star
66

dns-hijacking

JavaScript
11
star
67

default-user-agent

Default user agent string for Node.js http request
JavaScript
11
star
68

jsonp-body

Helper to create more safe jsonp response body for koa and other web framework.
JavaScript
10
star
69

zookeeper-watcher

Extend node-zookeeper-client, let zookeeper client support `watch(path)` method.
JavaScript
10
star
70

weibo-mid

Convert Weibo Open API mid to base62 hash string.
JavaScript
10
star
71

connection

JavaScript
10
star
72

enums

JavaScript
9
star
73

node-homedir

Get the effective user's homedir
TypeScript
9
star
74

rid

Request Unique ID, base on current server `ip`, `process.pid` and auto increase id, like `$ip,$pid,$id`
JavaScript
9
star
75

error-formatter

format an error into string or json for log
JavaScript
8
star
76

auto-correct

auto correct for command line tools
JavaScript
8
star
77

install-node

Install node into node_modules
JavaScript
8
star
78

digest-header

Digest access authentication header helper
JavaScript
8
star
79

http-doctor

HTTP doctor
JavaScript
7
star
80

vmto

velocity(vm) to any other templates.
JavaScript
7
star
81

restful-client

RESTFul api client base object. Usually use by some api client implementation.
JavaScript
6
star
82

diskstore

a local cache implement
JavaScript
6
star
83

koa-override

method override middleware for koa
JavaScript
6
star
84

memory-tripwire

suicide when memory over the limit
JavaScript
5
star
85

urlmock

Easy load mock data from a specify url.
JavaScript
5
star
86

performance-ms

performance timer in ms
TypeScript
4
star
87

common-bin-plus

advanced common-bin for cli usage
JavaScript
4
star
88

aggregate-base

Base class for aggregate operation
JavaScript
4
star
89

watch-files

watch files by polling
JavaScript
3
star
90

oss-syncer

synchronization all files from this bucket to another bucket
JavaScript
3
star
91

common-boilerplate

base class for boilerplate
JavaScript
3
star
92

fileloader

more stable file loader for nunjucks, and support charsets like `gbk`.
JavaScript
3
star
93

assert-file

assert file utilities
JavaScript
3
star
94

changing

Watching `file`, `dir` or `link` changing, using interval timer.
JavaScript
3
star
95

speeds

Speeds controllable stream. You can control the downstream speed on your own.
JavaScript
3
star
96

cov

Mocha Coverage report store on CDN.
JavaScript
3
star
97

onelogger

The only ONE logger
TypeScript
3
star
98

sse-decoder

SSE decoder for nodejs
TypeScript
3
star
99

fast-ua-parser

A Fast JavaScript library to detect user's Browser, Engine, OS, CPU, and Device type/model
2
star
100

get-ready

NodeJS mixin to add one-time ready event
TypeScript
2
star