All files / src timeout.ts

89.05% Statements 122/137
85.71% Branches 78/91
88.37% Functions 38/43
90.47% Lines 114/126

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 406580x     580x   580x     580x     27093x       181340x 181340x       249060x                           580x       31241547x   31241547x 31241547x                           15570117x     31241551x 31241551x 31241551x   31241551x 4x       31241547x 31241547x   31241547x     31241547x 31241547x   31241547x 15481495x 181146x 181146x 181146x   15481495x       15760052x 194x 194x 194x               15466029x 15466029x 15466029x 15466029x       15670986x       194x 194x         15569927x       194x                                               14257557x                     14351130x                     580x   14352274x 14351130x 14257557x                                                             580x                 114983x       114983x 114983x   114983x   114983x   114983x   114983x               492632x 492632x       557053x         121287x 112803x 112803x 194x       112609x   112609x 28187x   84422x 84418x   4x         121093x       124549x       124549x   124545x   4x         124545x       211x 211x 211x         125620x 125620x 102364x         8216x 8216x 8216x 8216x       56854x 56854x                 14978x 14978x   14978x                 192x       192x 192x       8968x       126015x 112048x 112048x       126015x         580x         14257668x 14257668x 14257668x       58722801x       15107405x 15107389x 16x       13339369x 5937x 13333432x       24118x       11675152x               332325x               95x               13396699x      
import { clearTimeout, setTimeout } from 'timers';
 
import { type Document } from './bson';
import { MongoInvalidArgumentError, MongoOperationTimeoutError, MongoRuntimeError } from './error';
import { type ClientSession } from './sessions';
import { csotMin, noop, squashError } from './utils';
 
/** @internal */
export class TimeoutError extends Error {
  duration: number;
  override get name(): 'TimeoutError' {
    return 'TimeoutError';
  }
 
  constructor(message: string, options: { cause?: Error; duration: number }) {
    super(message, options);
    this.duration = options.duration;
  }
 
  static is(error: unknown): error is TimeoutError {
    return (
      error != null && typeof error === 'object' && 'name' in error && error.name === 'TimeoutError'
    );
  }
}
 
type Executor = ConstructorParameters<typeof Promise<never>>[0];
type Reject = Parameters<ConstructorParameters<typeof Promise<never>>[0]>[1];
/**
 * @internal
 * This class is an abstraction over timeouts
 * The Timeout class can only be in the pending or rejected states. It is guaranteed not to resolve
 * if interacted with exclusively through its public API
 * */
export class Timeout extends Promise<never> {
  private id?: NodeJS.Timeout;
 
  public readonly start: number;
  public ended: number | null = null;
  public duration: number;
  private timedOut = false;
  public cleared = false;
 
  get remainingTime(): number {
    if (this.timedOut) return 0;
    if (this.duration === 0) return Infinity;
    return this.start + this.duration - Math.trunc(performance.now());
  }
 
  get timeElapsed(): number {
    return Math.trunc(performance.now()) - this.start;
  }
 
  /** Create a new timeout that expires in `duration` ms */
  private constructor(
    executor: Executor = () => null,
    options?: { duration: number; unref?: true; rejection?: Error }
  ) {
    const duration = options?.duration ?? 0;
    const unref = !!options?.unref;
    const rejection = options?.rejection;
 
    if (duration < 0) {
      throw new MongoInvalidArgumentError('Cannot create a Timeout with a negative duration');
    }
 
    let reject!: Reject;
    super((_, promiseReject) => {
      reject = promiseReject;
 
      executor(noop, promiseReject);
    });
 
    this.duration = duration;
    this.start = Math.trunc(performance.now());
 
    if (rejection == null && this.duration > 0) {
      this.id = setTimeout(() => {
        this.ended = Math.trunc(performance.now());
        this.timedOut = true;
        reject(new TimeoutError(`Expired after ${duration}ms`, { duration }));
      }, this.duration);
      Iif (typeof this.id.unref === 'function' && unref) {
        // Ensure we do not keep the Node.js event loop running
        this.id.unref();
      }
    } else if (rejection != null) {
      this.ended = Math.trunc(performance.now());
      this.timedOut = true;
      reject(rejection);
    }
  }
 
  /**
   * Clears the underlying timeout. This method is idempotent
   */
  clear(): void {
    clearTimeout(this.id);
    this.id = undefined;
    this.timedOut = false;
    this.cleared = true;
  }
 
  throwIfExpired(): void {
    if (this.timedOut) {
      // This method is invoked when someone wants to throw immediately instead of await the result of this promise
      // Since they won't be handling the rejection from the promise (because we're about to throw here)
      // attach handling to prevent this from bubbling up to Node.js
      this.then(undefined, squashError);
      throw new TimeoutError('Timed out', { duration: this.duration });
    }
  }
 
  public static expires(duration: number, unref?: true): Timeout {
    return new Timeout(undefined, { duration, unref });
  }
 
