Package detail

cluster-client

node-modules103.6kMIT3.7.0

Sharing Connection among Multi-Process Nodejs

cluster, multi-process

readme

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

  2. Only provider data API, interact with server and maintain persistent connections etc.

  3. No need to concern cluster issue

  4. APIClient

  5. Using cluster-client to wrap DataClient

  6. 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.

changelog

Changelog

3.7.0 (2024-05-25)

Features

  • use egg-logger@3, sdk-base@4, utility@2 (#67) (71dff9a)

3.6.0 (2024-01-24)

Features

  • set ClusterServer default maximum listeners up to 20 (#66) (384b7b4)

3.5.0 (2023-08-30)

Features

3.4.1 (2023-06-20)

Bug Fixes

  • avoid serialize-json encoder error (#63) (73c44d2)

3.4.0 (2023-01-11)

Features

  • throw error when create server port is missing (#62) (eb890c3)

3.3.3 (2023-01-10)

Bug Fixes

3.3.2 (2022-12-17)

Bug Fixes


3.3.1 / 2022-11-23

fixes

3.3.0 / 2022-11-14

features

3.2.0 / 2022-10-18

features

3.1.1 / 2022-06-22

fixes

  • [f4cc11b] - fix: subscribe is not working on single thread mode (#51) (钟典 Desmond <z@limme.net>)

3.1.0 / 2021-11-21

features

3.0.1 / 2019-03-01

fixes

3.0.0 / 2019-02-26

features

2.1.2 / 2018-11-23

others

2.1.1 / 2018-06-12

fixes

2.1.0 / 2018-03-26

features

2.0.0 / 2018-03-06

others

1.7.1 / 2017-09-21

  • fix: error occured while calling invokeOneway method if ready failed (#33)

1.7.0 / 2017-08-18

  • feat: support custom port by env NODE_CLUSTER_CLIENT_PORT (#31)

1.6.8 / 2017-08-18

  • fix: make sure leader ready before follower in egg (#32)

1.6.7 / 2017-07-31

  • fix: only close server when server exists (#30)

1.6.6 / 2017-07-28

  • fix: set exclusive to true on listen (#29)

1.6.5 / 2017-06-24

  • fix: ignore error after close & register channel issue (#28)

1.6.4 / 2017-05-08

  • chore: remove unnecessary log, using debug instead (#27)

1.6.3 / 2017-04-25

  • fix: make sure follower test socket end (#25)

1.6.2 / 2017-04-25

  • fix: ignore ECONNRESET error (#24)

1.6.1 / 2017-04-20

  • fix: invoke before client ready issue (#23)
  • fix: fix symbol property error (#22)

1.6.0 / 2017-04-18

  • feat: make clustClient method writable to support mock or spy (#21)

1.5.4 / 2017-04-12

  • fix: avoid event memory leak warning (#20)

1.5.3 / 2017-03-17

  • fix: make sure subscribe listener triggered asynchronized (#19)

1.5.2 / 2017-03-14

  • fix: event delegate & leader ready bug (#18)

1.5.1 / 2017-03-13

  • fix: don't auto ready when initMethod exists (#17)

1.5.0 / 2017-03-10

  • feat: add APIClientBase to help you create your api client (#16)

1.4.0 / 2017-03-08

  • feat: support unSubscribe, invokeOneway & close self (#14)

1.3.2 / 2017-03-08

  • fix: fix leader subscribe issue & heartbeat timeout issue (#15)

1.3.1 / 2017-03-07

  • chore: better notice (#13)
  • test: fix failed case (#12)

1.3.0 / 2017-02-22

  • fix: block all remote connection (#11)

1.2.0 / 2017-02-20

  • feat: use serialize-json to support encode/decode buffer, date, undef… (#10)

1.1.0 / 2017-02-07

  • feat: close (#7)
  • fix: no more need harmony-reflect on node >= 6 (#8)
  • refactor: improve utils.delegateEvents() (#6)

1.0.3 / 2017-02-04

  • fix: adjust serialize algorithm for invoke arguments (#3)

1.0.2 / 2017-01-25

  • fix: log error if error exist (#5)
  • docs: fix typo subsribe -> subscribe (#4)

1.0.1 / 2016-12-26

  • fix: fix shared memory issue (#2)

1.0.0 / 2016-12-22

  • feat: implement cluster-client