Source: lib/Transport.js

  1. /*
  2. * Copyright OpenSearch Contributors
  3. * SPDX-License-Identifier: Apache-2.0
  4. *
  5. * The OpenSearch Contributors require contributions made to
  6. * this file be licensed under the Apache-2.0 license or a
  7. * compatible open source license.
  8. *
  9. */
  10. /*
  11. * Licensed to Elasticsearch B.V. under one or more contributor
  12. * license agreements. See the NOTICE file distributed with
  13. * this work for additional information regarding copyright
  14. * ownership. Elasticsearch B.V. licenses this file to you under
  15. * the Apache License, Version 2.0 (the "License"); you may
  16. * not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing,
  22. * software distributed under the License is distributed on an
  23. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24. * KIND, either express or implied. See the License for the
  25. * specific language governing permissions and limitations
  26. * under the License.
  27. */
  28. 'use strict';
  29. const debug = require('debug')('opensearch');
  30. const os = require('os');
  31. const { gzip, unzip, createGzip } = require('zlib');
  32. const buffer = require('buffer');
  33. const ms = require('ms');
  34. const { EventEmitter } = require('events');
  35. const {
  36. ConnectionError,
  37. RequestAbortedError,
  38. NoLivingConnectionsError,
  39. ResponseError,
  40. ConfigurationError,
  41. } = require('./errors');
  42. const noop = () => {};
  43. const compatibleCheckEmitter = new EventEmitter();
  44. const clientVersion = require('../package.json').version;
  45. const userAgent = `opensearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${
  46. process.version
  47. })`;
  48. const MAX_BUFFER_LENGTH = buffer.constants.MAX_LENGTH;
  49. const MAX_STRING_LENGTH = buffer.constants.MAX_STRING_LENGTH;
  50. const HEAP_SIZE_LIMIT = require('v8').getHeapStatistics().heap_size_limit;
  51. const kCompatibleCheck = Symbol('compatible check');
  52. const kApiVersioning = Symbol('api versioning');
  53. /** Default Transport Layer */
  54. class Transport {
  55. constructor(opts) {
  56. if (typeof opts.compression === 'string' && opts.compression !== 'gzip') {
  57. throw new ConfigurationError(`Invalid compression: '${opts.compression}'`);
  58. }
  59. this.emit = opts.emit;
  60. this.connectionPool = opts.connectionPool;
  61. this.serializer = opts.serializer;
  62. this.maxRetries = opts.maxRetries;
  63. this.requestTimeout = toMs(opts.requestTimeout);
  64. this.suggestCompression = opts.suggestCompression === true;
  65. this.compression = opts.compression || false;
  66. this.context = opts.context || null;
  67. this.headers = Object.assign(
  68. {},
  69. { 'user-agent': userAgent },
  70. opts.suggestCompression === true ? { 'accept-encoding': 'gzip,deflate' } : null,
  71. lowerCaseHeaders(opts.headers)
  72. );
  73. this.sniffInterval = opts.sniffInterval;
  74. this.sniffOnConnectionFault = opts.sniffOnConnectionFault;
  75. this.sniffEndpoint = opts.sniffEndpoint;
  76. this.generateRequestId = opts.generateRequestId || generateRequestId();
  77. this.name = opts.name;
  78. this.opaqueIdPrefix = opts.opaqueIdPrefix;
  79. this[kCompatibleCheck] = 0; // 0 = to be checked, 1 = checking, 2 = checked-ok, 3 checked-notok
  80. this[kApiVersioning] = process.env.OPENSEARCH_CLIENT_APIVERSIONING === 'true';
  81. this.memoryCircuitBreaker = opts.memoryCircuitBreaker;
  82. this.nodeFilter = opts.nodeFilter || defaultNodeFilter;
  83. if (typeof opts.nodeSelector === 'function') {
  84. this.nodeSelector = opts.nodeSelector;
  85. } else if (opts.nodeSelector === 'round-robin') {
  86. this.nodeSelector = roundRobinSelector();
  87. } else if (opts.nodeSelector === 'random') {
  88. this.nodeSelector = randomSelector;
  89. } else {
  90. this.nodeSelector = roundRobinSelector();
  91. }
  92. this._sniffEnabled = typeof this.sniffInterval === 'number';
  93. this._nextSniff = this._sniffEnabled ? Date.now() + this.sniffInterval : 0;
  94. this._isSniffing = false;
  95. this._auth = opts.auth;
  96. if (opts.sniffOnStart === true) {
  97. // timer needed otherwise it will clash
  98. // with the compatible check testing
  99. setTimeout(() => {
  100. this.sniff({ reason: Transport.sniffReasons.SNIFF_ON_START });
  101. }, 10);
  102. }
  103. }
  104. /**
  105. * @param {Object} params
  106. * @param {string} params.method - HTTP Method (e.g. HEAD, GET, POST...)
  107. * @param {string} params.path - Relative URL path
  108. * @param {Object | string} [params.body] - Body of a standard request.
  109. * @param {Object[] | string} [params.bulkBody] - Body of a bulk request.
  110. * @param {Object[] | string} [params.querystring] - Querystring params.
  111. *
  112. * @param {Object} options
  113. * @param {number} [options.id] - Request ID
  114. * @param {Object} [options.context] - Object used for observability
  115. * @param {number} [options.maxRetries] - Max number of retries
  116. * @param {false | 'gzip'} [options.compression] - Request body compression, if any
  117. * @param {boolean} [options.asStream] - Whether to emit the response as stream
  118. * @param {number[]} [options.ignore] - Response's Error Status Codes to ignore
  119. * @param {Object} [options.headers] - Request headers
  120. * @param {Object | string} [options.querystring] - Request's query string
  121. * @param {number} [options.requestTimeout] - Max request timeout in milliseconds
  122. *
  123. * @param {function} callback - Callback that handles errors and response
  124. */
  125. request(params, options, callback) {
  126. options = options || {};
  127. if (typeof options === 'function') {
  128. callback = options;
  129. options = {};
  130. }
  131. let p = null;
  132. // promises support
  133. if (callback === undefined) {
  134. let onFulfilled = null;
  135. let onRejected = null;
  136. p = new Promise((resolve, reject) => {
  137. onFulfilled = resolve;
  138. onRejected = reject;
  139. });
  140. callback = function callback(err, result) {
  141. err ? onRejected(err) : onFulfilled(result);
  142. };
  143. }
  144. const meta = {
  145. context: null,
  146. request: {
  147. params: null,
  148. options: null,
  149. id: options.id || this.generateRequestId(params, options),
  150. },
  151. name: this.name,
  152. connection: null,
  153. attempts: 0,
  154. aborted: false,
  155. };
  156. if (this.context != null && options.context != null) {
  157. meta.context = Object.assign({}, this.context, options.context);
  158. } else if (this.context != null) {
  159. meta.context = this.context;
  160. } else if (options.context != null) {
  161. meta.context = options.context;
  162. }
  163. const result = {
  164. body: null,
  165. statusCode: null,
  166. headers: null,
  167. meta,
  168. };
  169. Object.defineProperty(result, 'warnings', {
  170. get() {
  171. return this.headers && this.headers.warning
  172. ? this.headers.warning.split(/(?!\B"[^"]*),(?![^"]*"\B)/)
  173. : null;
  174. },
  175. });
  176. // We should not retry if we are sending a stream body, because we should store in memory
  177. // a copy of the stream to be able to send it again, but since we don't know in advance
  178. // the size of the stream, we risk to take too much memory.
  179. // Furthermore, copying everytime the stream is very a expensive operation.
  180. const maxRetries =
  181. isStream(params.body) || isStream(params.bulkBody)
  182. ? 0
  183. : typeof options.maxRetries === 'number'
  184. ? options.maxRetries
  185. : this.maxRetries;
  186. const compression = options.compression !== undefined ? options.compression : this.compression;
  187. let request = { abort: noop };
  188. const transportReturn = {
  189. then(onFulfilled, onRejected) {
  190. if (p != null) {
  191. return p.then(onFulfilled, onRejected);
  192. }
  193. },
  194. catch(onRejected) {
  195. if (p != null) {
  196. return p.catch(onRejected);
  197. }
  198. },
  199. abort() {
  200. meta.aborted = true;
  201. request.abort();
  202. debug('Aborting request', params);
  203. return this;
  204. },
  205. finally(onFinally) {
  206. if (p != null) {
  207. return p.finally(onFinally);
  208. }
  209. },
  210. };
  211. const makeRequest = () => {
  212. if (meta.aborted === true) {
  213. return process.nextTick(callback, new RequestAbortedError(), result);
  214. }
  215. meta.connection = this.getConnection({ requestId: meta.request.id });
  216. if (meta.connection == null) {
  217. return process.nextTick(callback, new NoLivingConnectionsError(), result);
  218. }
  219. this.emit('request', null, result);
  220. // perform the actual http request
  221. request = meta.connection.request(params, onResponse);
  222. };
  223. const onConnectionError = (err) => {
  224. if (err.name !== 'RequestAbortedError') {
  225. // if there is an error in the connection
  226. // let's mark the connection as dead
  227. this.connectionPool.markDead(meta.connection);
  228. if (this.sniffOnConnectionFault === true) {
  229. this.sniff({
  230. reason: Transport.sniffReasons.SNIFF_ON_CONNECTION_FAULT,
  231. requestId: meta.request.id,
  232. });
  233. }
  234. // retry logic
  235. if (meta.attempts < maxRetries) {
  236. meta.attempts++;
  237. debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
  238. makeRequest();
  239. return;
  240. }
  241. }
  242. err.meta = result;
  243. this.emit('response', err, result);
  244. return callback(err, result);
  245. };
  246. const onResponse = (err, response) => {
  247. if (err !== null) {
  248. return onConnectionError(err);
  249. }
  250. result.statusCode = response.statusCode;
  251. result.headers = response.headers;
  252. if (options.asStream === true) {
  253. result.body = response;
  254. this.emit('response', null, result);
  255. callback(null, result);
  256. return;
  257. }
  258. const contentEncoding = (result.headers['content-encoding'] || '').toLowerCase();
  259. const isCompressed =
  260. contentEncoding.indexOf('gzip') > -1 || contentEncoding.indexOf('deflate') > -1;
  261. /* istanbul ignore else */
  262. if (result.headers['content-length'] !== undefined) {
  263. const contentLength = Number(result.headers['content-length']);
  264. // nodeJS data type limit check
  265. if (isCompressed && contentLength > MAX_BUFFER_LENGTH) {
  266. response.destroy();
  267. return onConnectionError(
  268. new RequestAbortedError(
  269. `The content length (${contentLength}) is bigger than the maximum allowed buffer (${MAX_BUFFER_LENGTH})`,
  270. result
  271. )
  272. );
  273. } else if (contentLength > MAX_STRING_LENGTH) {
  274. response.destroy();
  275. return onConnectionError(
  276. new RequestAbortedError(
  277. `The content length (${contentLength}) is bigger than the maximum allowed string (${MAX_STRING_LENGTH})`,
  278. result
  279. )
  280. );
  281. } else if (shouldApplyCircuitBreaker(contentLength)) {
  282. // Abort this response to avoid OOM crash of dashboards.
  283. response.destroy();
  284. return onConnectionError(
  285. new RequestAbortedError(
  286. `The content length (${contentLength}) is bigger than the maximum allowed heap memory limit.`,
  287. result
  288. )
  289. );
  290. }
  291. }
  292. // if the response is compressed, we must handle it
  293. // as buffer for allowing decompression later
  294. let payload = isCompressed ? [] : '';
  295. const onData = isCompressed
  296. ? (chunk) => {
  297. payload.push(chunk);
  298. }
  299. : (chunk) => {
  300. payload += chunk;
  301. };
  302. const onEnd = (err) => {
  303. response.removeListener('data', onData);
  304. response.removeListener('end', onEnd);
  305. response.removeListener('error', onEnd);
  306. response.removeListener('aborted', onAbort);
  307. if (err) {
  308. return onConnectionError(new ConnectionError(err.message));
  309. }
  310. if (isCompressed) {
  311. unzip(Buffer.concat(payload), onBody);
  312. } else {
  313. onBody(null, payload);
  314. }
  315. };
  316. const onAbort = () => {
  317. response.destroy();
  318. onEnd(new Error('Response aborted while reading the body'));
  319. };
  320. if (!isCompressed) {
  321. response.setEncoding('utf8');
  322. }
  323. this.emit('deserialization', null, result);
  324. response.on('data', onData);
  325. response.on('error', onEnd);
  326. response.on('end', onEnd);
  327. response.on('aborted', onAbort);
  328. };
  329. // Helper function to check if memory circuit breaker enabled and the response payload is too large to fit into available heap memory.
  330. const shouldApplyCircuitBreaker = (contentLength) => {
  331. if (!this.memoryCircuitBreaker || !this.memoryCircuitBreaker.enabled) return false;
  332. const maxPercentage = validateMemoryPercentage(this.memoryCircuitBreaker.maxPercentage);
  333. const heapUsed = process.memoryUsage().heapUsed;
  334. return contentLength + heapUsed > HEAP_SIZE_LIMIT * maxPercentage;
  335. };
  336. const onBody = (err, payload) => {
  337. if (err) {
  338. this.emit('response', err, result);
  339. return callback(err, result);
  340. }
  341. if (Buffer.isBuffer(payload)) {
  342. payload = payload.toString();
  343. }
  344. const isHead = params.method === 'HEAD';
  345. // we should attempt the payload deserialization only if:
  346. // - a `content-type` is defined and is equal to `application/json`
  347. // - the request is not a HEAD request
  348. // - the payload is not an empty string
  349. if (
  350. result.headers['content-type'] !== undefined &&
  351. (result.headers['content-type'].indexOf('application/json') > -1 ||
  352. result.headers['content-type'].indexOf('application/vnd.opensearch+json') > -1) &&
  353. isHead === false &&
  354. payload !== ''
  355. ) {
  356. try {
  357. result.body = this.serializer.deserialize(payload);
  358. } catch (err) {
  359. this.emit('response', err, result);
  360. return callback(err, result);
  361. }
  362. } else {
  363. // cast to boolean if the request method was HEAD and there was no error
  364. result.body = isHead === true && result.statusCode < 400 ? true : payload;
  365. }
  366. // we should ignore the statusCode if the user has configured the `ignore` field with
  367. // the statusCode we just got or if the request method is HEAD and the statusCode is 404
  368. const ignoreStatusCode =
  369. (Array.isArray(options.ignore) && options.ignore.indexOf(result.statusCode) > -1) ||
  370. (isHead === true && result.statusCode === 404);
  371. if (
  372. ignoreStatusCode === false &&
  373. (result.statusCode === 502 || result.statusCode === 503 || result.statusCode === 504)
  374. ) {
  375. // if the statusCode is 502/3/4 we should run our retry strategy
  376. // and mark the connection as dead
  377. this.connectionPool.markDead(meta.connection);
  378. // retry logic (we should not retry on "429 - Too Many Requests")
  379. if (meta.attempts < maxRetries && result.statusCode !== 429) {
  380. meta.attempts++;
  381. debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
  382. makeRequest();
  383. return;
  384. }
  385. } else {
  386. // everything has worked as expected, let's mark
  387. // the connection as alive (or confirm it)
  388. this.connectionPool.markAlive(meta.connection);
  389. }
  390. if (ignoreStatusCode === false && result.statusCode >= 400) {
  391. const error = new ResponseError(result);
  392. this.emit('response', error, result);
  393. callback(error, result);
  394. } else {
  395. // cast to boolean if the request method was HEAD
  396. if (isHead === true && result.statusCode === 404) {
  397. result.body = false;
  398. }
  399. this.emit('response', null, result);
  400. callback(null, result);
  401. }
  402. };
  403. const prepareRequest = () => {
  404. this.emit('serialization', null, result);
  405. const headers = Object.assign({}, this.headers, lowerCaseHeaders(options.headers));
  406. if (options.opaqueId !== undefined) {
  407. headers['x-opaque-id'] =
  408. this.opaqueIdPrefix !== null ? this.opaqueIdPrefix + options.opaqueId : options.opaqueId;
  409. }
  410. // handle json body
  411. if (params.body != null) {
  412. if (shouldSerialize(params.body) === true) {
  413. try {
  414. params.body = this.serializer.serialize(params.body);
  415. } catch (err) {
  416. this.emit('request', err, result);
  417. process.nextTick(callback, err, result);
  418. return transportReturn;
  419. }
  420. }
  421. if (params.body !== '') {
  422. headers['content-type'] =
  423. headers['content-type'] ||
  424. (this[kApiVersioning]
  425. ? 'application/vnd.opensearch+json; compatible-with=7'
  426. : 'application/json');
  427. }
  428. // handle ndjson body
  429. } else if (params.bulkBody != null) {
  430. if (shouldSerialize(params.bulkBody) === true) {
  431. try {
  432. params.body = this.serializer.ndserialize(params.bulkBody);
  433. } catch (err) {
  434. this.emit('request', err, result);
  435. process.nextTick(callback, err, result);
  436. return transportReturn;
  437. }
  438. } else {
  439. params.body = params.bulkBody;
  440. }
  441. if (params.body !== '') {
  442. headers['content-type'] =
  443. headers['content-type'] ||
  444. (this[kApiVersioning]
  445. ? 'application/vnd.opensearch+x-ndjson; compatible-with=7'
  446. : 'application/x-ndjson');
  447. }
  448. }
  449. params.headers = headers;
  450. // serializes the querystring
  451. if (options.querystring == null) {
  452. params.querystring = this.serializer.qserialize(params.querystring);
  453. } else {
  454. params.querystring = this.serializer.qserialize(
  455. Object.assign({}, params.querystring, options.querystring)
  456. );
  457. }
  458. if (this._auth !== null && typeof this._auth === 'object' && 'credentials' in this._auth) {
  459. params.auth = this._auth;
  460. }
  461. // handles request timeout
  462. params.timeout = toMs(options.requestTimeout || this.requestTimeout);
  463. if (options.asStream === true) params.asStream = true;
  464. meta.request.params = params;
  465. meta.request.options = options;
  466. // handle compression
  467. if (params.body !== '' && params.body != null) {
  468. if (isStream(params.body) === true) {
  469. if (compression === 'gzip') {
  470. params.headers['content-encoding'] = compression;
  471. params.body = params.body.pipe(createGzip());
  472. }
  473. makeRequest();
  474. } else if (compression === 'gzip') {
  475. gzip(params.body, (err, buffer) => {
  476. /* istanbul ignore next */
  477. if (err) {
  478. this.emit('request', err, result);
  479. return callback(err, result);
  480. }
  481. params.headers['content-encoding'] = compression;
  482. params.headers['content-length'] = '' + Buffer.byteLength(buffer);
  483. params.body = buffer;
  484. makeRequest();
  485. });
  486. } else {
  487. params.headers['content-length'] = '' + Buffer.byteLength(params.body);
  488. makeRequest();
  489. }
  490. } else {
  491. makeRequest();
  492. }
  493. };
  494. prepareRequest();
  495. return transportReturn;
  496. }
  497. getConnection(opts) {
  498. const now = Date.now();
  499. if (this._sniffEnabled === true && now > this._nextSniff) {
  500. this.sniff({ reason: Transport.sniffReasons.SNIFF_INTERVAL, requestId: opts.requestId });
  501. }
  502. return this.connectionPool.getConnection({
  503. filter: this.nodeFilter,
  504. selector: this.nodeSelector,
  505. requestId: opts.requestId,
  506. name: this.name,
  507. now,
  508. });
  509. }
  510. sniff(opts, callback = noop) {
  511. if (this._isSniffing === true) return;
  512. this._isSniffing = true;
  513. debug('Started sniffing request');
  514. if (typeof opts === 'function') {
  515. callback = opts;
  516. opts = { reason: Transport.sniffReasons.DEFAULT };
  517. }
  518. const { reason } = opts;
  519. const request = {
  520. method: 'GET',
  521. path: this.sniffEndpoint,
  522. };
  523. this.request(request, { id: opts.requestId }, (err, result) => {
  524. this._isSniffing = false;
  525. if (this._sniffEnabled === true) {
  526. this._nextSniff = Date.now() + this.sniffInterval;
  527. }
  528. if (err != null) {
  529. debug('Sniffing errored', err);
  530. result.meta.sniff = { hosts: [], reason };
  531. this.emit('sniff', err, result);
  532. return callback(err);
  533. }
  534. debug('Sniffing ended successfully', result.body);
  535. const protocol = result.meta.connection.url.protocol || /* istanbul ignore next */ 'http:';
  536. const hosts = this.connectionPool.nodesToHost(result.body.nodes, protocol);
  537. this.connectionPool.update(hosts);
  538. result.meta.sniff = { hosts, reason };
  539. this.emit('sniff', null, result);
  540. callback(null, hosts);
  541. });
  542. }
  543. // checkCompatibleInfo validates whether the informations are compatible
  544. checkCompatibleInfo() {
  545. debug('Start compatible check');
  546. this[kCompatibleCheck] = 1;
  547. this.request(
  548. {
  549. method: 'GET',
  550. path: '/',
  551. },
  552. (err, result) => {
  553. this[kCompatibleCheck] = 3;
  554. if (err) {
  555. debug('compatible check failed', err);
  556. if (err.statusCode === 401 || err.statusCode === 403) {
  557. this[kCompatibleCheck] = 2;
  558. process.emitWarning(
  559. 'The client is unable to verify the distribution due to security privileges on the server side. Some functionality may not be compatible if the server is running an unsupported product.'
  560. );
  561. compatibleCheckEmitter.emit('compatible-check', true);
  562. } else {
  563. this[kCompatibleCheck] = 0;
  564. compatibleCheckEmitter.emit('compatible-check', false);
  565. }
  566. } else {
  567. debug('Checking OpenSearch version', result.body, result.headers);
  568. if (result.body.version == null || typeof result.body.version.number !== 'string') {
  569. debug("Can't access OpenSearch version");
  570. return compatibleCheckEmitter.emit('compatible-check', false);
  571. }
  572. const distribution = result.body.version.distribution;
  573. const version = result.body.version.number.split('.');
  574. const major = Number(version[0]);
  575. // support OpenSearch validation
  576. if (distribution === 'opensearch') {
  577. debug('Valid OpenSearch distribution');
  578. this[kCompatibleCheck] = 2;
  579. return compatibleCheckEmitter.emit('compatible-check', true);
  580. }
  581. // support odfe > v7 validation
  582. if (major !== 7) {
  583. debug('Invalid distribution');
  584. return compatibleCheckEmitter.emit('compatible-check', false);
  585. }
  586. debug('Valid OpenSearch distribution');
  587. this[kCompatibleCheck] = 2;
  588. compatibleCheckEmitter.emit('compatible-check', true);
  589. }
  590. }
  591. );
  592. }
  593. }
  594. Transport.sniffReasons = {
  595. SNIFF_ON_START: 'sniff-on-start',
  596. SNIFF_INTERVAL: 'sniff-interval',
  597. SNIFF_ON_CONNECTION_FAULT: 'sniff-on-connection-fault',
  598. // TODO: find a better name
  599. DEFAULT: 'default',
  600. };
  601. function toMs(time) {
  602. if (typeof time === 'string') {
  603. return ms(time);
  604. }
  605. return time;
  606. }
  607. function shouldSerialize(obj) {
  608. return (
  609. typeof obj !== 'string' && typeof obj.pipe !== 'function' && Buffer.isBuffer(obj) === false
  610. );
  611. }
  612. function isStream(obj) {
  613. return obj != null && typeof obj.pipe === 'function';
  614. }
  615. function defaultNodeFilter(node) {
  616. // avoid cluster_manager or master only nodes
  617. // TODO: remove role check on master when master is not supported
  618. if (
  619. (node.roles.cluster_manager === true || node.roles.master === true) &&
  620. node.roles.data === false &&
  621. node.roles.ingest === false
  622. ) {
  623. return false;
  624. }
  625. return true;
  626. }
  627. function roundRobinSelector() {
  628. let current = -1;
  629. return function _roundRobinSelector(connections) {
  630. if (++current >= connections.length) {
  631. current = 0;
  632. }
  633. return connections[current];
  634. };
  635. }
  636. function randomSelector(connections) {
  637. const index = Math.floor(Math.random() * connections.length);
  638. return connections[index];
  639. }
  640. function generateRequestId() {
  641. const maxInt = 2147483647;
  642. let nextReqId = 0;
  643. return function genReqId() {
  644. return (nextReqId = (nextReqId + 1) & maxInt);
  645. };
  646. }
  647. function lowerCaseHeaders(oldHeaders) {
  648. if (oldHeaders == null) return oldHeaders;
  649. const newHeaders = {};
  650. for (const header in oldHeaders) {
  651. newHeaders[header.toLowerCase()] = oldHeaders[header];
  652. }
  653. return newHeaders;
  654. }
  655. function validateMemoryPercentage(percentage) {
  656. if (percentage < 0 || percentage > 1) return 1.0;
  657. return percentage;
  658. }
  659. module.exports = Transport;
  660. module.exports.internals = {
  661. defaultNodeFilter,
  662. roundRobinSelector,
  663. randomSelector,
  664. generateRequestId,
  665. lowerCaseHeaders,
  666. toMs,
  667. };