All files / src/sdam monitor.ts

96.09% Statements 271/282
90.57% Branches 125/138
92.3% Functions 48/52
96.64% Lines 259/268

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772139x   139x 139x   139x 139x 139x 139x 139x 139x                 139x 139x         139x     139x 139x 139x             139x   2321865x       139x                                                                   139x                                           578946x         578946x 578946x   578946x 578946x 578946x 578946x 578946x 578946x     578946x 578946x           578946x 578946x 578946x   578946x   578946x                             578946x 578946x 14502x     578946x       573515x 1x       573514x 573514x 573514x               518371x 457466x     60905x       46086x 46086x 39303x     6783x 6783x     6783x     6783x 6783x 6783x             574682x 1172x     573510x 573510x     573510x 573510x       608704x       608702x       28887x       608720x       580293x         580293x 580293x   580293x 580293x   580293x   580293x 580293x   580293x             1827935x   1039550x 1039550x 1017185x       1016712x 1016184x           634828x 634828x 634828x               39008x 39008x 39008x             39008x     39008x 39008x 356x     39008x 39008x       39073x   2967x             39073x       39073x   39073x             39073x     13962x               13962x   25111x 25111x   25111x       634828x 634828x 54150x 54150x 54150x   54150x             54150x             54150x 28887x       54150x   54150x 28963x 28963x 42925x 13962x       25187x 25187x       25187x       580678x 580678x 571970x   571970x 571970x 571970x 570709x   1261x 1261x       570709x 1062x 1062x   569647x 569647x   569647x 569647x                       569647x     9969x 9969x 9969x           580297x 634828x       634828x   633766x 598213x     633766x     634828x 633766x   39008x 10306x         623460x 496622x 496622x 474469x         623460x           28963x                           139x                         28887x 28887x 28887x 28887x 28887x   28887x 28887x                       28887x 28887x   28887x 28887x       12578x 3x 3x     12575x 1497x     12575x 12575x 11197x           12845x   12845x       12845x 12845x 1648x   1500x     148x     1648x       11197x   11197x 11078x   119x 119x 119x                                         139x       580357x 580357x 580357x 580357x           580357x 580357x   580357x 580357x   580357x 573518x   6839x         535434x 535434x     535434x 8x     535426x 28x       535398x 49256x         486142x 481840x 481840x 481840x     4302x       580365x 580365x 572461x 572461x     580365x 580365x                                             1122537x 1086839x 514378x     1086839x     580357x 634924x 634924x 61406x     634924x 634924x   634924x 633858x 633858x 633858x                     139x             578994x 578994x 578994x                 609116x 609116x 585277x     609116x               608718x 39256x 39256x 249440x     39256x             608708x 608708x 608708x 858148x     608708x               28899x 28895x                 580297x 580297x      
import { clearTimeout, setTimeout } from 'timers';
 
import { type Document, Long } from '../bson';
import { connect, makeConnection, makeSocket, performInitialHandshake } from '../cmap/connect';
import type { Connection, ConnectionOptions } from '../cmap/connection';
import { getFAASEnv } from '../cmap/handshake/client_metadata';
import { LEGACY_HELLO_COMMAND } from '../constants';
import { MongoError, MongoErrorLabel, MongoNetworkTimeoutError } from '../error';
import { MongoLoggableComponent } from '../mongo_logger';
import { CancellationToken, TypedEventEmitter } from '../mongo_types';
import {
  calculateDurationInMs,
  type Callback,
  type EventEmitterWithState,
  makeStateMachine,
  noop,
  now,
  ns
} from '../utils';
import { ServerType, STATE_CLOSED, STATE_CLOSING } from './common';
import {
  ServerHeartbeatFailedEvent,
  ServerHeartbeatStartedEvent,
  ServerHeartbeatSucceededEvent
} from './events';
import { Server } from './server';
import type { TopologyVersion } from './server_description';
 
const STATE_IDLE = 'idle';
const STATE_MONITORING = 'monitoring';
const stateTransition = makeStateMachine({
  [STATE_CLOSING]: [STATE_CLOSING, STATE_IDLE, STATE_CLOSED],
  [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING],
  [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING],
  [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING]
});
 
