parser.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.Parser = void 0;
  7. const messages_1 = require("./messages");
  8. const buffer_reader_1 = require("./buffer-reader");
  9. const assert_1 = __importDefault(require("assert"));
  10. // every message is prefixed with a single bye
  11. const CODE_LENGTH = 1;
  12. // every message has an int32 length which includes itself but does
  13. // NOT include the code in the length
  14. const LEN_LENGTH = 4;
  15. const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH;
  16. const emptyBuffer = Buffer.allocUnsafe(0);
  17. class Parser {
  18. constructor(opts) {
  19. this.buffer = emptyBuffer;
  20. this.bufferLength = 0;
  21. this.bufferOffset = 0;
  22. this.reader = new buffer_reader_1.BufferReader();
  23. if ((opts === null || opts === void 0 ? void 0 : opts.mode) === 'binary') {
  24. throw new Error('Binary mode not supported yet');
  25. }
  26. this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || 'text';
  27. }
  28. parse(buffer, callback) {
  29. this.mergeBuffer(buffer);
  30. const bufferFullLength = this.bufferOffset + this.bufferLength;
  31. let offset = this.bufferOffset;
  32. while (offset + HEADER_LENGTH <= bufferFullLength) {
  33. // code is 1 byte long - it identifies the message type
  34. const code = this.buffer[offset];
  35. // length is 1 Uint32BE - it is the length of the message EXCLUDING the code
  36. const length = this.buffer.readUInt32BE(offset + CODE_LENGTH);
  37. const fullMessageLength = CODE_LENGTH + length;
  38. if (fullMessageLength + offset <= bufferFullLength) {
  39. const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer);
  40. callback(message);
  41. offset += fullMessageLength;
  42. }
  43. else {
  44. break;
  45. }
  46. }
  47. if (offset === bufferFullLength) {
  48. // No more use for the buffer
  49. this.buffer = emptyBuffer;
  50. this.bufferLength = 0;
  51. this.bufferOffset = 0;
  52. }
  53. else {
  54. // Adjust the cursors of remainingBuffer
  55. this.bufferLength = bufferFullLength - offset;
  56. this.bufferOffset = offset;
  57. }
  58. }
  59. mergeBuffer(buffer) {
  60. if (this.bufferLength > 0) {
  61. const newLength = this.bufferLength + buffer.byteLength;
  62. const newFullLength = newLength + this.bufferOffset;
  63. if (newFullLength > this.buffer.byteLength) {
  64. // We can't concat the new buffer with the remaining one
  65. let newBuffer;
  66. if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) {
  67. // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer
  68. newBuffer = this.buffer;
  69. }
  70. else {
  71. // Allocate a new larger buffer
  72. let newBufferLength = this.buffer.byteLength * 2;
  73. while (newLength >= newBufferLength) {
  74. newBufferLength *= 2;
  75. }
  76. newBuffer = Buffer.allocUnsafe(newBufferLength);
  77. }
  78. // Move the remaining buffer to the new one
  79. this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength);
  80. this.buffer = newBuffer;
  81. this.bufferOffset = 0;
  82. }
  83. // Concat the new buffer with the remaining one
  84. buffer.copy(this.buffer, this.bufferOffset + this.bufferLength);
  85. this.bufferLength = newLength;
  86. }
  87. else {
  88. this.buffer = buffer;
  89. this.bufferOffset = 0;
  90. this.bufferLength = buffer.byteLength;
  91. }
  92. }
  93. handlePacket(offset, code, length, bytes) {
  94. switch (code) {
  95. case 50 /* BindComplete */:
  96. return messages_1.bindComplete;
  97. case 49 /* ParseComplete */:
  98. return messages_1.parseComplete;
  99. case 51 /* CloseComplete */:
  100. return messages_1.closeComplete;
  101. case 110 /* NoData */:
  102. return messages_1.noData;
  103. case 115 /* PortalSuspended */:
  104. return messages_1.portalSuspended;
  105. case 99 /* CopyDone */:
  106. return messages_1.copyDone;
  107. case 87 /* ReplicationStart */:
  108. return messages_1.replicationStart;
  109. case 73 /* EmptyQuery */:
  110. return messages_1.emptyQuery;
  111. case 68 /* DataRow */:
  112. return this.parseDataRowMessage(offset, length, bytes);
  113. case 67 /* CommandComplete */:
  114. return this.parseCommandCompleteMessage(offset, length, bytes);
  115. case 90 /* ReadyForQuery */:
  116. return this.parseReadyForQueryMessage(offset, length, bytes);
  117. case 65 /* NotificationResponse */:
  118. return this.parseNotificationMessage(offset, length, bytes);
  119. case 82 /* AuthenticationResponse */:
  120. return this.parseAuthenticationResponse(offset, length, bytes);
  121. case 83 /* ParameterStatus */:
  122. return this.parseParameterStatusMessage(offset, length, bytes);
  123. case 75 /* BackendKeyData */:
  124. return this.parseBackendKeyData(offset, length, bytes);
  125. case 69 /* ErrorMessage */:
  126. return this.parseErrorMessage(offset, length, bytes, 'error');
  127. case 78 /* NoticeMessage */:
  128. return this.parseErrorMessage(offset, length, bytes, 'notice');
  129. case 84 /* RowDescriptionMessage */:
  130. return this.parseRowDescriptionMessage(offset, length, bytes);
  131. case 116 /* ParameterDescriptionMessage */:
  132. return this.parseParameterDescriptionMessage(offset, length, bytes);
  133. case 71 /* CopyIn */:
  134. return this.parseCopyInMessage(offset, length, bytes);
  135. case 72 /* CopyOut */:
  136. return this.parseCopyOutMessage(offset, length, bytes);
  137. case 100 /* CopyData */:
  138. return this.parseCopyData(offset, length, bytes);
  139. default:
  140. assert_1.default.fail(`unknown message code: ${code.toString(16)}`);
  141. }
  142. }
  143. parseReadyForQueryMessage(offset, length, bytes) {
  144. this.reader.setBuffer(offset, bytes);
  145. const status = this.reader.string(1);
  146. return new messages_1.ReadyForQueryMessage(length, status);
  147. }
  148. parseCommandCompleteMessage(offset, length, bytes) {
  149. this.reader.setBuffer(offset, bytes);
  150. const text = this.reader.cstring();
  151. return new messages_1.CommandCompleteMessage(length, text);
  152. }
  153. parseCopyData(offset, length, bytes) {
  154. const chunk = bytes.slice(offset, offset + (length - 4));
  155. return new messages_1.CopyDataMessage(length, chunk);
  156. }
  157. parseCopyInMessage(offset, length, bytes) {
  158. return this.parseCopyMessage(offset, length, bytes, 'copyInResponse');
  159. }
  160. parseCopyOutMessage(offset, length, bytes) {
  161. return this.parseCopyMessage(offset, length, bytes, 'copyOutResponse');
  162. }
  163. parseCopyMessage(offset, length, bytes, messageName) {
  164. this.reader.setBuffer(offset, bytes);
  165. const isBinary = this.reader.byte() !== 0;
  166. const columnCount = this.reader.int16();
  167. const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount);
  168. for (let i = 0; i < columnCount; i++) {
  169. message.columnTypes[i] = this.reader.int16();
  170. }
  171. return message;
  172. }
  173. parseNotificationMessage(offset, length, bytes) {
  174. this.reader.setBuffer(offset, bytes);
  175. const processId = this.reader.int32();
  176. const channel = this.reader.cstring();
  177. const payload = this.reader.cstring();
  178. return new messages_1.NotificationResponseMessage(length, processId, channel, payload);
  179. }
  180. parseRowDescriptionMessage(offset, length, bytes) {
  181. this.reader.setBuffer(offset, bytes);
  182. const fieldCount = this.reader.int16();
  183. const message = new messages_1.RowDescriptionMessage(length, fieldCount);
  184. for (let i = 0; i < fieldCount; i++) {
  185. message.fields[i] = this.parseField();
  186. }
  187. return message;
  188. }
  189. parseField() {
  190. const name = this.reader.cstring();
  191. const tableID = this.reader.int32();
  192. const columnID = this.reader.int16();
  193. const dataTypeID = this.reader.int32();
  194. const dataTypeSize = this.reader.int16();
  195. const dataTypeModifier = this.reader.int32();
  196. const mode = this.reader.int16() === 0 ? 'text' : 'binary';
  197. return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
  198. }
  199. parseParameterDescriptionMessage(offset, length, bytes) {
  200. this.reader.setBuffer(offset, bytes);
  201. const parameterCount = this.reader.int16();
  202. const message = new messages_1.ParameterDescriptionMessage(length, parameterCount);
  203. for (let i = 0; i < parameterCount; i++) {
  204. message.dataTypeIDs[i] = this.reader.int32();
  205. }
  206. return message;
  207. }
  208. parseDataRowMessage(offset, length, bytes) {
  209. this.reader.setBuffer(offset, bytes);
  210. const fieldCount = this.reader.int16();
  211. const fields = new Array(fieldCount);
  212. for (let i = 0; i < fieldCount; i++) {
  213. const len = this.reader.int32();
  214. // a -1 for length means the value of the field is null
  215. fields[i] = len === -1 ? null : this.reader.string(len);
  216. }
  217. return new messages_1.DataRowMessage(length, fields);
  218. }
  219. parseParameterStatusMessage(offset, length, bytes) {
  220. this.reader.setBuffer(offset, bytes);
  221. const name = this.reader.cstring();
  222. const value = this.reader.cstring();
  223. return new messages_1.ParameterStatusMessage(length, name, value);
  224. }
  225. parseBackendKeyData(offset, length, bytes) {
  226. this.reader.setBuffer(offset, bytes);
  227. const processID = this.reader.int32();
  228. const secretKey = this.reader.int32();
  229. return new messages_1.BackendKeyDataMessage(length, processID, secretKey);
  230. }
  231. parseAuthenticationResponse(offset, length, bytes) {
  232. this.reader.setBuffer(offset, bytes);
  233. const code = this.reader.int32();
  234. // TODO(bmc): maybe better types here
  235. const message = {
  236. name: 'authenticationOk',
  237. length,
  238. };
  239. switch (code) {
  240. case 0: // AuthenticationOk
  241. break;
  242. case 3: // AuthenticationCleartextPassword
  243. if (message.length === 8) {
  244. message.name = 'authenticationCleartextPassword';
  245. }
  246. break;
  247. case 5: // AuthenticationMD5Password
  248. if (message.length === 12) {
  249. message.name = 'authenticationMD5Password';
  250. const salt = this.reader.bytes(4);
  251. return new messages_1.AuthenticationMD5Password(length, salt);
  252. }
  253. break;
  254. case 10: // AuthenticationSASL
  255. message.name = 'authenticationSASL';
  256. message.mechanisms = [];
  257. let mechanism;
  258. do {
  259. mechanism = this.reader.cstring();
  260. if (mechanism) {
  261. message.mechanisms.push(mechanism);
  262. }
  263. } while (mechanism);
  264. break;
  265. case 11: // AuthenticationSASLContinue
  266. message.name = 'authenticationSASLContinue';
  267. message.data = this.reader.string(length - 8);
  268. break;
  269. case 12: // AuthenticationSASLFinal
  270. message.name = 'authenticationSASLFinal';
  271. message.data = this.reader.string(length - 8);
  272. break;
  273. default:
  274. throw new Error('Unknown authenticationOk message type ' + code);
  275. }
  276. return message;
  277. }
  278. parseErrorMessage(offset, length, bytes, name) {
  279. this.reader.setBuffer(offset, bytes);
  280. const fields = {};
  281. let fieldType = this.reader.string(1);
  282. while (fieldType !== '\0') {
  283. fields[fieldType] = this.reader.cstring();
  284. fieldType = this.reader.string(1);
  285. }
  286. const messageValue = fields.M;
  287. const message = name === 'notice' ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
  288. message.severity = fields.S;
  289. message.code = fields.C;
  290. message.detail = fields.D;
  291. message.hint = fields.H;
  292. message.position = fields.P;
  293. message.internalPosition = fields.p;
  294. message.internalQuery = fields.q;
  295. message.where = fields.W;
  296. message.schema = fields.s;
  297. message.table = fields.t;
  298. message.column = fields.c;
  299. message.dataType = fields.d;
  300. message.constraint = fields.n;
  301. message.file = fields.F;
  302. message.line = fields.L;
  303. message.routine = fields.R;
  304. return message;
  305. }
  306. }
  307. exports.Parser = Parser;
  308. //# sourceMappingURL=parser.js.map