schangxiang@126.com
2025-09-18 49a51c068d62084bc4c3e77c4be94a20de556c4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
'use strict';
 
const co = require('co');
const Base = require('./base');
const is = require('is-type-of');
const utils = require('../utils');
const SdkBase = require('sdk-base');
const random = require('utility').random;
 
// Symbol
const {
  logger,
  createClient,
  singleMode,
} = require('../symbol');
const _instances = new Map();
 
class InnerClient extends SdkBase {
  constructor(options = {}) {
    super(options);
 
    this._subData = new Map(); // <key, data>
    this._subSet = new Set();
    this._subListeners = new Map(); // <key, Array<Function>>
    this._transcode = options.transcode;
    this._realClient = options.createRealClient();
    this._closeMethodName = utils.findMethodName(options.descriptors, 'close');
    this._subscribeMethodName = utils.findMethodName(options.descriptors, 'subscribe');
    this._publishMethodName = utils.findMethodName(options.descriptors, 'publish');
    this._isReady = false;
    this._closeByUser = false;
    this._refCount = 1;
 
    // event delegate
    utils.delegateEvents(this._realClient, this);
 
    if (is.function(this._realClient.ready)) {
      this._realClient.ready(err => {
        if (err) {
          this.ready(err);
        } else {
          this._isReady = true;
          this.ready(true);
        }
      });
    } else {
      this._isReady = true;
      this.ready(true);
    }
  }
 
  ref() {
    this._refCount++;
  }
 
  get isLeader() {
    return true;
  }
 
  formatKey(reg) {
    return '$$inner$$__' + this.options.formatKey(reg);
  }
 
  subscribe(reg, listener) {
    const key = this.formatKey(reg);
    const transcode = this._transcode;
    const isBroadcast = this.options.isBroadcast;
 
    const listeners = this._subListeners.get(key) || [];
    listeners.push(listener);
    this._subListeners.set(key, listeners);
 
    if (!this._subSet.has(key)) {
      this._subSet.add(key);
      this._realClient[this._subscribeMethodName](reg, result => {
        const data = transcode.encode(result);
        this._subData.set(key, data);
 
        let fns = this._subListeners.get(key);
        if (!fns) {
          return;
        }
 
        const len = fns.length;
        // if isBroadcast equal to false, random pick one to notify
        if (!isBroadcast) {
          fns = [ fns[random(len)] ];
        }
 
        for (const fn of fns) {
          fn(transcode.decode(data));
        }
      });
    } else if (this._subData.has(key) && isBroadcast) {
      process.nextTick(() => {
        const data = this._subData.get(key);
        listener(transcode.decode(data));
      });
    }
  }
 
  unSubscribe(reg, listener) {
    const key = this.formatKey(reg);
 
    if (!listener) {
      this._subListeners.delete(key);
    } else {
      const listeners = this._subListeners.get(key) || [];
      const newListeners = [];
 
      for (const fn of listeners) {
        if (fn === listener) {
          continue;
        }
        newListeners.push(fn);
      }
      this._subListeners.set(key, newListeners);
    }
  }
 
  publish(reg) {
    this._realClient[this._publishMethodName](reg);
  }
 
  invoke(methodName, args, callback) {
    let method = this._realClient[methodName];
    // compatible with generatorFunction
    if (is.generatorFunction(method)) {
      method = co.wrap(method);
    }
    args.push(callback);
    const ret = method.apply(this._realClient, args);
    if (callback && is.promise(ret)) {
      ret.then(result => callback(null, result), err => callback(err))
        // to avoid uncaught exception in callback function, then cause unhandledRejection
        .catch(err => { this._errorHandler(err); });
    }
  }
 
  // emit error asynchronously
  _errorHandler(err) {
    setImmediate(() => {
      if (!this._closeByUser) {
        this.emit('error', err);
      }
    });
  }
 
  async close() {
    if (this._refCount > 0) {
      this._refCount--;
    }
    if (this._refCount > 0) return;
 
    this._closeByUser = true;
 
    if (this._realClient) {
      if (this._closeMethodName) {
        // support common function, generatorFunction, and function returning a promise
        await utils.callFn(this._realClient[this._closeMethodName].bind(this._realClient));
      }
    }
    this.emit('close');
  }
}
 
 
class SingleClient extends Base {
  get [singleMode]() {
    return true;
  }
 
  async [createClient]() {
    const options = this.options;
    let client;
    if (_instances.has(options.name)) {
      client = _instances.get(options.name);
      client.ref();
      return client;
    }
    client = new InnerClient(options);
    client.once('close', () => {
      _instances.delete(options.name);
      this[logger].info('[cluster#SingleClient] %s is closed.', options.name);
    });
    _instances.set(options.name, client);
    return client;
  }
}
 
module.exports = SingleClient;