const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]);
function isInCloseState(monitor: Monitor) {
  return monitor.s.state === STATE_CLOSED || monitor.s.state === STATE_CLOSING;
}
 
/** @public */
export const ServerMonitoringMode = Object.freeze({
  auto: 'auto',
  poll: 'poll',
  stream: 'stream'
} as const);
 
/** @public */
export type ServerMonitoringMode = (typeof ServerMonitoringMode)[keyof typeof ServerMonitoringMode];
 
/** @internal */
export interface MonitorPrivate {
  state: string;
}
 
/** @public */
export interface MonitorOptions
  extends Omit<ConnectionOptions, 'id' | 'generation' | 'hostAddress'> {
  connectTimeoutMS: number;
  heartbeatFrequencyMS: number;
  minHeartbeatFrequencyMS: number;
  serverMonitoringMode: ServerMonitoringMode;
}
 
/** @public */
export type MonitorEvents = {
  serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
  serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
  serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
  resetServer(error?: MongoError): void;
  resetConnectionPool(): void;
  close(): void;
} & EventEmitterWithState;
 
/** @internal */
export class Monitor extends TypedEventEmitter<MonitorEvents> {
  /** @internal */
  s: MonitorPrivate;
  address: string;
  options: Readonly<
    Pick<
      MonitorOptions,
      | 'connectTimeoutMS'
      | 'heartbeatFrequencyMS'
      | 'minHeartbeatFrequencyMS'
      | 'serverMonitoringMode'
    >
  >;
  connectOptions: ConnectionOptions;
  isRunningInFaasEnv: boolean;
  server: Server;
  connection: Connection | null;
  cancellationToken: CancellationToken;
  /** @internal */
  monitorId?: MonitorInterval;
  rttPinger?: RTTPinger;
  /** @internal */
  override component = MongoLoggableComponent.TOPOLOGY;
  /** @internal */
  private rttSampler: RTTSampler;
 
  constructor(server: Server, options: MonitorOptions) {
    super();
    this.on('error', noop);
 
    this.server = server;
    this.connection = null;
    this.cancellationToken = new CancellationToken();
    this.cancellationToken.setMaxListeners(Infinity);
    this.monitorId = undefined;
    this.s = {
      state: STATE_CLOSED
    };
    this.address = server.description.address;
    this.options = Object.freeze({
      connectTimeoutMS: options.connectTimeoutMS ?? 10000,
      heartbeatFrequencyMS: options.heartbeatFrequencyMS ?? 10000,
      minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500,
      serverMonitoringMode: options.serverMonitoringMode
    });
    this.isRunningInFaasEnv = getFAASEnv() != null;
    this.mongoLogger = this.server.topology.client?.mongoLogger;
    this.rttSampler = new RTTSampler(10);
 
    const cancellationToken = this.cancellationToken;
    // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration
    const connectOptions = {
      id: '<monitor>' as const,
      generation: server.pool.generation,
      cancellationToken,
      hostAddress: server.description.hostAddress,
      ...options,
      // force BSON serialization options
      raw: false,
      useBigInt64: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: true
    };
 
    // ensure no authentication is used for monitoring
    delete connectOptions.credentials;
    if (connectOptions.autoEncrypter) {
      delete connectOptions.autoEncrypter;
    }
 
    this.connectOptions = Object.freeze(connectOptions);
  }
 
  connect(): void {
    if (this.s.state !== STATE_CLOSED) {
      return;
    }
 
    // start
    const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
    const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
    this.monitorId = new MonitorInterval(monitorServer(this), {
      heartbeatFrequencyMS: heartbeatFrequencyMS,
      minHeartbeatFrequencyMS: minHeartbeatFrequencyMS,
      immediate: true
    });
  }
 
  requestCheck(): void {
    if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) {
      return;
    }
 
