schangxiang@126.com
2025-09-19 0821aa23eabe557c0d9ef5dbe6989c68be35d1fe
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
'use strict';
 
const debug = require('debug')('cluster-client#follower');
const is = require('is-type-of');
const Base = require('tcp-base');
const Packet = require('./protocol/packet');
const Request = require('./protocol/request');
const Response = require('./protocol/response');
 
class Follower extends Base {
  /**
   * "Fake" Client, forward request to leader
   *
   * @param {Object} options
   *  - {Number} port - the port
   *  - {Map} descriptors - interface descriptors
   *  - {Transcode} transcode - serialze / deserialze methods
   *  - {Number} responseTimeout - the timeout
   * @constructor
   */
  constructor(options) {
    // local address
    options.host = '127.0.0.1';
    super(options);
    this._publishMethodName = this._findMethodName('publish');
    this._subInfo = new Set();
    this._subData = new Map();
    this._transcode = options.transcode;
    this._closeByUser = false;
 
    this.on('request', req => this._handleRequest(req));
    // avoid warning message
    this.setMaxListeners(100);
  }
  get isLeader() {
    return false;
  }
 
  get logger() {
    return this.options.logger;
  }
 
  get heartBeatPacket() {
    const heartbeat = new Request({
      connObj: {
        type: 'heartbeat',
      },
      timeout: this.options.responseTimeout,
    });
    return heartbeat.encode();
  }
 
  getHeader() {
    return this.read(24);
  }
 
  getBodyLength(header) {
    return header.readInt32BE(16) + header.readInt32BE(20);
  }
 
  close(err) {
    this._closeByUser = true;
    return super.close(err);
  }
 
  decode(body, header) {
    const buf = Buffer.concat([ header, body ]);
    const packet = Packet.decode(buf);
    const connObj = packet.connObj;
    if (connObj && connObj.type === 'invoke_result') {
      let data;
      if (packet.data) {
        data = this.options.transcode.decode(packet.data);
      }
      if (connObj.success) {
        return {
          id: packet.id,
          isResponse: packet.isResponse,
          data,
        };
      }
      const error = new Error(data.message);
      Object.assign(error, data);
      return {
        id: packet.id,
        isResponse: packet.isResponse,
        error,
      };
    }
    return {
      id: packet.id,
      isResponse: packet.isResponse,
      connObj: packet.connObj,
      data: packet.data,
    };
  }
 
  send(...args) {
    // just ignore after close
    if (this._closeByUser) {
      return;
    }
    return super.send(...args);
  }
 
  formatKey(reg) {
    return '$$inner$$__' + this.options.formatKey(reg);
  }
 
  subscribe(reg, listener) {
    const key = this.formatKey(reg);
    this.on(key, listener);
 
    // no need duplicate subscribe
    if (!this._subInfo.has(key)) {
      debug('[Follower:%s] subscribe %j for first time', this.options.name, reg);
      const req = new Request({
        connObj: { type: 'subscribe', key, reg },
        timeout: this.options.responseTimeout,
      });
 
      // send subscription
      this.send({
        id: req.id,
        oneway: true,
        data: req.encode(),
      });
      this._subInfo.add(key);
    } else if (this._subData.has(key)) {
      debug('[Follower:%s] subscribe %j', this.options.name, reg);
      process.nextTick(() => {
        listener(this._subData.get(key));
      });
    }
    return this;
  }
 
  unSubscribe(reg, listener) {
    const key = this.formatKey(reg);
    if (listener) {
      this.removeListener(key, listener);
    } else {
      this.removeAllListeners(key);
    }
    if (this.listeners(key).length === 0) {
      debug('[Follower:%s] no more subscriber for %j, send unSubscribe req to leader', this.options.name, reg);
      this._subInfo.delete(key);
 
      const req = new Request({
        connObj: { type: 'unSubscribe', key, reg },
        timeout: this.options.responseTimeout,
      });
      // send subscription
      this.send({
        id: req.id,
        oneway: true,
        data: req.encode(),
      });
    }
  }
 
  publish(reg) {
    this.invoke(this._publishMethodName, [ reg ]);
    return this;
  }
 
  invoke(method, args, callback) {
    const oneway = !is.function(callback); // if no callback, means oneway
    const argLength = args.length;
    let data;
    // data:
    // +-----+---------------+-----+---------------+
    // | len |   arg1 body   | len |   arg2 body   |  ...
    // +-----+---------------+-----+---------------+
    if (argLength > 0) {
      let argsBufLength = 0;
      const arr = [];
      for (const arg of args) {
        const argBuf = this._transcode.encode(arg);
        const len = argBuf.length;
        const buf = Buffer.alloc(4 + len);
        buf.writeInt32BE(len, 0);
        argBuf.copy(buf, 4, 0, len);
        arr.push(buf);
        argsBufLength += (len + 4);
      }
      data = Buffer.concat(arr, argsBufLength);
    }
    const req = new Request({
      connObj: {
        type: 'invoke',
        method,
        argLength,
        oneway,
      },
      data,
      timeout: this.options.responseTimeout,
    });
    // send invoke request
    this.send({
      id: req.id,
      oneway,
      data: req.encode(),
    }, callback);
  }
 
  _registerChannel() {
    const req = new Request({
      connObj: {
        type: 'register_channel',
        channelName: this.options.name,
      },
      timeout: this.options.responseTimeout,
    });
    // send invoke request
    this.send({
      id: req.id,
      oneway: false,
      data: req.encode(),
    }, (err, data) => {
      if (err) {
        // if socket alive, do retry
        if (this._socket) {
          err.message = `register to channel: ${this.options.name} failed, will retry after 3s, ${err.message}`;
          this.logger.warn(err);
          // if exception, retry after 3s
          setTimeout(() => this._registerChannel(), 3000);
        } else {
          this.ready(err);
        }
        return;
      }
      const res = this._transcode.decode(data);
      if (res.success) {
        debug('[Follower:%s] register to channel: %s success', this.options.name, this.options.name);
        this.ready(true);
      } else {
        const error = new Error(res.error.message);
        Object.assign(error, res.error);
        this.ready(error);
      }
    });
  }
 
  _findMethodName(type) {
    for (const method of this.options.descriptors.keys()) {
      const descriptor = this.options.descriptors.get(method);
      if (descriptor.type === 'delegate' && descriptor.to === type) {
        return method;
      }
    }
    return null;
  }
 
  _handleRequest(req) {
    debug('[Follower:%s] receive req: %j from leader', this.options.name, req);
    const connObj = req.connObj || {};
    if (connObj.type === 'subscribe_result') {
      const result = this._transcode.decode(req.data);
      this.emit(connObj.key, result);
      this._subData.set(connObj.key, result);
      // feedback
      const res = new Response({
        id: req.id,
        timeout: req.timeout,
        connObj: { type: 'subscribe_result_res' },
      });
      this.send({
        id: req.id,
        oneway: true,
        data: res.encode(),
      });
    }
  }
 
  _connect(done) {
    if (!done) {
      done = err => {
        if (err) {
          this.ready(err);
        } else {
          // register to proper channel, difference type of client into difference channel
          this._registerChannel();
        }
      };
    }
    super._connect(done);
  }
}
 
module.exports = Follower;