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