    this.monitorId?.wake();
  }
 
  reset(): void {
    const topologyVersion = this.server.description.topologyVersion;
    if (isInCloseState(this) || topologyVersion == null) {
      return;
    }
 
    stateTransition(this, STATE_CLOSING);
    resetMonitorState(this);
 
    // restart monitor
    stateTransition(this, STATE_IDLE);
 
    // restart monitoring
    const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS;
    const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS;
    this.monitorId = new MonitorInterval(monitorServer(this), {
      heartbeatFrequencyMS: heartbeatFrequencyMS,
      minHeartbeatFrequencyMS: minHeartbeatFrequencyMS
    });
  }
 
  close(): void {
    if (isInCloseState(this)) {
      return;
    }
 
    stateTransition(this, STATE_CLOSING);
    resetMonitorState(this);
 
    // close monitor
    this.emit('close');
    stateTransition(this, STATE_CLOSED);
  }
 
  get roundTripTime(): number {
    return this.rttSampler.average();
  }
 
  get minRoundTripTime(): number {
    return this.rttSampler.min();
  }
 
  get latestRtt(): number | null {
    return this.rttSampler.last;
  }
 
  addRttSample(rtt: number) {
    this.rttSampler.addSample(rtt);
  }
 
  clearRttSamples() {
    this.rttSampler.clear();
  }
}
 
function resetMonitorState(monitor: Monitor) {
  monitor.monitorId?.stop();
  monitor.monitorId = undefined;
 
  monitor.rttPinger?.close();
  monitor.rttPinger = undefined;
 
  monitor.cancellationToken.emit('cancel');
 
  monitor.connection?.destroy();
  monitor.connection = null;
 
  monitor.clearRttSamples();
}
 
function useStreamingProtocol(monitor: Monitor, topologyVersion: TopologyVersion | null): boolean {
  // If we have no topology version we always poll no matter
  // what the user provided, since the server does not support
  // the streaming protocol.
  if (topologyVersion == null) return false;
 
  const serverMonitoringMode = monitor.options.serverMonitoringMode;
  if (serverMonitoringMode === ServerMonitoringMode.poll) return false;
  if (serverMonitoringMode === ServerMonitoringMode.stream) return true;
 
  // If we are in auto mode, we need to figure out if we're in a FaaS
  // environment or not and choose the appropriate mode.
  if (monitor.isRunningInFaasEnv) return false;
  return true;
}
 
