monitor.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.MonitorInterval = exports.RTTPinger = exports.Monitor = void 0;
  4. const timers_1 = require("timers");
  5. const bson_1 = require("../bson");
  6. const connect_1 = require("../cmap/connect");
  7. const connection_1 = require("../cmap/connection");
  8. const constants_1 = require("../constants");
  9. const error_1 = require("../error");
  10. const mongo_types_1 = require("../mongo_types");
  11. const utils_1 = require("../utils");
  12. const common_1 = require("./common");
  13. const events_1 = require("./events");
  14. const server_1 = require("./server");
  15. /** @internal */
  16. const kServer = Symbol('server');
  17. /** @internal */
  18. const kMonitorId = Symbol('monitorId');
  19. /** @internal */
  20. const kConnection = Symbol('connection');
  21. /** @internal */
  22. const kCancellationToken = Symbol('cancellationToken');
  23. /** @internal */
  24. const kRTTPinger = Symbol('rttPinger');
  25. /** @internal */
  26. const kRoundTripTime = Symbol('roundTripTime');
  27. const STATE_IDLE = 'idle';
  28. const STATE_MONITORING = 'monitoring';
  29. const stateTransition = (0, utils_1.makeStateMachine)({
  30. [common_1.STATE_CLOSING]: [common_1.STATE_CLOSING, STATE_IDLE, common_1.STATE_CLOSED],
  31. [common_1.STATE_CLOSED]: [common_1.STATE_CLOSED, STATE_MONITORING],
  32. [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, common_1.STATE_CLOSING],
  33. [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, common_1.STATE_CLOSING]
  34. });
  35. const INVALID_REQUEST_CHECK_STATES = new Set([common_1.STATE_CLOSING, common_1.STATE_CLOSED, STATE_MONITORING]);
  36. function isInCloseState(monitor) {
  37. return monitor.s.state === common_1.STATE_CLOSED || monitor.s.state === common_1.STATE_CLOSING;
  38. }
  39. /** @internal */
  40. class Monitor extends mongo_types_1.TypedEventEmitter {
  41. get connection() {
  42. return this[kConnection];
  43. }
  44. constructor(server, options) {
  45. super();
  46. this[kServer] = server;
  47. this[kConnection] = undefined;
  48. this[kCancellationToken] = new mongo_types_1.CancellationToken();
  49. this[kCancellationToken].setMaxListeners(Infinity);
  50. this[kMonitorId] = undefined;
  51. this.s = {
  52. state: common_1.STATE_CLOSED
  53. };
  54. this.address = server.description.address;
  55. this.options = Object.freeze({
  56. connectTimeoutMS: options.connectTimeoutMS ?? 10000,
  57. heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000,
  58. minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500
  59. });
  60. const cancellationToken = this[kCancellationToken];
  61. // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration
  62. const connectOptions = Object.assign({
  63. id: '<monitor>',
  64. generation: server.pool.generation,
  65. connectionType: connection_1.Connection,
  66. cancellationToken,
  67. hostAddress: server.description.hostAddress
  68. }, options,
  69. // force BSON serialization options
  70. {
  71. raw: false,
  72. useBigInt64: false,
  73. promoteLongs: true,
  74. promoteValues: true,
  75. promoteBuffers: true
  76. });
  77. // ensure no authentication is used for monitoring
  78. delete connectOptions.credentials;
  79. if (connectOptions.autoEncrypter) {
  80. delete connectOptions.autoEncrypter;
  81. }
  82. this.connectOptions = Object.freeze(connectOptions);
  83. }
  84. connect() {
  85. if (this.s.state !== common_1.STATE_CLOSED) {
  86. return;
  87. }
  88. // start
  89. const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
  90. const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
  91. this[kMonitorId] = new MonitorInterval(monitorServer(this), {
  92. heartbeatFrequencyMS: heartbeatFrequencyMS,
  93. minHeartbeatFrequencyMS: minHeartbeatFrequencyMS,
  94. immediate: true
  95. });
  96. }
  97. requestCheck() {
  98. if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {
  99. return;
  100. }
  101. this[kMonitorId]?.wake();
  102. }
  103. reset() {
  104. const topologyVersion = this[kServer].description.topologyVersion;
  105. if (isInCloseState(this) || topologyVersion == null) {
  106. return;
  107. }
  108. stateTransition(this, common_1.STATE_CLOSING);
  109. resetMonitorState(this);
  110. // restart monitor
  111. stateTransition(this, STATE_IDLE);
  112. // restart monitoring
  113. const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
  114. const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
  115. this[kMonitorId] = new MonitorInterval(monitorServer(this), {
  116. heartbeatFrequencyMS: heartbeatFrequencyMS,
  117. minHeartbeatFrequencyMS: minHeartbeatFrequencyMS
  118. });
  119. }
  120. close() {
  121. if (isInCloseState(this)) {
  122. return;
  123. }
  124. stateTransition(this, common_1.STATE_CLOSING);
  125. resetMonitorState(this);
  126. // close monitor
  127. this.emit('close');
  128. stateTransition(this, common_1.STATE_CLOSED);
  129. }
  130. }
  131. exports.Monitor = Monitor;
  132. function resetMonitorState(monitor) {
  133. monitor[kMonitorId]?.stop();
  134. monitor[kMonitorId] = undefined;
  135. monitor[kRTTPinger]?.close();
  136. monitor[kRTTPinger] = undefined;
  137. monitor[kCancellationToken].emit('cancel');
  138. monitor[kConnection]?.destroy({ force: true });
  139. monitor[kConnection] = undefined;
  140. }
  141. function checkServer(monitor, callback) {
  142. let start = (0, utils_1.now)();
  143. monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address));
  144. function failureHandler(err) {
  145. monitor[kConnection]?.destroy({ force: true });
  146. monitor[kConnection] = undefined;
  147. monitor.emit(server_1.Server.SERVER_HEARTBEAT_FAILED, new events_1.ServerHeartbeatFailedEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), err));
  148. const error = !(err instanceof error_1.MongoError) ? new error_1.MongoError(err) : err;
  149. error.addErrorLabel(error_1.MongoErrorLabel.ResetPool);
  150. if (error instanceof error_1.MongoNetworkTimeoutError) {
  151. error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections);
  152. }
  153. monitor.emit('resetServer', error);
  154. callback(err);
  155. }
  156. const connection = monitor[kConnection];
  157. if (connection && !connection.closed) {
  158. const { serverApi, helloOk } = connection;
  159. const connectTimeoutMS = monitor.options.connectTimeoutMS;
  160. const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;
  161. const topologyVersion = monitor[kServer].description.topologyVersion;
  162. const isAwaitable = topologyVersion != null;
  163. const cmd = {
  164. [serverApi?.version || helloOk ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: 1,
  165. ...(isAwaitable && topologyVersion
  166. ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) }
  167. : {})
  168. };
  169. const options = isAwaitable
  170. ? {
  171. socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0,
  172. exhaustAllowed: true
  173. }
  174. : { socketTimeoutMS: connectTimeoutMS };
  175. if (isAwaitable && monitor[kRTTPinger] == null) {
  176. monitor[kRTTPinger] = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions));
  177. }
  178. connection.command((0, utils_1.ns)('admin.$cmd'), cmd, options, (err, hello) => {
  179. if (err) {
  180. return failureHandler(err);
  181. }
  182. if (!('isWritablePrimary' in hello)) {
  183. // Provide hello-style response document.
  184. hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND];
  185. }
  186. const rttPinger = monitor[kRTTPinger];
  187. const duration = isAwaitable && rttPinger ? rttPinger.roundTripTime : (0, utils_1.calculateDurationInMs)(start);
  188. monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello));
  189. // if we are using the streaming protocol then we immediately issue another `started`
  190. // event, otherwise the "check" is complete and return to the main monitor loop
  191. if (isAwaitable && hello.topologyVersion) {
  192. monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address));
  193. start = (0, utils_1.now)();
  194. }
  195. else {
  196. monitor[kRTTPinger]?.close();
  197. monitor[kRTTPinger] = undefined;
  198. callback(undefined, hello);
  199. }
  200. });
  201. return;
  202. }
  203. // connecting does an implicit `hello`
  204. (0, connect_1.connect)(monitor.connectOptions, (err, conn) => {
  205. if (err) {
  206. monitor[kConnection] = undefined;
  207. failureHandler(err);
  208. return;
  209. }
  210. if (conn) {
  211. // Tell the connection that we are using the streaming protocol so that the
  212. // connection's message stream will only read the last hello on the buffer.
  213. conn.isMonitoringConnection = true;
  214. if (isInCloseState(monitor)) {
  215. conn.destroy({ force: true });
  216. return;
  217. }
  218. monitor[kConnection] = conn;
  219. monitor.emit(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), conn.hello));
  220. callback(undefined, conn.hello);
  221. }
  222. });
  223. }
  224. function monitorServer(monitor) {
  225. return (callback) => {
  226. if (monitor.s.state === STATE_MONITORING) {
  227. process.nextTick(callback);
  228. return;
  229. }
  230. stateTransition(monitor, STATE_MONITORING);
  231. function done() {
  232. if (!isInCloseState(monitor)) {
  233. stateTransition(monitor, STATE_IDLE);
  234. }
  235. callback();
  236. }
  237. checkServer(monitor, (err, hello) => {
  238. if (err) {
  239. // otherwise an error occurred on initial discovery, also bail
  240. if (monitor[kServer].description.type === common_1.ServerType.Unknown) {
  241. return done();
  242. }
  243. }
  244. // if the check indicates streaming is supported, immediately reschedule monitoring
  245. if (hello && hello.topologyVersion) {
  246. (0, timers_1.setTimeout)(() => {
  247. if (!isInCloseState(monitor)) {
  248. monitor[kMonitorId]?.wake();
  249. }
  250. }, 0);
  251. }
  252. done();
  253. });
  254. };
  255. }
  256. function makeTopologyVersion(tv) {
  257. return {
  258. processId: tv.processId,
  259. // tests mock counter as just number, but in a real situation counter should always be a Long
  260. // TODO(NODE-2674): Preserve int64 sent from MongoDB
  261. counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter)
  262. };
  263. }
  264. /** @internal */
  265. class RTTPinger {
  266. constructor(cancellationToken, options) {
  267. this[kConnection] = undefined;
  268. this[kCancellationToken] = cancellationToken;
  269. this[kRoundTripTime] = 0;
  270. this.closed = false;
  271. const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
  272. this[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(this, options), heartbeatFrequencyMS);
  273. }
  274. get roundTripTime() {
  275. return this[kRoundTripTime];
  276. }
  277. close() {
  278. this.closed = true;
  279. (0, timers_1.clearTimeout)(this[kMonitorId]);
  280. this[kConnection]?.destroy({ force: true });
  281. this[kConnection] = undefined;
  282. }
  283. }
  284. exports.RTTPinger = RTTPinger;
  285. function measureRoundTripTime(rttPinger, options) {
  286. const start = (0, utils_1.now)();
  287. options.cancellationToken = rttPinger[kCancellationToken];
  288. const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
  289. if (rttPinger.closed) {
  290. return;
  291. }
  292. function measureAndReschedule(conn) {
  293. if (rttPinger.closed) {
  294. conn?.destroy({ force: true });
  295. return;
  296. }
  297. if (rttPinger[kConnection] == null) {
  298. rttPinger[kConnection] = conn;
  299. }
  300. rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start);
  301. rttPinger[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS);
  302. }
  303. const connection = rttPinger[kConnection];
  304. if (connection == null) {
  305. (0, connect_1.connect)(options, (err, conn) => {
  306. if (err) {
  307. rttPinger[kConnection] = undefined;
  308. rttPinger[kRoundTripTime] = 0;
  309. return;
  310. }
  311. measureAndReschedule(conn);
  312. });
  313. return;
  314. }
  315. connection.command((0, utils_1.ns)('admin.$cmd'), { [constants_1.LEGACY_HELLO_COMMAND]: 1 }, undefined, err => {
  316. if (err) {
  317. rttPinger[kConnection] = undefined;
  318. rttPinger[kRoundTripTime] = 0;
  319. return;
  320. }
  321. measureAndReschedule();
  322. });
  323. }
  324. /**
  325. * @internal
  326. */
  327. class MonitorInterval {
  328. constructor(fn, options = {}) {
  329. this.isExpeditedCallToFnScheduled = false;
  330. this.stopped = false;
  331. this.isExecutionInProgress = false;
  332. this.hasExecutedOnce = false;
  333. this._executeAndReschedule = () => {
  334. if (this.stopped)
  335. return;
  336. if (this.timerId) {
  337. (0, timers_1.clearTimeout)(this.timerId);
  338. }
  339. this.isExpeditedCallToFnScheduled = false;
  340. this.isExecutionInProgress = true;
  341. this.fn(() => {
  342. this.lastExecutionEnded = (0, utils_1.now)();
  343. this.isExecutionInProgress = false;
  344. this._reschedule(this.heartbeatFrequencyMS);
  345. });
  346. };
  347. this.fn = fn;
  348. this.lastExecutionEnded = -Infinity;
  349. this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000;
  350. this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500;
  351. if (options.immediate) {
  352. this._executeAndReschedule();
  353. }
  354. else {
  355. this._reschedule(undefined);
  356. }
  357. }
  358. wake() {
  359. const currentTime = (0, utils_1.now)();
  360. const timeSinceLastCall = currentTime - this.lastExecutionEnded;
  361. // TODO(NODE-4674): Add error handling and logging to the monitor
  362. if (timeSinceLastCall < 0) {
  363. return this._executeAndReschedule();
  364. }
  365. if (this.isExecutionInProgress) {
  366. return;
  367. }
  368. // debounce multiple calls to wake within the `minInterval`
  369. if (this.isExpeditedCallToFnScheduled) {
  370. return;
  371. }
  372. // reschedule a call as soon as possible, ensuring the call never happens
  373. // faster than the `minInterval`
  374. if (timeSinceLastCall < this.minHeartbeatFrequencyMS) {
  375. this.isExpeditedCallToFnScheduled = true;
  376. this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall);
  377. return;
  378. }
  379. this._executeAndReschedule();
  380. }
  381. stop() {
  382. this.stopped = true;
  383. if (this.timerId) {
  384. (0, timers_1.clearTimeout)(this.timerId);
  385. this.timerId = undefined;
  386. }
  387. this.lastExecutionEnded = -Infinity;
  388. this.isExpeditedCallToFnScheduled = false;
  389. }
  390. toString() {
  391. return JSON.stringify(this);
  392. }
  393. toJSON() {
  394. const currentTime = (0, utils_1.now)();
  395. const timeSinceLastCall = currentTime - this.lastExecutionEnded;
  396. return {
  397. timerId: this.timerId != null ? 'set' : 'cleared',
  398. lastCallTime: this.lastExecutionEnded,
  399. isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled,
  400. stopped: this.stopped,
  401. heartbeatFrequencyMS: this.heartbeatFrequencyMS,
  402. minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS,
  403. currentTime,
  404. timeSinceLastCall
  405. };
  406. }
  407. _reschedule(ms) {
  408. if (this.stopped)
  409. return;
  410. if (this.timerId) {
  411. (0, timers_1.clearTimeout)(this.timerId);
  412. }
  413. this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS);
  414. }
  415. }
  416. exports.MonitorInterval = MonitorInterval;
  417. //# sourceMappingURL=monitor.js.map