  static override reject(rejection?: Error): Timeout {
    return new Timeout(undefined, { duration: 0, unref: true, rejection });
  }
}
 
/** @internal */
export type TimeoutContextOptions = (LegacyTimeoutContextOptions | CSOTTimeoutContextOptions) & {
  session?: ClientSession;
};
 
/** @internal */
export type LegacyTimeoutContextOptions = {
  serverSelectionTimeoutMS: number;
  waitQueueTimeoutMS: number;
  socketTimeoutMS?: number;
};
 
/** @internal */
export type CSOTTimeoutContextOptions = {
  timeoutMS: number;
  serverSelectionTimeoutMS: number;
  socketTimeoutMS?: number;
};
 
function isLegacyTimeoutContextOptions(v: unknown): v is LegacyTimeoutContextOptions {
  return (
    v != null &&
    typeof v === 'object' &&
    'serverSelectionTimeoutMS' in v &&
    typeof v.serverSelectionTimeoutMS === 'number' &&
    'waitQueueTimeoutMS' in v &&
    typeof v.waitQueueTimeoutMS === 'number'
  );
}
 
function isCSOTTimeoutContextOptions(v: unknown): v is CSOTTimeoutContextOptions {
  return (
    v != null &&
    typeof v === 'object' &&
    'serverSelectionTimeoutMS' in v &&
    typeof v.serverSelectionTimeoutMS === 'number' &&
    'timeoutMS' in v &&
    typeof v.timeoutMS === 'number'
  );
}
 
/** @internal */
export abstract class TimeoutContext {
  static create(options: TimeoutContextOptions): TimeoutContext {
    if (options.session?.timeoutContext != null) return options.session?.timeoutContext;
    if (isCSOTTimeoutContextOptions(options)) return new CSOTTimeoutContext(options);
    else Eif (isLegacyTimeoutContextOptions(options)) return new LegacyTimeoutContext(options);
    else throw new MongoRuntimeError('Unrecognized options');
  }
 
  abstract get maxTimeMS(): number | null;
 
  abstract get serverSelectionTimeout(): Timeout | null;
 
  abstract get connectionCheckoutTimeout(): Timeout | null;
 
  abstract get clearServerSelectionTimeout(): boolean;
 
  abstract get timeoutForSocketWrite(): Timeout | null;
 
  abstract get timeoutForSocketRead(): Timeout | null;
 
  abstract csotEnabled(): this is CSOTTimeoutContext;
 
  abstract refresh(): void;
 
  abstract clear(): void;
 
  /** Returns a new instance of the TimeoutContext, with all timeouts refreshed and restarted. */
  abstract refreshed(): TimeoutContext;
 
  abstract addMaxTimeMSToCommand(command: Document, options: { omitMaxTimeMS?: boolean }): void;
 
  abstract getSocketTimeoutMS(): number | undefined;
}
 
/** @internal */
export class CSOTTimeoutContext extends TimeoutContext {
  timeoutMS: number;
  serverSelectionTimeoutMS: number;
  socketTimeoutMS?: number;
 
  clearServerSelectionTimeout: boolean;
 
  private _serverSelectionTimeout?: Timeout | null;
  private _connectionCheckoutTimeout?: Timeout | null;
  public minRoundTripTime = 0;
  public start: number;
 
  constructor(options: CSOTTimeoutContextOptions) {
    super();
    this.start = Math.trunc(performance.now());
 
    this.timeoutMS = options.timeoutMS;
 
    this.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS;
 
    this.socketTimeoutMS = options.socketTimeoutMS;
 
    this.clearServerSelectionTimeout = false;
  }
 
  get maxTimeMS(): number {
    return this.remainingTimeMS - this.minRoundTripTime;
  }
 
  get remainingTimeMS() {
    const timePassed = Math.trunc(performance.now()) - this.start;
    return this.timeoutMS <= 0 ? Infinity : this.timeoutMS - timePassed;
  }
 
  csotEnabled(): this is CSOTTimeoutContext {
    return true;
  }
 