function checkServer(monitor: Monitor, callback: Callback<Document | null>) {
  let start: number;
  let awaited: boolean;
  const topologyVersion = monitor.server.description.topologyVersion;
  const isAwaitable = useStreamingProtocol(monitor, topologyVersion);
  monitor.emitAndLogHeartbeat(
    Server.SERVER_HEARTBEAT_STARTED,
    monitor.server.topology.s.id,
    undefined,
    new ServerHeartbeatStartedEvent(monitor.address, isAwaitable)
  );
 
  function onHeartbeatFailed(err: Error) {
    monitor.connection?.destroy();
    monitor.connection = null;
    monitor.emitAndLogHeartbeat(
      Server.SERVER_HEARTBEAT_FAILED,
      monitor.server.topology.s.id,
      undefined,
      new ServerHeartbeatFailedEvent(monitor.address, calculateDurationInMs(start), err, awaited)
    );
 
    const error = !(err instanceof MongoError)
      ? new MongoError(MongoError.buildErrorMessage(err), { cause: err })
      : err;
    error.addErrorLabel(MongoErrorLabel.ResetPool);
    if (error instanceof MongoNetworkTimeoutError) {
      error.addErrorLabel(MongoErrorLabel.InterruptInUseConnections);
    }
 
    monitor.emit('resetServer', error);
    callback(err);
  }
 
  function onHeartbeatSucceeded(hello: Document) {
    if (!('isWritablePrimary' in hello)) {
      // Provide hello-style response document.
      hello.isWritablePrimary = hello[LEGACY_HELLO_COMMAND];
    }
 
    // NOTE: here we use the latestRtt as this measurement corresponds with the value
    // obtained for this successful heartbeat, if there is no latestRtt, then we calculate the
    // duration
    const duration =
      isAwaitable && monitor.rttPinger
        ? (monitor.rttPinger.latestRtt ?? calculateDurationInMs(start))
        : calculateDurationInMs(start);
 
    monitor.addRttSample(duration);
 
    monitor.emitAndLogHeartbeat(
      Server.SERVER_HEARTBEAT_SUCCEEDED,
      monitor.server.topology.s.id,
      hello.connectionId,
      new ServerHeartbeatSucceededEvent(monitor.address, duration, hello, isAwaitable)
    );
 
    if (isAwaitable) {
      // If we are using the streaming protocol then we immediately issue another 'started'
      // event, otherwise the "check" is complete and return to the main monitor loop
      monitor.emitAndLogHeartbeat(
        Server.SERVER_HEARTBEAT_STARTED,
        monitor.server.topology.s.id,
        undefined,
        new ServerHeartbeatStartedEvent(monitor.address, true)
      );
      // We have not actually sent an outgoing handshake, but when we get the next response we
      // want the duration to reflect the time since we last heard from the server
      start = now();
    } else {
      monitor.rttPinger?.close();
      monitor.rttPinger = undefined;
 
      callback(undefined, hello);
    }
  }
 
  const { connection } = monitor;
  if (connection && !connection.closed) {
    const { serverApi, helloOk } = connection;
    const connectTimeoutMS = monitor.options.connectTimeoutMS;
    const maxAwaitTimeMS = monitor.options.heartbeatFrequencyMS;
 
    const cmd = {
      [serverApi?.version || helloOk ? 'hello' : LEGACY_HELLO_COMMAND]: 1,
      ...(isAwaitable && topologyVersion
        ? { maxAwaitTimeMS, topologyVersion: makeTopologyVersion(topologyVersion) }
        : {})
    };
 
    const options = isAwaitable
      ? {
          socketTimeoutMS: connectTimeoutMS ? connectTimeoutMS + maxAwaitTimeMS : 0,
          exhaustAllowed: true
        }
      : { socketTimeoutMS: connectTimeoutMS };
 
    if (isAwaitable && monitor.rttPinger == null) {
      monitor.rttPinger = new RTTPinger(monitor);
    }
 
    // Record new start time before sending handshake
    start = now();
 
    if (isAwaitable) {
      awaited = true;
      return connection.exhaustCommand(ns('admin.$cmd'), cmd, options, (error, hello) => {
        if (error) return onHeartbeatFailed(error);
        return onHeartbeatSucceeded(hello);
      });
    }
 
    awaited = false;
    connection
      .command(ns('admin.$cmd'), cmd, options)
      .then(onHeartbeatSucceeded, onHeartbeatFailed);
 
    return;
  }
 
  // connecting does an implicit `hello`
  (async () => {
    const socket = await makeSocket(monitor.connectOptions);
    const connection = makeConnection(monitor.connectOptions, socket);
    // The start time is after socket creation but before the handshake
    start = now();
    try {
      await performInitialHandshake(connection, monitor.connectOptions);
      return connection;
    } catch (error) {
      connection.destroy();
      throw error;
    }
  })().then(
    connection => {
      if (isInCloseState(monitor)) {
        connection.destroy();
        return;
      }
      const duration = calculateDurationInMs(start);
      monitor.addRttSample(duration);
 
      monitor.connection = connection;
      monitor.emitAndLogHeartbeat(
        Server.SERVER_HEARTBEAT_SUCCEEDED,
        monitor.server.topology.s.id,
        connection.hello?.connectionId,
        new ServerHeartbeatSucceededEvent(
          monitor.address,
          duration,
          connection.hello,
          useStreamingProtocol(monitor, connection.hello?.topologyVersion)
        )
      );
 
      callback(undefined, connection.hello);
    },
    error => {
      monitor.connection = null;
      awaited = false;
      onHeartbeatFailed(error);
    }
  );
}
 
function monitorServer(monitor: Monitor) {
  return (callback: Callback) => {
    Iif (monitor.s.state === STATE_MONITORING) {
      process.nextTick(callback);
      return;
    }
    stateTransition(monitor, STATE_MONITORING);
    function done() {
      if (!isInCloseState(monitor)) {
        stateTransition(monitor, STATE_IDLE);
      }
 
      callback();
    }
 
    checkServer(monitor, (err, hello) => {
      if (err) {
        // otherwise an error occurred on initial discovery, also bail
        if (monitor.server.description.type === ServerType.Unknown) {
          return done();
        }
      }
 
      // if the check indicates streaming is supported, immediately reschedule monitoring
      if (useStreamingProtocol(monitor, hello?.topologyVersion)) {
        setTimeout(() => {
          if (!isInCloseState(monitor)) {
            monitor.monitorId?.wake();
          }
        }, 0);
      }
 
      done();
    });
  };
}
 
