follower.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. 'use strict';
  2. const debug = require('debug')('cluster-client#follower');
  3. const is = require('is-type-of');
  4. const Base = require('tcp-base');
  5. const Packet = require('./protocol/packet');
  6. const Request = require('./protocol/request');
  7. const Response = require('./protocol/response');
  8. class Follower extends Base {
  9. /**
  10. * "Fake" Client, forward request to leader
  11. *
  12. * @param {Object} options
  13. * - {Number} port - the port
  14. * - {Map} descriptors - interface descriptors
  15. * - {Transcode} transcode - serialze / deserialze methods
  16. * - {Number} responseTimeout - the timeout
  17. * @constructor
  18. */
  19. constructor(options) {
  20. // local address
  21. options.host = '127.0.0.1';
  22. super(options);
  23. this._publishMethodName = this._findMethodName('publish');
  24. this._subInfo = new Set();
  25. this._subData = new Map();
  26. this._transcode = options.transcode;
  27. this._closeByUser = false;
  28. this.on('request', req => this._handleRequest(req));
  29. // avoid warning message
  30. this.setMaxListeners(100);
  31. }
  32. get isLeader() {
  33. return false;
  34. }
  35. get logger() {
  36. return this.options.logger;
  37. }
  38. get heartBeatPacket() {
  39. const heartbeat = new Request({
  40. connObj: {
  41. type: 'heartbeat',
  42. },
  43. timeout: this.options.responseTimeout,
  44. });
  45. return heartbeat.encode();
  46. }
  47. getHeader() {
  48. return this.read(24);
  49. }
  50. getBodyLength(header) {
  51. return header.readInt32BE(16) + header.readInt32BE(20);
  52. }
  53. close(err) {
  54. this._closeByUser = true;
  55. return super.close(err);
  56. }
  57. decode(body, header) {
  58. const buf = Buffer.concat([ header, body ]);
  59. const packet = Packet.decode(buf);
  60. const connObj = packet.connObj;
  61. if (connObj && connObj.type === 'invoke_result') {
  62. let data;
  63. if (packet.data) {
  64. data = this.options.transcode.decode(packet.data);
  65. }
  66. if (connObj.success) {
  67. return {
  68. id: packet.id,
  69. isResponse: packet.isResponse,
  70. data,
  71. };
  72. }
  73. const error = new Error(data.message);
  74. Object.assign(error, data);
  75. return {
  76. id: packet.id,
  77. isResponse: packet.isResponse,
  78. error,
  79. };
  80. }
  81. return {
  82. id: packet.id,
  83. isResponse: packet.isResponse,
  84. connObj: packet.connObj,
  85. data: packet.data,
  86. };
  87. }
  88. send(...args) {
  89. // just ignore after close
  90. if (this._closeByUser) {
  91. return;
  92. }
  93. return super.send(...args);
  94. }
  95. formatKey(reg) {
  96. return '$$inner$$__' + this.options.formatKey(reg);
  97. }
  98. subscribe(reg, listener) {
  99. const key = this.formatKey(reg);
  100. this.on(key, listener);
  101. // no need duplicate subscribe
  102. if (!this._subInfo.has(key)) {
  103. debug('[Follower:%s] subscribe %j for first time', this.options.name, reg);
  104. const req = new Request({
  105. connObj: { type: 'subscribe', key, reg },
  106. timeout: this.options.responseTimeout,
  107. });
  108. // send subscription
  109. this.send({
  110. id: req.id,
  111. oneway: true,
  112. data: req.encode(),
  113. });
  114. this._subInfo.add(key);
  115. } else if (this._subData.has(key)) {
  116. debug('[Follower:%s] subscribe %j', this.options.name, reg);
  117. process.nextTick(() => {
  118. listener(this._subData.get(key));
  119. });
  120. }
  121. return this;
  122. }
  123. unSubscribe(reg, listener) {
  124. const key = this.formatKey(reg);
  125. if (listener) {
  126. this.removeListener(key, listener);
  127. } else {
  128. this.removeAllListeners(key);
  129. }
  130. if (this.listeners(key).length === 0) {
  131. debug('[Follower:%s] no more subscriber for %j, send unSubscribe req to leader', this.options.name, reg);
  132. this._subInfo.delete(key);
  133. const req = new Request({
  134. connObj: { type: 'unSubscribe', key, reg },
  135. timeout: this.options.responseTimeout,
  136. });
  137. // send subscription
  138. this.send({
  139. id: req.id,
  140. oneway: true,
  141. data: req.encode(),
  142. });
  143. }
  144. }
  145. publish(reg) {
  146. this.invoke(this._publishMethodName, [ reg ]);
  147. return this;
  148. }
  149. invoke(method, args, callback) {
  150. const oneway = !is.function(callback); // if no callback, means oneway
  151. const argLength = args.length;
  152. let data;
  153. // data:
  154. // +-----+---------------+-----+---------------+
  155. // | len | arg1 body | len | arg2 body | ...
  156. // +-----+---------------+-----+---------------+
  157. if (argLength > 0) {
  158. let argsBufLength = 0;
  159. const arr = [];
  160. for (const arg of args) {
  161. const argBuf = this._transcode.encode(arg);
  162. const len = argBuf.length;
  163. const buf = Buffer.alloc(4 + len);
  164. buf.writeInt32BE(len, 0);
  165. argBuf.copy(buf, 4, 0, len);
  166. arr.push(buf);
  167. argsBufLength += (len + 4);
  168. }
  169. data = Buffer.concat(arr, argsBufLength);
  170. }
  171. const req = new Request({
  172. connObj: {
  173. type: 'invoke',
  174. method,
  175. argLength,
  176. oneway,
  177. },
  178. data,
  179. timeout: this.options.responseTimeout,
  180. });
  181. // send invoke request
  182. this.send({
  183. id: req.id,
  184. oneway,
  185. data: req.encode(),
  186. }, callback);
  187. }
  188. _registerChannel() {
  189. const req = new Request({
  190. connObj: {
  191. type: 'register_channel',
  192. channelName: this.options.name,
  193. },
  194. timeout: this.options.responseTimeout,
  195. });
  196. // send invoke request
  197. this.send({
  198. id: req.id,
  199. oneway: false,
  200. data: req.encode(),
  201. }, (err, data) => {
  202. if (err) {
  203. // if socket alive, do retry
  204. if (this._socket) {
  205. err.message = `register to channel: ${this.options.name} failed, will retry after 3s, ${err.message}`;
  206. this.logger.warn(err);
  207. // if exception, retry after 3s
  208. setTimeout(() => this._registerChannel(), 3000);
  209. } else {
  210. this.ready(err);
  211. }
  212. return;
  213. }
  214. const res = this._transcode.decode(data);
  215. if (res.success) {
  216. debug('[Follower:%s] register to channel: %s success', this.options.name, this.options.name);
  217. this.ready(true);
  218. } else {
  219. const error = new Error(res.error.message);
  220. Object.assign(error, res.error);
  221. this.ready(error);
  222. }
  223. });
  224. }
  225. _findMethodName(type) {
  226. for (const method of this.options.descriptors.keys()) {
  227. const descriptor = this.options.descriptors.get(method);
  228. if (descriptor.type === 'delegate' && descriptor.to === type) {
  229. return method;
  230. }
  231. }
  232. return null;
  233. }
  234. _handleRequest(req) {
  235. debug('[Follower:%s] receive req: %j from leader', this.options.name, req);
  236. const connObj = req.connObj || {};
  237. if (connObj.type === 'subscribe_result') {
  238. const result = this._transcode.decode(req.data);
  239. this.emit(connObj.key, result);
  240. this._subData.set(connObj.key, result);
  241. // feedback
  242. const res = new Response({
  243. id: req.id,
  244. timeout: req.timeout,
  245. connObj: { type: 'subscribe_result_res' },
  246. });
  247. this.send({
  248. id: req.id,
  249. oneway: true,
  250. data: res.encode(),
  251. });
  252. }
  253. }
  254. _connect(done) {
  255. if (!done) {
  256. done = err => {
  257. if (err) {
  258. this.ready(err);
  259. } else {
  260. // register to proper channel, difference type of client into difference channel
  261. this._registerChannel();
  262. }
  263. };
  264. }
  265. super._connect(done);
  266. }
  267. }
  268. module.exports = Follower;