bulk-packet.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. 'use strict';
  2. const moment = require('moment-timezone');
  3. const Iconv = require('iconv-lite');
  4. const SMALL_BUFFER_SIZE = 1024;
  5. const MEDIUM_BUFFER_SIZE = 16384; //16k
  6. const LARGE_BUFFER_SIZE = 131072; //128k
  7. const BIG_BUFFER_SIZE = 1048576; //1M
  8. const MAX_BUFFER_SIZE = 16777219; //16M + 4
  9. /**
  10. * Packet splitter.
  11. *
  12. * The servers have a limit max_allowed_packet which limits the size of the data sent, to avoid saturating the server in memory.
  13. *
  14. * The following implementation has a workaround that will rewrite the command and separate the send according to this value.
  15. * This implies that this command can send multiple commands, with some tricks for sequencing packets.
  16. *
  17. */
  18. class BulkPacket {
  19. constructor(opts, out, row) {
  20. this.out = out;
  21. this.buf = Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  22. this.pos = 4;
  23. this.datatypes = [];
  24. this.encoding = out.encoding;
  25. this.statementId = -1;
  26. this.waitingResponseNo = 1;
  27. this.singleQuery = false;
  28. this.haveErrorResponse = false;
  29. this.writeBinaryDate = opts.tz
  30. ? opts.tz === 'Etc/UTC'
  31. ? this.writeBinaryUtcDate
  32. : this.writeBinaryTimezoneDate
  33. : this.writeBinaryLocalDate;
  34. if (this.encoding === 'utf8') {
  35. this.writeLengthEncodedString = this.writeDefaultLengthEncodedString;
  36. } else if (Buffer.isEncoding(this.encoding)) {
  37. this.writeLengthEncodedString = this.writeDefaultLengthEncodedString;
  38. } else {
  39. this.writeLengthEncodedString = this.writeIconvLengthEncodedString;
  40. }
  41. this.maxAllowedPacket = opts.maxAllowedPacket;
  42. this.maxPacketSize = opts.maxAllowedPacket
  43. ? Math.min(MAX_BUFFER_SIZE, opts.maxAllowedPacket)
  44. : 4194304;
  45. this.writeHeader(row);
  46. }
  47. datatypeChanged(row) {
  48. if (this.datatypes.length !== row.length) return true;
  49. for (let r = 0; r < row.length; r++) {
  50. if (row[r] !== null) {
  51. switch (typeof row[r]) {
  52. case 'boolean':
  53. if (this.datatypes[r] !== 0x01) return true;
  54. break;
  55. case 'number':
  56. case 'bigint':
  57. if (this.datatypes[r] !== 0x0f) return true;
  58. break;
  59. case 'object':
  60. if (Object.prototype.toString.call(row[r]) === '[object Date]') {
  61. if (this.datatypes[r] !== 0x0c) return true;
  62. } else if (Buffer.isBuffer(row[r])) {
  63. if (this.datatypes[r] !== 0xfb) return true;
  64. } else if (
  65. row[r].type != null &&
  66. [
  67. 'Point',
  68. 'LineString',
  69. 'Polygon',
  70. 'MultiPoint',
  71. 'MultiLineString',
  72. 'MultiPolygon',
  73. 'GeometryCollection'
  74. ].includes(row[r].type)
  75. ) {
  76. if (this.datatypes[r] !== 0xfb) return true;
  77. } else {
  78. if (this.datatypes[r] !== 0x0f) return true;
  79. }
  80. break;
  81. default:
  82. if (this.datatypes[r] !== 0x0f) return true;
  83. }
  84. }
  85. }
  86. return false;
  87. }
  88. writeHeader(row) {
  89. this.buf[this.pos++] = 0xfa;
  90. //use last prepare command
  91. this.buf[this.pos++] = this.statementId;
  92. this.buf[this.pos++] = this.statementId >> 8;
  93. this.buf[this.pos++] = this.statementId >> 16;
  94. this.buf[this.pos++] = this.statementId >> 24;
  95. //set bulk flags to Send types to server
  96. this.buf[this.pos++] = 0x80;
  97. this.buf[this.pos++] = 0x00;
  98. //send data type (strings)
  99. this.datatypes = [];
  100. if (row) {
  101. for (let r = 0; r < row.length; r++) {
  102. if (row[r] === null) {
  103. this.buf[this.pos++] = 0x0f;
  104. } else {
  105. switch (typeof row[r]) {
  106. case 'boolean':
  107. this.buf[this.pos++] = 0x01;
  108. break;
  109. case 'bigint':
  110. case 'number':
  111. this.buf[this.pos++] = 0x0f;
  112. break;
  113. case 'object':
  114. if (Object.prototype.toString.call(row[r]) === '[object Date]') {
  115. this.buf[this.pos++] = 0x0c;
  116. } else if (Buffer.isBuffer(row[r])) {
  117. this.buf[this.pos++] = 0xfb;
  118. } else if (
  119. row[r].type != null &&
  120. [
  121. 'Point',
  122. 'LineString',
  123. 'Polygon',
  124. 'MultiPoint',
  125. 'MultiLineString',
  126. 'MultiPolygon',
  127. 'GeometryCollection'
  128. ].includes(row[r].type)
  129. ) {
  130. this.buf[this.pos++] = 0xfb;
  131. } else {
  132. this.buf[this.pos++] = 0x0f;
  133. }
  134. break;
  135. default:
  136. this.buf[this.pos++] = 0x0f;
  137. }
  138. }
  139. this.datatypes[r] = this.buf[this.pos - 1];
  140. this.buf[this.pos++] = 0x00;
  141. }
  142. }
  143. }
  144. growBuffer(len) {
  145. let newCapacity;
  146. if (len + this.pos < MEDIUM_BUFFER_SIZE) {
  147. newCapacity = MEDIUM_BUFFER_SIZE;
  148. } else if (len + this.pos < LARGE_BUFFER_SIZE) {
  149. newCapacity = LARGE_BUFFER_SIZE;
  150. } else if (len + this.pos < BIG_BUFFER_SIZE) {
  151. newCapacity = BIG_BUFFER_SIZE;
  152. } else newCapacity = MAX_BUFFER_SIZE;
  153. if (newCapacity > this.maxPacketSize && this.markPos) {
  154. this.flush(false, len);
  155. return true;
  156. } else {
  157. let newBuf = Buffer.allocUnsafe(Math.min(newCapacity));
  158. this.buf.copy(newBuf, 0, 0, this.pos);
  159. this.buf = newBuf;
  160. return false;
  161. }
  162. }
  163. writeLengthStringAscii(val) {
  164. let len = val.length;
  165. //not enough space remaining
  166. if (len >= this.buf.length - this.pos) {
  167. let strBuf = Buffer.from(val, 'ascii');
  168. return this.writeLengthEncodedBuffer(strBuf);
  169. }
  170. this.writeLength(len);
  171. for (let off = 0; off < len; ) {
  172. this.buf[this.pos++] = val.charCodeAt(off++);
  173. }
  174. return false;
  175. }
  176. writeLength(len) {
  177. if (len < 0xfb) {
  178. return this.writeInt8(len);
  179. } else if (len < 65536) {
  180. let flushed = this.writeInt8(0xfc);
  181. return this.writeInt16(len) || flushed;
  182. } else if (len < 16777216) {
  183. let flushed = this.writeInt8(0xfd);
  184. return this.writeInt24(len) || flushed;
  185. } else {
  186. //4 last bytes are filled with 0, packet limitation size is 32 bit integer
  187. if (this.pos + 9 >= this.buf.length) {
  188. const tmpBuf = Buffer.allocUnsafe(9);
  189. tmpBuf[0] = 0xfe;
  190. tmpBuf[1] = len;
  191. tmpBuf[2] = len >>> 8;
  192. tmpBuf[3] = len >>> 16;
  193. tmpBuf[4] = len >>> 24;
  194. tmpBuf[5] = 0;
  195. tmpBuf[6] = 0;
  196. tmpBuf[7] = 0;
  197. tmpBuf[8] = 0;
  198. return this.writeBuffer(tmpBuf);
  199. }
  200. this.buf[this.pos++] = 0xfe;
  201. this.buf[this.pos++] = len;
  202. this.buf[this.pos++] = len >>> 8;
  203. this.buf[this.pos++] = len >>> 16;
  204. this.buf[this.pos++] = len >>> 24;
  205. this.buf[this.pos++] = 0;
  206. this.buf[this.pos++] = 0;
  207. this.buf[this.pos++] = 0;
  208. this.buf[this.pos++] = 0;
  209. return false;
  210. }
  211. }
  212. writeLengthEncodedBuffer(val) {
  213. let valLen = val.length;
  214. let flushed = this.writeLength(valLen);
  215. return this.writeBuffer(val) || flushed;
  216. }
  217. writeBuffer(val) {
  218. let flushed = false;
  219. let valLen = val.length;
  220. if (valLen > this.buf.length - this.pos) {
  221. //makes buffer bigger (up to 16M)
  222. if (this.buf.length < MAX_BUFFER_SIZE) flushed = this.growBuffer(valLen * 2);
  223. //data may still be bigger than buffer.
  224. //must flush buffer when full (and reset position to 4)
  225. if (valLen > this.buf.length - this.pos) {
  226. let tmpPos = this.buf.length - this.pos;
  227. val.copy(this.buf, this.pos, 0, tmpPos);
  228. this.pos += tmpPos;
  229. this.flush(false, valLen - tmpPos);
  230. while (tmpPos < valLen) {
  231. if (this.buf.length - this.pos < valLen - tmpPos) this.growBuffer(valLen - tmpPos);
  232. const toWrite = Math.min(valLen - tmpPos, this.buf.length - this.pos);
  233. val.copy(this.buf, this.pos, tmpPos, tmpPos + toWrite);
  234. tmpPos += toWrite;
  235. this.pos += toWrite;
  236. if (valLen - tmpPos > 0) this.flush(false, valLen - tmpPos);
  237. }
  238. return true;
  239. }
  240. }
  241. //sure to have enough place to use buffer directly
  242. val.copy(this.buf, this.pos, 0, valLen);
  243. this.pos += valLen;
  244. return flushed;
  245. }
  246. writeInt8(value) {
  247. let flushed = false;
  248. if (this.pos + 1 > this.buf.length) {
  249. if (this.buf.length < MAX_BUFFER_SIZE) {
  250. flushed = this.growBuffer(1);
  251. } else {
  252. this.flush(false, 1);
  253. this.buf[this.pos++] = value;
  254. return true;
  255. }
  256. }
  257. this.buf[this.pos++] = value;
  258. return flushed;
  259. }
  260. writeInt16(value) {
  261. let flushed = false;
  262. if (this.pos + 2 > this.buf.length) {
  263. if (this.buf.length < this.maxPacketSize) flushed = this.growBuffer(2);
  264. if (this.pos + 2 > this.buf.length) {
  265. const tmpBuf = Buffer.allocUnsafe(2);
  266. tmpBuf[0] = value;
  267. tmpBuf[1] = value >>> 8;
  268. this.writeBuffer(tmpBuf);
  269. return true;
  270. }
  271. }
  272. this.buf[this.pos++] = value;
  273. this.buf[this.pos++] = value >>> 8;
  274. return flushed;
  275. }
  276. writeInt24(value) {
  277. let flushed = false;
  278. if (this.pos + 3 > this.buf.length) {
  279. if (this.buf.length < this.maxPacketSize) flushed = this.growBuffer(3);
  280. if (this.pos + 3 > this.buf.length) {
  281. const tmpBuf = Buffer.allocUnsafe(3);
  282. tmpBuf[0] = value;
  283. tmpBuf[1] = value >>> 8;
  284. tmpBuf[2] = value >>> 16;
  285. this.writeBuffer(tmpBuf);
  286. return true;
  287. }
  288. }
  289. this.buf[this.pos++] = value;
  290. this.buf[this.pos++] = value >>> 8;
  291. this.buf[this.pos++] = value >>> 16;
  292. return flushed;
  293. }
  294. writeIconvLengthEncodedString(str) {
  295. let buf = Iconv.encode(str, this.encoding);
  296. return this.writeLengthEncodedBuffer(buf, 0, buf.length);
  297. }
  298. writeDefaultLengthEncodedString(str) {
  299. //javascript use UCS-2 or UTF-16 string internal representation
  300. //that means that string to byte will be a maximum of * 3
  301. // (4 bytes utf-8 are represented on 2 UTF-16 characters)
  302. if (str.length * 3 + 10 < this.buf.length - this.pos) {
  303. //reserve position for length indicator
  304. const maxLen = str.length * 3;
  305. let lengthPos;
  306. if (maxLen < 0xfb) {
  307. lengthPos = this.pos;
  308. this.pos++;
  309. } else if (maxLen < 65536) {
  310. this.buf[this.pos++] = 0xfc;
  311. lengthPos = this.pos;
  312. this.pos += 2;
  313. } else {
  314. //if len was > 16M, would have been > to buffer length
  315. this.buf[this.pos++] = 0xfd;
  316. lengthPos = this.pos;
  317. this.pos += 3;
  318. }
  319. const prevPos = this.pos;
  320. this.pos += this.buf.write(str, this.pos, this.encoding);
  321. //write real data length
  322. const realLen = this.pos - prevPos;
  323. if (maxLen < 0xfb) {
  324. this.buf[lengthPos] = realLen;
  325. } else if (maxLen < 65536) {
  326. this.buf[lengthPos] = realLen;
  327. this.buf[lengthPos + 1] = realLen >>> 8;
  328. } else {
  329. this.buf[lengthPos] = realLen;
  330. this.buf[lengthPos + 1] = realLen >>> 8;
  331. this.buf[lengthPos + 2] = realLen >>> 16;
  332. }
  333. return false;
  334. }
  335. //checking real length
  336. let flushed = false;
  337. let byteLength = Buffer.byteLength(str, this.encoding);
  338. if (byteLength + 9 > this.buf.length - this.pos) {
  339. if (this.buf.length < MAX_BUFFER_SIZE) flushed = this.growBuffer(byteLength + 9);
  340. if (byteLength > this.buf.length - this.pos) {
  341. //not enough space in buffer, will stream :
  342. let strBuf = Buffer.from(str, this.encoding);
  343. return this.writeLengthEncodedBuffer(strBuf) || flushed;
  344. }
  345. }
  346. this.writeLength(byteLength);
  347. this.pos += this.buf.write(str, this.pos, this.encoding);
  348. return flushed;
  349. }
  350. writeBinaryLocalDate(date, opts) {
  351. const year = date.getFullYear();
  352. const mon = date.getMonth() + 1;
  353. const day = date.getDate();
  354. const hour = date.getHours();
  355. const min = date.getMinutes();
  356. const sec = date.getSeconds();
  357. const ms = date.getMilliseconds();
  358. return this._writeBinaryDate(year, mon, day, hour, min, sec, ms);
  359. }
  360. writeBinaryUtcDate(date, opts) {
  361. const year = date.getUTCFullYear();
  362. const mon = date.getUTCMonth() + 1;
  363. const day = date.getUTCDate();
  364. const hour = date.getUTCHours();
  365. const min = date.getUTCMinutes();
  366. const sec = date.getUTCSeconds();
  367. const ms = date.getUTCMilliseconds();
  368. return this._writeBinaryDate(year, mon, day, hour, min, sec, ms);
  369. }
  370. _writeBinaryDate(year, mon, day, hour, min, sec, ms) {
  371. let len = ms === 0 ? 7 : 11;
  372. //not enough space remaining
  373. if (len + 1 > this.buf.length - this.pos) {
  374. let tmpBuf = Buffer.allocUnsafe(len + 1);
  375. tmpBuf[0] = len;
  376. tmpBuf[1] = year;
  377. tmpBuf[2] = year >>> 8;
  378. tmpBuf[3] = mon;
  379. tmpBuf[4] = day;
  380. tmpBuf[5] = hour;
  381. tmpBuf[6] = min;
  382. tmpBuf[7] = sec;
  383. if (ms !== 0) {
  384. const micro = ms * 1000;
  385. tmpBuf[8] = micro;
  386. tmpBuf[9] = micro >>> 8;
  387. tmpBuf[10] = micro >>> 16;
  388. tmpBuf[11] = micro >>> 24;
  389. }
  390. return this.writeBuffer(tmpBuf);
  391. }
  392. this.buf[this.pos] = len;
  393. this.buf[this.pos + 1] = year;
  394. this.buf[this.pos + 2] = year >>> 8;
  395. this.buf[this.pos + 3] = mon;
  396. this.buf[this.pos + 4] = day;
  397. this.buf[this.pos + 5] = hour;
  398. this.buf[this.pos + 6] = min;
  399. this.buf[this.pos + 7] = sec;
  400. if (ms !== 0) {
  401. const micro = ms * 1000;
  402. this.buf[this.pos + 8] = micro;
  403. this.buf[this.pos + 9] = micro >>> 8;
  404. this.buf[this.pos + 10] = micro >>> 16;
  405. this.buf[this.pos + 11] = micro >>> 24;
  406. }
  407. this.pos += len + 1;
  408. return false;
  409. }
  410. writeBinaryTimezoneDate(date, opts) {
  411. const dateZoned = new Date(
  412. moment.tz(date, opts.localTz).tz(opts.tz).format('YYYY-MM-DD HH:mm:ss.SSSSSS')
  413. );
  414. const year = dateZoned.getFullYear();
  415. const mon = dateZoned.getMonth() + 1;
  416. const day = dateZoned.getDate();
  417. const hour = dateZoned.getHours();
  418. const min = dateZoned.getMinutes();
  419. const sec = dateZoned.getSeconds();
  420. const ms = dateZoned.getMilliseconds();
  421. return this._writeBinaryDate(year, mon, day, hour, min, sec, ms);
  422. }
  423. mark(isLast, nextRow) {
  424. let flushed = false;
  425. this.nextRow = nextRow;
  426. if (this.singleQuery) {
  427. //end of big query that is more than 16M
  428. //write single one
  429. if (!this.haveErrorResponse) {
  430. const packetSendSize =
  431. this.pos +
  432. (this.singleQuerySequenceNo !== undefined
  433. ? (this.singleQuerySequenceNo + 1) * MAX_BUFFER_SIZE
  434. : 0);
  435. if (this.maxAllowedPacket && packetSendSize > this.maxAllowedPacket) {
  436. console.log(
  437. "will send a packet to db server with size > connection option 'maxAllowedPacket' (size send is " +
  438. packetSendSize +
  439. ') connection might be reset by server'
  440. );
  441. }
  442. this.copyAndFlush(true);
  443. flushed = true;
  444. this.markPos = undefined;
  445. }
  446. this.singleQuerySequenceNo = undefined;
  447. this.singleQueryCompressSequenceNo = undefined;
  448. this.singleQuery = false;
  449. this.writeHeader(nextRow);
  450. this.markPos = undefined;
  451. } else {
  452. if (!isLast && this.datatypeChanged(nextRow)) {
  453. this.markPos = this.pos;
  454. this.flushMark();
  455. flushed = true;
  456. } else if (this.markPos && this.pos > this.maxPacketSize) {
  457. //not enough room for current query , flush mark.
  458. this.flushMark();
  459. flushed = true;
  460. } else {
  461. //just mark ending query
  462. this.markPos = this.pos;
  463. if (isLast) {
  464. this.flushMark();
  465. flushed = true;
  466. }
  467. }
  468. }
  469. return flushed;
  470. }
  471. flush(end, remainingLen) {
  472. if (this.markPos && !this.singleQuery) {
  473. this.flushMark();
  474. } else {
  475. //one insert is more than 16M, will continue to mono insert, hoping
  476. //that max_allowed_packet is sized accordingly to query.
  477. if (this.buf.length < MAX_BUFFER_SIZE) {
  478. //in this case, connector has default to 4M packet, and a single query size
  479. //is > to 4mb. growing buffer to 16M
  480. let newBuf = Buffer.allocUnsafe(MAX_BUFFER_SIZE);
  481. this.buf.copy(newBuf, 0, 0, this.pos);
  482. this.buf = newBuf;
  483. } else {
  484. if (!this.haveErrorResponse) {
  485. if (this.maxAllowedPacket && this.buf.length > this.maxAllowedPacket) {
  486. console.log(
  487. "will send a packet to server with size > connection option 'maxAllowedPacket' (size send is " +
  488. this.pos +
  489. ') connection might be reset by server'
  490. );
  491. }
  492. this.copyAndFlush(false);
  493. this.markPos = undefined;
  494. if (!this.singleQuery) this.waitingResponseNo++;
  495. this.singleQuery = true;
  496. this.singleQuerySequenceNo = this.out.cmd.sequenceNo;
  497. this.singleQueryCompressSequenceNo = this.out.cmd.compressSequenceNo;
  498. }
  499. }
  500. }
  501. }
  502. flushMark() {
  503. let afterMark;
  504. if (this.pos !== this.markPos) {
  505. afterMark = Buffer.allocUnsafe(this.pos - this.markPos);
  506. this.buf.copy(afterMark, 0, this.markPos, this.pos);
  507. }
  508. this.pos = this.markPos;
  509. if (!this.haveErrorResponse) {
  510. this.copyAndFlush(true);
  511. this.waitingResponseNo++;
  512. }
  513. this.pos = 4;
  514. this.markPos = undefined;
  515. if (this.nextRow) this.writeHeader(this.nextRow);
  516. if (afterMark) {
  517. if (this.buf.length - this.pos < afterMark.length)
  518. this.growBuffer(afterMark.length - (this.buf.length - this.pos));
  519. afterMark.copy(this.buf, this.pos, 0, afterMark.length);
  520. this.pos += afterMark.length;
  521. }
  522. this.singleQuery = false;
  523. this.singleQuerySequenceNo = undefined;
  524. this.singleQueryCompressSequenceNo = undefined;
  525. }
  526. copyAndFlush(ended) {
  527. this.out.buf = this.buf;
  528. this.out.pos = this.pos;
  529. if (this.singleQuerySequenceNo !== undefined) {
  530. this.out.cmd.sequenceNo = this.singleQuerySequenceNo;
  531. this.out.cmd.compressSequenceNo = this.singleQueryCompressSequenceNo;
  532. } else {
  533. this.out.cmd.sequenceNo = -1;
  534. this.out.cmd.compressSequenceNo = -1;
  535. }
  536. this.out.flushBuffer(ended);
  537. if (this.singleQuerySequenceNo !== undefined) {
  538. this.singleQuerySequenceNo = this.out.cmd.sequenceNo;
  539. this.singleQueryCompressSequenceNo = this.out.cmd.compressSequenceNo;
  540. }
  541. this.pos = 4;
  542. this.buf = Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  543. }
  544. endedWithError() {
  545. this.haveErrorResponse = true;
  546. }
  547. }
  548. module.exports = BulkPacket;