  get serverSelectionTimeout(): Timeout | null {
    // check for undefined
    if (typeof this._serverSelectionTimeout !== 'object' || this._serverSelectionTimeout?.cleared) {
      const { remainingTimeMS, serverSelectionTimeoutMS } = this;
      if (remainingTimeMS <= 0)
        return Timeout.reject(
          new MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`)
        );
      const usingServerSelectionTimeoutMS =
        serverSelectionTimeoutMS !== 0 &&
        csotMin(remainingTimeMS, serverSelectionTimeoutMS) === serverSelectionTimeoutMS;
      if (usingServerSelectionTimeoutMS) {
        this._serverSelectionTimeout = Timeout.expires(serverSelectionTimeoutMS);
      } else {
        if (remainingTimeMS > 0 && Number.isFinite(remainingTimeMS)) {
          this._serverSelectionTimeout = Timeout.expires(remainingTimeMS);
        } else {
          this._serverSelectionTimeout = null;
        }
      }
    }
 
    return this._serverSelectionTimeout;
  }
 
  get connectionCheckoutTimeout(): Timeout | null {
    Eif (
      typeof this._connectionCheckoutTimeout !== 'object' ||
      this._connectionCheckoutTimeout?.cleared
    ) {
      if (typeof this._serverSelectionTimeout === 'object') {
        // null or Timeout
        this._connectionCheckoutTimeout = this._serverSelectionTimeout;
      } else {
        throw new MongoRuntimeError(
          'Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira'
        );
      }
    }
    return this._connectionCheckoutTimeout;
  }
 
  get timeoutForSocketWrite(): Timeout | null {
    const { remainingTimeMS } = this;
    Iif (!Number.isFinite(remainingTimeMS)) return null;
    Eif (remainingTimeMS > 0) return Timeout.expires(remainingTimeMS);
    return Timeout.reject(new MongoOperationTimeoutError('Timed out before socket write'));
  }
 
  get timeoutForSocketRead(): Timeout | null {
    const { remainingTimeMS } = this;
    if (!Number.isFinite(remainingTimeMS)) return null;
    Eif (remainingTimeMS > 0) return Timeout.expires(remainingTimeMS);
    return Timeout.reject(new MongoOperationTimeoutError('Timed out before socket read'));
  }
 
  refresh(): void {
    this.start = Math.trunc(performance.now());
    this.minRoundTripTime = 0;
    this._serverSelectionTimeout?.clear();
    this._connectionCheckoutTimeout?.clear();
  }
 
  clear(): void {
    this._serverSelectionTimeout?.clear();
    this._connectionCheckoutTimeout?.clear();
  }
 
  /**
   * @internal
   * Throws a MongoOperationTimeoutError if the context has expired.
   * If the context has not expired, returns the `remainingTimeMS`
   **/
  getRemainingTimeMSOrThrow(message?: string): number {
    const { remainingTimeMS } = this;
    Iif (remainingTimeMS <= 0)
      throw new MongoOperationTimeoutError(message ?? `Expired after ${this.timeoutMS}ms`);
    return remainingTimeMS;
  }
 
  /**
   * @internal
   * This method is intended to be used in situations where concurrent operation are on the same deadline, but cannot share a single `TimeoutContext` instance.
   * Returns a new instance of `CSOTTimeoutContext` constructed with identical options, but setting the `start` property to `this.start`.
   */
  clone(): CSOTTimeoutContext {
    const timeoutContext = new CSOTTimeoutContext({
      timeoutMS: this.timeoutMS,
      serverSelectionTimeoutMS: this.serverSelectionTimeoutMS
    });
    timeoutContext.start = this.start;
    return timeoutContext;
  }
 
  override refreshed(): CSOTTimeoutContext {
    return new CSOTTimeoutContext(this);
  }
 
  override addMaxTimeMSToCommand(command: Document, options: { omitMaxTimeMS?: boolean }): void {
    if (options.omitMaxTimeMS) return;
    const maxTimeMS = this.remainingTimeMS - this.minRoundTripTime;
    if (maxTimeMS > 0 && Number.isFinite(maxTimeMS)) command.maxTimeMS = maxTimeMS;
  }
 
  override getSocketTimeoutMS(): number | undefined {
    return 0;
  }
}
 
/** @internal */
export class LegacyTimeoutContext extends TimeoutContext {
  options: LegacyTimeoutContextOptions;
  clearServerSelectionTimeout: boolean;
 
  constructor(options: LegacyTimeoutContextOptions) {
    super();
    this.options = options;
    this.clearServerSelectionTimeout = true;
  }
 
  csotEnabled(): this is CSOTTimeoutContext {
    return false;
  }
 
  get serverSelectionTimeout(): Timeout | null {
    if (this.options.serverSelectionTimeoutMS != null && this.options.serverSelectionTimeoutMS > 0)
      return Timeout.expires(this.options.serverSelectionTimeoutMS);
    return null;
  }
 
  get connectionCheckoutTimeout(): Timeout | null {
    if (this.options.waitQueueTimeoutMS != null && this.options.waitQueueTimeoutMS > 0)
      return Timeout.expires(this.options.waitQueueTimeoutMS);
    return null;
  }
 
  get timeoutForSocketWrite(): Timeout | null {
    return null;
  }
 
  get timeoutForSocketRead(): Timeout | null {
    return null;
  }
 
  refresh(): void {
    return;
  }
 
  clear(): void {
    return;
  }
 
  get maxTimeMS() {
    return null;
  }
 
  override refreshed(): LegacyTimeoutContext {
    return new LegacyTimeoutContext(this.options);
  }
 
  override addMaxTimeMSToCommand(_command: Document, _options: { omitMaxTimeMS?: boolean }): void {
    // No max timeMS is added to commands in legacy timeout mode.
  }
 
  override getSocketTimeoutMS(): number | undefined {
    return this.options.socketTimeoutMS;
  }
}