function makeTopologyVersion(tv: TopologyVersion) {
  return {
    processId: tv.processId,
    // tests mock counter as just number, but in a real situation counter should always be a Long
    // TODO(NODE-2674): Preserve int64 sent from MongoDB
    counter: Long.isLong(tv.counter) ? tv.counter : Long.fromNumber(tv.counter)
  };
}
 
/** @internal */
export interface RTTPingerOptions extends ConnectionOptions {
  heartbeatFrequencyMS: number;
}
 
/** @internal */
export class RTTPinger {
  connection?: Connection;
  /** @internal */
  cancellationToken: CancellationToken;
  /** @internal */
  monitorId: NodeJS.Timeout;
  /** @internal */
  monitor: Monitor;
  closed: boolean;
  /** @internal */
  latestRtt?: number;
 
  constructor(monitor: Monitor) {
    this.connection = undefined;
    this.cancellationToken = monitor.cancellationToken;
    this.closed = false;
    this.monitor = monitor;
    this.latestRtt = monitor.latestRtt ?? undefined;
 
    const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS;
    this.monitorId = setTimeout(() => this.measureRoundTripTime(), heartbeatFrequencyMS);
  }
 
  get roundTripTime(): number {
    return this.monitor.roundTripTime;
  }
 
  get minRoundTripTime(): number {
    return this.monitor.minRoundTripTime;
  }
 
  close(): void {
    this.closed = true;
    clearTimeout(this.monitorId);
 
    this.connection?.destroy();
    this.connection = undefined;
  }
 
  private measureAndReschedule(start: number, conn?: Connection) {
    if (this.closed) {
      conn?.destroy();
      return;
    }
 
    if (this.connection == null) {
      this.connection = conn;
    }
 
    this.latestRtt = calculateDurationInMs(start);
    this.monitorId = setTimeout(
      () => this.measureRoundTripTime(),
      this.monitor.options.heartbeatFrequencyMS
    );
  }
 
  private measureRoundTripTime() {
    const start = now();
 
    Iif (this.closed) {
      return;
    }
 
    const connection = this.connection;
    if (connection == null) {
      connect(this.monitor.connectOptions).then(
        connection => {
          this.measureAndReschedule(start, connection);
        },
        () => {
          this.connection = undefined;
        }
      );
      return;
    }
 
    const commandName =
      connection.serverApi?.version || connection.helloOk ? 'hello' : LEGACY_HELLO_COMMAND;
 
    connection.command(ns('admin.$cmd'), { [commandName]: 1 }, undefined).then(
      () => this.measureAndReschedule(start),
      () => {
        this.connection?.destroy();
        this.connection = undefined;
        return;
      }
    );
  }
}
 
/**
 * @internal
 */
export interface MonitorIntervalOptions {
  /** The interval to execute a method on */
  heartbeatFrequencyMS: number;
  /** A minimum interval that must elapse before the method is called */
  minHeartbeatFrequencyMS: number;
  /** Whether the method should be called immediately when the interval is started  */
  immediate: boolean;
}
 
/**
 * @internal
 */
export class MonitorInterval {
  fn: (callback: Callback) => void;
  timerId: NodeJS.Timeout | undefined;
  lastExecutionEnded: number;
  isExpeditedCallToFnScheduled = false;
  stopped = false;
  isExecutionInProgress = false;
  hasExecutedOnce = false;
 
  heartbeatFrequencyMS: number;
  minHeartbeatFrequencyMS: number;
 
  constructor(fn: (callback: Callback) => void, options: Partial<MonitorIntervalOptions> = {}) {
    this.fn = fn;
    this.lastExecutionEnded = -Infinity;
 
    this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000;
    this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500;
 
    if (options.immediate) {
      this._executeAndReschedule();
    } else {
      this._reschedule(undefined);
    }
  }
 
