Protocol.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. var Parser = require('./Parser');
  2. var Sequences = require('./sequences');
  3. var Packets = require('./packets');
  4. var Auth = require('./Auth');
  5. var Stream = require('stream').Stream;
  6. var Util = require('util');
  7. var PacketWriter = require('./PacketWriter');
  8. module.exports = Protocol;
  9. Util.inherits(Protocol, Stream);
  10. function Protocol(options) {
  11. Stream.call(this);
  12. options = options || {};
  13. this.readable = true;
  14. this.writable = true;
  15. this._config = options.config || {};
  16. this._connection = options.connection;
  17. this._callback = null;
  18. this._fatalError = null;
  19. this._quitSequence = null;
  20. this._handshakeSequence = null;
  21. this._destroyed = false;
  22. this._queue = [];
  23. this._handshakeInitializationPacket = null;
  24. this._parser = new Parser({
  25. onPacket : this._parsePacket.bind(this),
  26. config : this._config
  27. });
  28. }
  29. Protocol.prototype.write = function(buffer) {
  30. this._parser.write(buffer);
  31. return true;
  32. };
  33. Protocol.prototype.handshake = function(cb) {
  34. return this._handshakeSequence = this._enqueue(new Sequences.Handshake(this._config, cb));
  35. };
  36. Protocol.prototype.query = function(options, cb) {
  37. return this._enqueue(new Sequences.Query(options, cb));
  38. };
  39. Protocol.prototype.changeUser = function(options, cb) {
  40. return this._enqueue(new Sequences.ChangeUser(options, cb));
  41. };
  42. Protocol.prototype.ping = function(cb) {
  43. return this._enqueue(new Sequences.Ping(cb));
  44. };
  45. Protocol.prototype.stats = function(cb) {
  46. return this._enqueue(new Sequences.Statistics(cb));
  47. };
  48. Protocol.prototype.quit = function(cb) {
  49. return this._quitSequence = this._enqueue(new Sequences.Quit(cb));
  50. };
  51. Protocol.prototype.end = function() {
  52. var expected = (this._quitSequence && this._queue[0] === this._quitSequence);
  53. if (expected) {
  54. this._quitSequence.end();
  55. this.emit('end');
  56. return;
  57. }
  58. var err = new Error('Connection lost: The server closed the connection.');
  59. err.fatal = true;
  60. err.code = 'PROTOCOL_CONNECTION_LOST';
  61. this._delegateError(err);
  62. };
  63. Protocol.prototype.pause = function() {
  64. this._parser.pause();
  65. };
  66. Protocol.prototype.resume = function() {
  67. this._parser.resume();
  68. };
  69. Protocol.prototype._enqueue = function(sequence) {
  70. if (!this._validateEnqueue(sequence)) {
  71. return sequence;
  72. }
  73. this._queue.push(sequence);
  74. var self = this;
  75. sequence
  76. .on('error', function(err) {
  77. self._delegateError(err, sequence);
  78. })
  79. .on('packet', function(packet) {
  80. self._emitPacket(packet);
  81. })
  82. .on('end', function() {
  83. self._dequeue();
  84. });
  85. if (this._queue.length === 1) {
  86. this._parser.resetPacketNumber();
  87. sequence.start();
  88. }
  89. return sequence;
  90. };
  91. Protocol.prototype._validateEnqueue = function(sequence) {
  92. var err;
  93. var prefix = 'Cannot enqueue ' + sequence.constructor.name + ' after ';
  94. if (this._quitSequence) {
  95. err = new Error(prefix + 'invoking quit.');
  96. err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT';
  97. } else if (this._destroyed) {
  98. err = new Error(prefix + 'being destroyed.');
  99. err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY';
  100. } else if (this._handshakeSequence && sequence.constructor === Sequences.Handshake) {
  101. err = new Error(prefix + 'already enqueuing a Handshake.');
  102. err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE';
  103. } else {
  104. return true;
  105. }
  106. var self = this;
  107. err.fatal = false;
  108. sequence
  109. .on('error', function(err) {
  110. self._delegateError(err, sequence);
  111. })
  112. .end(err);
  113. return false;
  114. };
  115. Protocol.prototype._parsePacket = function() {
  116. var sequence = this._queue[0];
  117. var Packet = this._determinePacket(sequence);
  118. var packet = new Packet();
  119. // Special case: Faster dispatch, and parsing done inside sequence
  120. if (Packet === Packets.RowDataPacket) {
  121. sequence.RowDataPacket(packet, this._parser, this._connection);
  122. if (this._config.debug) {
  123. this._debugPacket(true, packet);
  124. }
  125. return;
  126. }
  127. packet.parse(this._parser);
  128. if (this._config.debug) {
  129. this._debugPacket(true, packet);
  130. }
  131. if (Packet === Packets.HandshakeInitializationPacket) {
  132. this._handshakeInitializationPacket = packet;
  133. }
  134. sequence[Packet.name](packet);
  135. };
  136. Protocol.prototype._emitPacket = function(packet) {
  137. var packetWriter = new PacketWriter();
  138. packet.write(packetWriter);
  139. this.emit('data', packetWriter.toBuffer(this._parser));
  140. if (this._config.debug) {
  141. this._debugPacket(false, packet)
  142. }
  143. };
  144. Protocol.prototype._determinePacket = function(sequence) {
  145. var firstByte = this._parser.peak();
  146. if (sequence.determinePacket) {
  147. var Packet = sequence.determinePacket(firstByte, this._parser);
  148. if (Packet) {
  149. return Packet;
  150. }
  151. }
  152. switch (firstByte) {
  153. case 0x00: return Packets.OkPacket;
  154. case 0xfe: return Packets.EofPacket;
  155. case 0xff: return Packets.ErrorPacket;
  156. }
  157. throw new Error('Could not determine packet, firstByte = ' + firstByte);
  158. };
  159. Protocol.prototype._dequeue = function() {
  160. // No point in advancing the queue, we are dead
  161. if (this._fatalError) {
  162. return;
  163. }
  164. this._queue.shift();
  165. var sequence = this._queue[0];
  166. if (!sequence) {
  167. this.emit('drain');
  168. return;
  169. }
  170. this._parser.resetPacketNumber();
  171. if (sequence.constructor == Sequences.ChangeUser) {
  172. sequence.start(this._handshakeInitializationPacket);
  173. return;
  174. }
  175. sequence.start();
  176. };
  177. Protocol.prototype.handleNetworkError = function(err) {
  178. err.fatal = true;
  179. var sequence = this._queue[0];
  180. if (sequence) {
  181. sequence.end(err)
  182. } else {
  183. this._delegateError(err);
  184. }
  185. };
  186. Protocol.prototype._delegateError = function(err, sequence) {
  187. // Stop delegating errors after the first fatal error
  188. if (this._fatalError) {
  189. return;
  190. }
  191. if (err.fatal) {
  192. this._fatalError = err;
  193. }
  194. if (this._shouldErrorBubbleUp(err, sequence)) {
  195. // Can't use regular 'error' event here as that always destroys the pipe
  196. // between socket and protocol which is not what we want (unless the
  197. // exception was fatal).
  198. this.emit('unhandledError', err);
  199. } else if (err.fatal) {
  200. this._queue.forEach(function(sequence) {
  201. sequence.end(err);
  202. });
  203. }
  204. // Make sure the stream we are piping to is getting closed
  205. if (err.fatal) {
  206. this.emit('end', err);
  207. }
  208. };
  209. Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) {
  210. if (sequence) {
  211. if (sequence.hasErrorHandler()) {
  212. return false;
  213. } else if (!err.fatal) {
  214. return true;
  215. }
  216. }
  217. return (err.fatal && !this._hasPendingErrorHandlers());
  218. };
  219. Protocol.prototype._hasPendingErrorHandlers = function() {
  220. return this._queue.some(function(sequence) {
  221. return sequence.hasErrorHandler();
  222. });
  223. };
  224. Protocol.prototype.destroy = function() {
  225. this._destroyed = true;
  226. this._parser.pause();
  227. };
  228. Protocol.prototype._debugPacket = function(incoming, packet) {
  229. var headline = (incoming)
  230. ? '<-- '
  231. : '--> ';
  232. headline = headline + packet.constructor.name;
  233. console.log(headline);
  234. console.log(packet);
  235. console.log('');
  236. };