  wake() {
    const currentTime = now();
    const timeSinceLastCall = currentTime - this.lastExecutionEnded;
 
    // TODO(NODE-4674): Add error handling and logging to the monitor
    if (timeSinceLastCall < 0) {
      return this._executeAndReschedule();
    }
 
    if (this.isExecutionInProgress) {
      return;
    }
 
    // debounce multiple calls to wake within the `minInterval`
    if (this.isExpeditedCallToFnScheduled) {
      return;
    }
 
    // reschedule a call as soon as possible, ensuring the call never happens
    // faster than the `minInterval`
    if (timeSinceLastCall < this.minHeartbeatFrequencyMS) {
      this.isExpeditedCallToFnScheduled = true;
      this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall);
      return;
    }
 
    this._executeAndReschedule();
  }
 
  stop() {
    this.stopped = true;
    if (this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = undefined;
    }
 
    this.lastExecutionEnded = -Infinity;
    this.isExpeditedCallToFnScheduled = false;
  }
 
  toString() {
    return JSON.stringify(this);
  }
 
  toJSON() {
    const currentTime = now();
    const timeSinceLastCall = currentTime - this.lastExecutionEnded;
    return {
      timerId: this.timerId != null ? 'set' : 'cleared',
      lastCallTime: this.lastExecutionEnded,
      isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled,
      stopped: this.stopped,
      heartbeatFrequencyMS: this.heartbeatFrequencyMS,
      minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS,
      currentTime,
      timeSinceLastCall
    };
  }
 
  private _reschedule(ms?: number) {
    if (this.stopped) return;
    if (this.timerId) {
      clearTimeout(this.timerId);
    }
 
    this.timerId = setTimeout(this._executeAndReschedule, ms || this.heartbeatFrequencyMS);
  }
 
  private _executeAndReschedule = () => {
    Iif (this.stopped) return;
    if (this.timerId) {
      clearTimeout(this.timerId);
    }
 
    this.isExpeditedCallToFnScheduled = false;
    this.isExecutionInProgress = true;
 
    this.fn(() => {
      this.lastExecutionEnded = now();
      this.isExecutionInProgress = false;
      this._reschedule(this.heartbeatFrequencyMS);
    });
  };
}
 
/** @internal
 * This class implements the RTT sampling logic specified for [CSOT](https://github.com/mongodb/specifications/blob/bbb335e60cd7ea1e0f7cd9a9443cb95fc9d3b64d/source/client-side-operations-timeout/client-side-operations-timeout.md#drivers-use-minimum-rtt-to-short-circuit-operations)
 *
 * This is implemented as a [circular buffer](https://en.wikipedia.org/wiki/Circular_buffer) keeping
 * the most recent `windowSize` samples
 * */
export class RTTSampler {
  /** Index of the next slot to be overwritten */
  private writeIndex: number;
  private length: number;
  private rttSamples: Float64Array;
 
  constructor(windowSize = 10) {
    this.rttSamples = new Float64Array(windowSize);
    this.length = 0;
    this.writeIndex = 0;
  }
 
  /**
   * Adds an rtt sample to the end of the circular buffer
   * When `windowSize` samples have been collected, `addSample` overwrites the least recently added
   * sample
   */
  addSample(sample: number) {
    this.rttSamples[this.writeIndex++] = sample;
    if (this.length < this.rttSamples.length) {
      this.length++;
    }
 
    this.writeIndex %= this.rttSamples.length;
  }
 
  /**
   * When \< 2 samples have been collected, returns 0
   * Otherwise computes the minimum value samples contained in the buffer
   */
  min(): number {
    if (this.length < 2) return 0;
    let min = this.rttSamples[0];
    for (let i = 1; i < this.length; i++) {
      if (this.rttSamples[i] < min) min = this.rttSamples[i];
    }
 
    return min;
  }
 
  /**
   * Returns mean of samples contained in the buffer
   */
  average(): number {
    Iif (this.length === 0) return 0;
    let sum = 0;
    for (let i = 0; i < this.length; i++) {
      sum += this.rttSamples[i];
    }
 
    return sum / this.length;
  }
 
  /**
   * Returns most recently inserted element in the buffer
   * Returns null if the buffer is empty
   * */
  get last(): number | null {
    if (this.length === 0) return null;
    return this.rttSamples[this.writeIndex === 0 ? this.length - 1 : this.writeIndex - 1];
  }
 
  /**
   * Clear the buffer
   * NOTE: this does not overwrite the data held in the internal array, just the pointers into
   * this array
   */
  clear() {
    this.length = 0;
    this.writeIndex = 0;
  }
}