All files / src/cursor abstract_cursor.ts

92.32% Statements 349/378
88.38% Branches 213/241
92.85% Functions 65/70
92.66% Lines 341/368

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 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262275x   275x     275x                 275x 275x 275x 275x 275x 275x 275x   275x 275x 275x                                                       275x                                     1070337x                                                               275x                                                                                                                                                                                                                                       275x                               1070783x                                         275x                         1070783x 1070783x   1070783x     1070783x 1070783x 1070783x 1070783x 1070783x 1070783x 1070783x                         1070783x 9691x 7889x 2299x 2011x       130x         2169x   5590x     1802x 72x       1730x     1061092x 292x       1070289x           1070289x 1070289x 34936x     1070289x 8635x         1070289x 1299x     1070289x 1218x     1070289x 1144x     1070289x 4706x   1065583x     1070289x             1070289x 1070289x 1070289x   3604x   1070289x                     741484x         6801118x         2019391x         15286x       966204x       13907x       44x         1686x                     3650783x               264x                                       1070597x 1070597x 1070509x           7351x         178783x 178783x         178783x 286049x 286049x 286049x       178783x       157528x   157264x 264x     157000x 157000x 3489778x 132x     3489646x 131113x     3358533x       3358533x     3348583x 15044x     3333539x   3333042x         156824x 132x 132x                 6617x 6617x 44x   6617x 1197x     6617x 142x   142x         406x 406x 406x                   142x   142x     6475x       7311x   7047x       7047x     7047x 7047x 11423x 2753x   8670x     7047x 180x       450x         4964331x   4964067x 88x     4963979x 1426x     4963979x 4963979x 5787516x 5787164x 4678726x 4672451x   1108438x     4963979x 2535x       262766x             7184x   6920x       6920x 58x   6920x 6920x 6832x 176x 176x     6656x   2613x 2613x 517x 429x     6920x 87x       2096x                       2691x   2427x     2427x 1546517x 1546473x 44x                 923155x                   142611x   142347x     142347x 178167x 178167x 178167x 951x 2271x     177216x     134373x                 330x 330x       330x       330x 330x                                                                                           2891x 2891x 2891x 308x 704x     2583x     2891x                 2195x 2195x 2069x 126x 126x         2151x                 44x 44x 44x 44x     44x                 44x 44x       44x 44x                 853078x 853078x       853078x 44x     853034x 853034x                 440x 44x   396x 88x     308x 308x 308x 308x 308x 308x 308x 308x 308x     308x 264x 44x   264x                               92041x         92041x         92041x           92041x             92041x                     1052370x 8868x               1052370x 1052370x   1038237x 1038237x 1038237x 1038237x 1038185x 1038185x 1038185x     14185x 14185x 14185x     1038185x 1003948x     1038185x         1123764x 3464x     1120300x               1120300x 1043114x   1029648x         93104x   93104x 93104x 76548x 76548x   16556x 16556x         16556x     76548x               5511x           1963355x 1963355x 1963355x 29214x 36x 36x               29178x     1963355x 1963355x               29214x 29214x 29214x   29214x                     1963355x 1963355x 1957285x   1963355x 1959970x     1963355x           1070783x     1963355x 1963355x   1070337x     1963355x           8634x   8634x 8634x   8458x   264x 264x   8194x   440x 440x       440x           1723351x           6617x     6617x         6617x         581181x 579420x 579420x         5590x 5590x           725052x 92x 92x     724960x         719795x 1225x 718570x 46x   718524x 145632x     572891x                 5165x                   5165x 1424x                     3741x         1x 1x         275x                   275x   25644x 25644x   25644x     27786x     29243x     27786x     204x     29231x     151320x     1484x     7623x           956x     1957x     29231x     29231x      
import { Readable, Transform } from 'stream';
 
import { type BSONSerializeOptions, type Document, Long, pluckBSONSerializeOptions } from '../bson';
import { type OnDemandDocumentDeserializeOptions } from '../cmap/wire_protocol/on_demand/document';
import { type CursorResponse } from '../cmap/wire_protocol/responses';
import {
  MongoAPIError,
  MongoCursorExhaustedError,
  MongoCursorInUseError,
  MongoInvalidArgumentError,
  MongoRuntimeError,
  MongoTailableCursorError
} from '../error';
import type { MongoClient } from '../mongo_client';
import { type Abortable, TypedEventEmitter } from '../mongo_types';
import { executeOperation } from '../operations/execute_operation';
import { GetMoreOperation } from '../operations/get_more';
import { KillCursorsOperation } from '../operations/kill_cursors';
import { ReadConcern, type ReadConcernLike } from '../read_concern';
import { ReadPreference, type ReadPreferenceLike } from '../read_preference';
import { type AsyncDisposable, configureResourceManagement } from '../resource_management';
import type { Server } from '../sdam/server';
import { ClientSession, maybeClearPinnedConnection } from '../sessions';
import { type CSOTTimeoutContext, type Timeout, TimeoutContext } from '../timeout';
import {
  addAbortListener,
  type Disposable,
  kDispose,
  type MongoDBNamespace,
  noop,
  squashError
} from '../utils';
 
/**
 * @internal
 * TODO(NODE-2882): A cursor's getMore commands must be run on the same server it was started on
 * and the same session must be used for the lifetime of the cursor. This object serves to get the
 * server and session (along with the response) out of executeOperation back to the AbstractCursor.
 *
 * There may be a better design for communicating these values back to the cursor, currently an operation
 * MUST store the selected server on itself so it can be read after executeOperation has returned.
 */
export interface InitialCursorResponse {
  /** The server selected for the operation */
  server: Server;
  /** The session used for this operation, may be implicitly created */
  session?: ClientSession;
  /** The raw server response for the operation */
  response: CursorResponse;
}
 
/** @public */
export const CURSOR_FLAGS = [
  'tailable',
  'oplogReplay',
  'noCursorTimeout',
  'awaitData',
  'exhaust',
  'partial'
] as const;
 
/** @public */
export interface CursorStreamOptions {
  /** A transformation method applied to each document emitted by the stream */
  transform?(this: void, doc: Document): Document;
}
 
/** @public */
export type CursorFlag = (typeof CURSOR_FLAGS)[number];
 
function removeActiveCursor(this: AbstractCursor) {
  this.client.s.activeCursors.delete(this);
}
 
/**
 * @public
 * @experimental
 * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
 * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
 * `cursor.next()`.
 * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
 *
 * Depending on the type of cursor being used, this option has different default values.
 * For non-tailable cursors, this value defaults to `'cursorLifetime'`
 * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
 * definition can have an arbitrarily long lifetime.
 *
 * @example
 * ```ts
 * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
 * for await (const doc of cursor) {
 *  // process doc
 *  // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
 *  // will continue to iterate successfully otherwise, regardless of the number of batches.
 * }
 * ```
 *
 * @example
 * ```ts
 * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
 * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
 * ```
 */
export const CursorTimeoutMode = Object.freeze({
  ITERATION: 'iteration',
  LIFETIME: 'cursorLifetime'
} as const);
 
/**
 * @public
 * @experimental
 */
export type CursorTimeoutMode = (typeof CursorTimeoutMode)[keyof typeof CursorTimeoutMode];
 
/** @public */
export interface AbstractCursorOptions extends BSONSerializeOptions {
  session?: ClientSession;
  readPreference?: ReadPreferenceLike;
  readConcern?: ReadConcernLike;
  /**
   * Specifies the number of documents to return in each response from MongoDB
   */
  batchSize?: number;
  /**
   * When applicable `maxTimeMS` controls the amount of time the initial command
   * that constructs a cursor should take. (ex. find, aggregate, listCollections)
   */
  maxTimeMS?: number;
  /**
   * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores
   * that a cursor uses to fetch more data should take. (ex. cursor.next())
   */
  maxAwaitTimeMS?: number;
  /**
   * Comment to apply to the operation.
   *
   * In server versions pre-4.4, 'comment' must be string.  A server
   * error will be thrown if any other type is provided.
   *
   * In server versions 4.4 and above, 'comment' can be any valid BSON type.
   */
  comment?: unknown;
  /**
   * By default, MongoDB will automatically close a cursor when the
   * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)
   * you may use a Tailable Cursor that remains open after the client exhausts
   * the results in the initial cursor.
   */
  tailable?: boolean;
  /**
   * If awaitData is set to true, when the cursor reaches the end of the capped collection,
   * MongoDB blocks the query thread for a period of time waiting for new data to arrive.
   * When new data is inserted into the capped collection, the blocked thread is signaled
   * to wake up and return the next batch to the client.
   */
  awaitData?: boolean;
  noCursorTimeout?: boolean;
  /** Specifies the time an operation will run until it throws a timeout error. See {@link AbstractCursorOptions.timeoutMode} for more details on how this option applies to cursors. */
  timeoutMS?: number;
  /**
   * @public
   * @experimental
   * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
   * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
   * `cursor.next()`.
   * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
   *
   * Depending on the type of cursor being used, this option has different default values.
   * For non-tailable cursors, this value defaults to `'cursorLifetime'`
   * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
   * definition can have an arbitrarily long lifetime.
   *
   * @example
   * ```ts
   * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
   * for await (const doc of cursor) {
   *  // process doc
   *  // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
   *  // will continue to iterate successfully otherwise, regardless of the number of batches.
   * }
   * ```
   *
   * @example
   * ```ts
   * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
   * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
   * ```
   */
  timeoutMode?: CursorTimeoutMode;
 
  /**
   * @internal
   *
   * A timeout context to govern the total time the cursor can live.  If provided, the cursor
   * cannot be used in ITERATION mode.
   */
  timeoutContext?: CursorTimeoutContext;
}
 
/** @internal */
export type InternalAbstractCursorOptions = Omit<AbstractCursorOptions, 'readPreference'> & {
  // resolved
  readPreference: ReadPreference;
  readConcern?: ReadConcern;
 
  // cursor flags, some are deprecated
  oplogReplay?: boolean;
  exhaust?: boolean;
  partial?: boolean;
 
  omitMaxTimeMS?: boolean;
};
 
/** @public */
export type AbstractCursorEvents = {
  [AbstractCursor.CLOSE](): void;
};
 
/** @public */
export abstract class AbstractCursor<
    TSchema = any,
    CursorEvents extends AbstractCursorEvents = AbstractCursorEvents
  >
  extends TypedEventEmitter<CursorEvents>
  implements AsyncDisposable
{
  /** @internal */
  private cursorId: Long | null;
  /** @internal */
  private cursorSession: ClientSession;
  /** @internal */
  private selectedServer?: Server;
  /** @internal */
  private cursorNamespace: MongoDBNamespace;
  /** @internal */
  private documents: CursorResponse | null = null;
  /** @internal */
  private cursorClient: MongoClient;
  /** @internal */
  private transform?: (doc: TSchema) => any;
  /**
   * @internal
   * This is true whether or not the first command fails. It only indicates whether or not the first
   * command has been run.
   */
  private initialized: boolean;
  /** @internal */
  private isClosed: boolean;
  /** @internal */
  private isKilled: boolean;
  /** @internal */
  protected readonly cursorOptions: InternalAbstractCursorOptions;
  /** @internal */
  protected timeoutContext?: CursorTimeoutContext;
 
  /** @event */
  static readonly CLOSE = 'close' as const;
 
  /** @internal */
  protected deserializationOptions: OnDemandDocumentDeserializeOptions;
  protected signal: AbortSignal | undefined;
  private abortListener: Disposable | undefined;
 
  /** @internal */
  protected constructor(
    client: MongoClient,
    namespace: MongoDBNamespace,
    options: AbstractCursorOptions & Abortable = {}
  ) {
    super();
    this.on('error', noop);
 
    Iif (!client.s.isMongoClient) {
      throw new MongoRuntimeError('Cursor must be constructed with MongoClient');
    }
    this.cursorClient = client;
    this.cursorNamespace = namespace;
    this.cursorId = null;
    this.initialized = false;
    this.isClosed = false;
    this.isKilled = false;
    this.cursorOptions = {
      readPreference:
        options.readPreference && options.readPreference instanceof ReadPreference
          ? options.readPreference
          : ReadPreference.primary,
      ...pluckBSONSerializeOptions(options),
      timeoutMS: options?.timeoutContext?.csotEnabled()
        ? options.timeoutContext.timeoutMS
        : options.timeoutMS,
      tailable: options.tailable,
      awaitData: options.awaitData
    };
 
    if (this.cursorOptions.timeoutMS != null) {
      if (options.timeoutMode == null) {
        if (options.tailable) {
          if (options.awaitData) {
            if (
              options.maxAwaitTimeMS != null &&
              options.maxAwaitTimeMS >= this.cursorOptions.timeoutMS
            )
              throw new MongoInvalidArgumentError(
                'Cannot specify maxAwaitTimeMS >= timeoutMS for a tailable awaitData cursor'
              );
          }
 
          this.cursorOptions.timeoutMode = CursorTimeoutMode.ITERATION;
        } else {
          this.cursorOptions.timeoutMode = CursorTimeoutMode.LIFETIME;
        }
      } else {
        if (options.tailable && options.timeoutMode === CursorTimeoutMode.LIFETIME) {
          throw new MongoInvalidArgumentError(
            "Cannot set tailable cursor's timeoutMode to LIFETIME"
          );
        }
        this.cursorOptions.timeoutMode = options.timeoutMode;
      }
    } else {
      if (options.timeoutMode != null)
        throw new MongoInvalidArgumentError('Cannot set timeoutMode without setting timeoutMS');
    }
 
    // Set for initial command
    this.cursorOptions.omitMaxTimeMS =
      this.cursorOptions.timeoutMS != null &&
      ((this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION &&
        !this.cursorOptions.tailable) ||
        (this.cursorOptions.tailable && !this.cursorOptions.awaitData));
 
    const readConcern = ReadConcern.fromOptions(options);
    if (readConcern) {
      this.cursorOptions.readConcern = readConcern;
    }
 
    if (typeof options.batchSize === 'number') {
      this.cursorOptions.batchSize = options.batchSize;
    }
 
    // we check for undefined specifically here to allow falsy values
    // eslint-disable-next-line no-restricted-syntax
    if (options.comment !== undefined) {
      this.cursorOptions.comment = options.comment;
    }
 
    if (typeof options.maxTimeMS === 'number') {
      this.cursorOptions.maxTimeMS = options.maxTimeMS;
    }
 
    if (typeof options.maxAwaitTimeMS === 'number') {
      this.cursorOptions.maxAwaitTimeMS = options.maxAwaitTimeMS;
    }
 
    if (options.session instanceof ClientSession) {
      this.cursorSession = options.session;
    } else {
      this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
    }
 
    this.deserializationOptions = {
      ...this.cursorOptions,
      validation: {
        utf8: options?.enableUtf8Validation === false ? false : true
      }
    };
 
    this.timeoutContext = options.timeoutContext;
    this.signal = options.signal;
    this.abortListener = addAbortListener(
      this.signal,
      () => void this.close().then(undefined, squashError)
    );
    this.trackCursor();
  }
 
  /**
   * The cursor has no id until it receives a response from the initial cursor creating command.
   *
   * It is non-zero for as long as the database has an open cursor.
   *
   * The initiating command may receive a zero id if the entire result is in the `firstBatch`.
   */
  get id(): Long | undefined {
    return this.cursorId ?? undefined;
  }
 
  /** @internal */
  get isDead() {
    return (this.cursorId?.isZero() ?? false) || this.isClosed || this.isKilled;
  }
 
  /** @internal */
  get client(): MongoClient {
    return this.cursorClient;
  }
 
  /** @internal */
  get server(): Server | undefined {
    return this.selectedServer;
  }
 
  get namespace(): MongoDBNamespace {
    return this.cursorNamespace;
  }
 
  get readPreference(): ReadPreference {
    return this.cursorOptions.readPreference;
  }
 
  get readConcern(): ReadConcern | undefined {
    return this.cursorOptions.readConcern;
  }
 
  /** @internal */
  get session(): ClientSession {
    return this.cursorSession;
  }
 
  set session(clientSession: ClientSession) {
    this.cursorSession = clientSession;
  }
 
  /**
   * The cursor is closed and all remaining locally buffered documents have been iterated.
   */
  get closed(): boolean {
    return this.isClosed && (this.documents?.length ?? 0) === 0;
  }
 
  /**
   * A `killCursors` command was attempted on this cursor.
   * This is performed if the cursor id is non zero.
   */
  get killed(): boolean {
    return this.isKilled;
  }
 
  get loadBalanced(): boolean {
    return !!this.cursorClient.topology?.loadBalanced;
  }
 
  /**
   * @beta
   * @experimental
   * An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
   */
  declare [Symbol.asyncDispose]: () => Promise<void>;
  /** @internal */
  async asyncDispose() {
    await this.close();
  }
 
  /** Adds cursor to client's tracking so it will be closed by MongoClient.close() */
  private trackCursor() {
    this.cursorClient.s.activeCursors.add(this);
    if (!this.listeners('close').includes(removeActiveCursor)) {
      this.once('close', removeActiveCursor);
    }
  }
 
  /** Returns current buffered documents length */
  bufferedCount(): number {
    return this.documents?.length ?? 0;
  }
 
  /** Returns current buffered documents */
  readBufferedDocuments(number?: number): NonNullable<TSchema>[] {
    const bufferedDocs: NonNullable<TSchema>[] = [];
    const documentsToRead = Math.min(
      number ?? this.documents?.length ?? 0,
      this.documents?.length ?? 0
    );
 
    for (let count = 0; count < documentsToRead; count++) {
      const document = this.documents?.shift(this.deserializationOptions);
      Eif (document != null) {
        bufferedDocs.push(document);
      }
    }
 
    return bufferedDocs;
  }
 
  async *[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void> {
    this.signal?.throwIfAborted();
 
    if (this.closed) {
      return;
    }
 
    try {
      while (true) {
        if (this.isKilled) {
          return;
        }
 
        if (this.closed) {
          return;
        }
 
        Iif (this.cursorId != null && this.isDead && (this.documents?.length ?? 0) === 0) {
          return;
        }
 
        const document = await this.next();
 
        // eslint-disable-next-line no-restricted-syntax
        if (document === null) {
          return;
        }
 
        yield document;
 
        this.signal?.throwIfAborted();
      }
    } finally {
      // Only close the cursor if it has not already been closed. This finally clause handles
      // the case when a user would break out of a for await of loop early.
      if (!this.isClosed) {
        try {
          await this.close();
        } catch (error) {
          squashError(error);
        }
      }
    }
  }
 
  stream(options?: CursorStreamOptions): Readable & AsyncIterable<TSchema> {
    const readable = new ReadableCursorStream(this);
    const abortListener = addAbortListener(this.signal, function () {
      readable.destroy(this.reason);
    });
    readable.once('end', () => {
      abortListener?.[kDispose]();
    });
 
    if (options?.transform) {
      const transform = options.transform;
 
      const transformedStream = readable.pipe(
        new Transform({
          objectMode: true,
          highWaterMark: 1,
          transform(chunk, _, callback) {
            try {
              const transformed = transform(chunk);
              callback(undefined, transformed);
            } catch (err) {
              callback(err);
            }
          }
        })
      );
 
      // Bubble errors to transformed stream, because otherwise no way
      // to handle this error.
      readable.on('error', err => transformedStream.emit('error', err));
 
      return transformedStream;
    }
 
    return readable;
  }
 
  async hasNext(): Promise<boolean> {
    this.signal?.throwIfAborted();
 
    Iif (this.cursorId === Long.ZERO) {
      return false;
    }
 
    Iif (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION && this.cursorId != null) {
      this.timeoutContext?.refresh();
    }
    try {
      do {
        if ((this.documents?.length ?? 0) !== 0) {
          return true;
        }
        await this.fetchBatch();
      } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
    } finally {
      if (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION) {
        this.timeoutContext?.clear();
      }
    }
 
    return false;
  }
 
  /** Get the next available document from the cursor, returns null if no more documents are available. */
  async next(): Promise<TSchema | null> {
    this.signal?.throwIfAborted();
 
    if (this.cursorId === Long.ZERO) {
      throw new MongoCursorExhaustedError();
    }
 
    if (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION && this.cursorId != null) {
      this.timeoutContext?.refresh();
    }
 
    try {
      do {
        const doc = this.documents?.shift(this.deserializationOptions);
        if (doc != null) {
          if (this.transform != null) return await this.transformDocument(doc);
          return doc;
        }
        await this.fetchBatch();
      } while (!this.isDead || (this.documents?.length ?? 0) !== 0);
    } finally {
      if (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION) {
        this.timeoutContext?.clear();
      }
    }
 
    return null;
  }
 
  /**
   * Try to get the next available document from the cursor or `null` if an empty batch is returned
   */
  async tryNext(): Promise<TSchema | null> {
    this.signal?.throwIfAborted();
 
    Iif (this.cursorId === Long.ZERO) {
      throw new MongoCursorExhaustedError();
    }
 
    if (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION && this.cursorId != null) {
      this.timeoutContext?.refresh();
    }
    try {
      let doc = this.documents?.shift(this.deserializationOptions);
      if (doc != null) {
        Iif (this.transform != null) return await this.transformDocument(doc);
        return doc;
      }
 
      await this.fetchBatch();
 
      doc = this.documents?.shift(this.deserializationOptions);
      if (doc != null) {
        if (this.transform != null) return await this.transformDocument(doc);
        return doc;
      }
    } finally {
      if (this.cursorOptions.timeoutMode === CursorTimeoutMode.ITERATION) {
        this.timeoutContext?.clear();
      }
    }
 
    return null;
  }
 
  /**
   * Iterates over all the documents for this cursor using the iterator, callback pattern.
   *
   * If the iterator returns `false`, iteration will stop.
   *
   * @param iterator - The iteration callback.
   * @deprecated - Will be removed in a future release. Use for await...of instead.
   */
  async forEach(iterator: (doc: TSchema) => boolean | void): Promise<void> {
    this.signal?.throwIfAborted();
 
    Iif (typeof iterator !== 'function') {
      throw new MongoInvalidArgumentError('Argument "iterator" must be a function');
    }
    for await (const document of this) {
      const result = iterator(document);
      if (result === false) {
        break;
      }
    }
  }
 
  /**
   * Frees any client-side resources used by the cursor.
   */
  async close(options?: { timeoutMS?: number }): Promise<void> {
    await this.cleanup(options?.timeoutMS);
  }
 
  /**
   * Returns an array of documents. The caller is responsible for making sure that there
   * is enough memory to store the results. Note that the array only contains partial
   * results when this cursor had been previously accessed. In that case,
   * cursor.rewind() can be used to reset the cursor.
   */
  async toArray(): Promise<TSchema[]> {
    this.signal?.throwIfAborted();
 
    const array: TSchema[] = [];
    // at the end of the loop (since readBufferedDocuments is called) the buffer will be empty
    // then, the 'await of' syntax will run a getMore call
    for await (const document of this) {
      array.push(document);
      const docs = this.readBufferedDocuments();
      if (this.transform != null) {
        for (const doc of docs) {
          array.push(await this.transformDocument(doc));
        }
      } else {
        array.push(...docs);
      }
    }
    return array;
  }
  /**
   * Add a cursor flag to the cursor
   *
   * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
   * @param value - The flag boolean value.
   */
  addCursorFlag(flag: CursorFlag, value: boolean): this {
    this.throwIfInitialized();
    Iif (!CURSOR_FLAGS.includes(flag)) {
      throw new MongoInvalidArgumentError(`Flag ${flag} is not one of ${CURSOR_FLAGS}`);
    }
 
    Iif (typeof value !== 'boolean') {
      throw new MongoInvalidArgumentError(`Flag ${flag} must be a boolean value`);
    }
 
    this.cursorOptions[flag] = value;
    return this;
  }
 
  /**
   * Map all documents using the provided function
   * If there is a transform set on the cursor, that will be called first and the result passed to
   * this function's transform.
   *
   * @remarks
   *
   * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
   * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
   * all documents.  This will **not** result in a memory leak, just surprising behavior.  For example:
   *
   * ```typescript
   * const cursor = collection.find({});
   * cursor.map(() => null);
   *
   * const documents = await cursor.toArray();
   * // documents is always [], regardless of how many documents are in the collection.
   * ```
   *
   * Other falsey values are allowed:
   *
   * ```typescript
   * const cursor = collection.find({});
   * cursor.map(() => '');
   *
   * const documents = await cursor.toArray();
   * // documents is now an array of empty strings
   * ```
   *
   * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
   * it **does not** return a new instance of a cursor. This means when calling map,
   * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
   * Take note of the following example:
   *
   * @example
   * ```typescript
   * const cursor: FindCursor<Document> = coll.find();
   * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
   * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
   * ```
   * @param transform - The mapping transformation method.
   */
  map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T> {
    this.throwIfInitialized();
    const oldTransform = this.transform;
    if (oldTransform) {
      this.transform = doc => {
        return transform(oldTransform(doc));
      };
    } else {
      this.transform = transform;
    }
 
    return this as unknown as AbstractCursor<T>;
  }
 
  /**
   * Set the ReadPreference for the cursor.
   *
   * @param readPreference - The new read preference for the cursor.
   */
  withReadPreference(readPreference: ReadPreferenceLike): this {
    this.throwIfInitialized();
    if (readPreference instanceof ReadPreference) {
      this.cursorOptions.readPreference = readPreference;
    } else Eif (typeof readPreference === 'string') {
      this.cursorOptions.readPreference = ReadPreference.fromString(readPreference);
    } else {
      throw new MongoInvalidArgumentError(`Invalid read preference: ${readPreference}`);
    }
 
    return this;
  }
 
  /**
   * Set the ReadPreference for the cursor.
   *
   * @param readPreference - The new read preference for the cursor.
   */
  withReadConcern(readConcern: ReadConcernLike): this {
    this.throwIfInitialized();
    const resolvedReadConcern = ReadConcern.fromOptions({ readConcern });
    Eif (resolvedReadConcern) {
      this.cursorOptions.readConcern = resolvedReadConcern;
    }
 
    return this;
  }
 
  /**
   * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
   *
   * @param value - Number of milliseconds to wait before aborting the query.
   */
  maxTimeMS(value: number): this {
    this.throwIfInitialized();
    Iif (typeof value !== 'number') {
      throw new MongoInvalidArgumentError('Argument for maxTimeMS must be a number');
    }
 
    this.cursorOptions.maxTimeMS = value;
    return this;
  }
 
  /**
   * Set the batch size for the cursor.
   *
   * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
   */
  batchSize(value: number): this {
    this.throwIfInitialized();
    Iif (this.cursorOptions.tailable) {
      throw new MongoTailableCursorError('Tailable cursor does not support batchSize');
    }
 
    if (typeof value !== 'number') {
      throw new MongoInvalidArgumentError('Operation "batchSize" requires an integer');
    }
 
    this.cursorOptions.batchSize = value;
    return this;
  }
 
  /**
   * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
   * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
   * if the resultant data has already been retrieved by this cursor.
   */
  rewind(): void {
    if (this.timeoutContext && this.timeoutContext.owner !== this) {
      throw new MongoAPIError(`Cannot rewind cursor that does not own its timeout context.`);
    }
    if (!this.initialized) {
      return;
    }
 
    this.cursorId = null;
    this.documents?.clear();
    this.timeoutContext?.clear();
    this.timeoutContext = undefined;
    this.isClosed = false;
    this.isKilled = false;
    this.initialized = false;
    this.hasEmittedClose = false;
    this.trackCursor();
 
    // We only want to end this session if we created it, and it hasn't ended yet
    if (this.cursorSession.explicit === false) {
      if (!this.cursorSession.hasEnded) {
        this.cursorSession.endSession().then(undefined, squashError);
      }
      this.cursorSession = this.cursorClient.startSession({ owner: this, explicit: false });
    }
  }
 
  /**
   * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
   */
  abstract clone(): AbstractCursor<TSchema>;
 
  /** @internal */
  protected abstract _initialize(
    session: ClientSession | undefined
  ): Promise<InitialCursorResponse>;
 
  /** @internal */
  async getMore(batchSize: number): Promise<CursorResponse> {
    Iif (this.cursorId == null) {
      throw new MongoRuntimeError(
        'Unexpected null cursor id. A cursor creating command should have set this'
      );
    }
    Iif (this.selectedServer == null) {
      throw new MongoRuntimeError(
        'Unexpected null selectedServer. A cursor creating command should have set this'
      );
    }
    const getMoreOptions = {
      ...this.cursorOptions,
      session: this.cursorSession,
      batchSize
    };
 
    const getMoreOperation = new GetMoreOperation(
      this.cursorNamespace,
      this.cursorId,
      this.selectedServer,
      getMoreOptions
    );
 
    return await executeOperation(this.cursorClient, getMoreOperation, this.timeoutContext);
  }
 
  /**
   * @internal
   *
   * This function is exposed for the unified test runner's createChangeStream
   * operation.  We cannot refactor to use the abstract _initialize method without
   * a significant refactor.
   */
  private async cursorInit(): Promise<void> {
    if (this.cursorOptions.timeoutMS != null) {
      this.timeoutContext ??= new CursorTimeoutContext(
        TimeoutContext.create({
          serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS,
          timeoutMS: this.cursorOptions.timeoutMS
        }),
        this
      );
    }
    try {
      const state = await this._initialize(this.cursorSession);
      // Set omitMaxTimeMS to the value needed for subsequent getMore calls
      this.cursorOptions.omitMaxTimeMS = this.cursorOptions.timeoutMS != null;
      const response = state.response;
      this.selectedServer = state.server;
      this.cursorId = response.id;
      this.cursorNamespace = response.ns ?? this.namespace;
      this.documents = response;
      this.initialized = true; // the cursor is now initialized, even if it is dead
    } catch (error) {
      // the cursor is now initialized, even if an error occurred
      this.initialized = true;
      await this.cleanup(undefined, error);
      throw error;
    }
 
    if (this.isDead) {
      await this.cleanup();
    }
 
    return;
  }
 
  /** @internal Attempt to obtain more documents */
  private async fetchBatch(): Promise<void> {
    if (this.isClosed) {
      return;
    }
 
    Iif (this.isDead) {
      // if the cursor is dead, we clean it up
      // cleanupCursor should never throw, but if it does it indicates a bug in the driver
      // and we should surface the error
      await this.cleanup();
      return;
    }
 
    if (this.cursorId == null) {
      await this.cursorInit();
      // If the cursor died or returned documents, return
      if ((this.documents?.length ?? 0) !== 0 || this.isDead) return;
      // Otherwise, run a getMore
    }
 
    // otherwise need to call getMore
    const batchSize = this.cursorOptions.batchSize || 1000;
 
    try {
      const response = await this.getMore(batchSize);
      this.cursorId = response.id;
      this.documents = response;
    } catch (error) {
      try {
        await this.cleanup(undefined, error);
      } catch (cleanupError) {
        // `cleanupCursor` should never throw, squash and throw the original error
        squashError(cleanupError);
      }
      throw error;
    }
 
    if (this.isDead) {
      // If we successfully received a response from a cursor BUT the cursor indicates that it is exhausted,
      // we intentionally clean up the cursor to release its session back into the pool before the cursor
      // is iterated.  This prevents a cursor that is exhausted on the server from holding
      // onto a session indefinitely until the AbstractCursor is iterated.
      //
      // cleanupCursorAsync should never throw, but if it does it indicates a bug in the driver
      // and we should surface the error
      await this.cleanup();
    }
  }
 
  /** @internal */
  private async cleanup(timeoutMS?: number, error?: Error) {
    this.abortListener?.[kDispose]();
    this.isClosed = true;
    const timeoutContextForKillCursors = (): CursorTimeoutContext | undefined => {
      if (timeoutMS != null) {
        this.timeoutContext?.clear();
        return new CursorTimeoutContext(
          TimeoutContext.create({
            serverSelectionTimeoutMS: this.client.s.options.serverSelectionTimeoutMS,
            timeoutMS
          }),
          this
        );
      } else {
        return this.timeoutContext?.refreshed();
      }
    };
    try {
      if (
        !this.isKilled &&
        this.cursorId &&
        !this.cursorId.isZero() &&
        this.cursorNamespace &&
        this.selectedServer &&
        !this.cursorSession.hasEnded
      ) {
        this.isKilled = true;
        const cursorId = this.cursorId;
        this.cursorId = Long.ZERO;
 
        await executeOperation(
          this.cursorClient,
          new KillCursorsOperation(cursorId, this.cursorNamespace, this.selectedServer, {
            session: this.cursorSession
          }),
          timeoutContextForKillCursors()
        );
      }
    } catch (error) {
      squashError(error);
    } finally {
      try {
        if (this.cursorSession?.owner === this) {
          await this.cursorSession.endSession({ error });
        }
        if (!this.cursorSession?.inTransaction()) {
          maybeClearPinnedConnection(this.cursorSession, { error });
        }
      } finally {
        this.emitClose();
      }
    }
  }
 
  /** @internal */
  private hasEmittedClose = false;
  /** @internal */
  private emitClose() {
    try {
      if (!this.hasEmittedClose && ((this.documents?.length ?? 0) === 0 || this.isClosed)) {
        // @ts-expect-error: CursorEvents is generic so Parameters<CursorEvents["close"]> may not be assignable to `[]`. Not sure how to require extenders do not add parameters.
        this.emit('close');
      }
    } finally {
      this.hasEmittedClose = true;
    }
  }
 
  /** @internal */
  private async transformDocument(document: NonNullable<TSchema>): Promise<NonNullable<TSchema>> {
    Iif (this.transform == null) return document;
 
    try {
      const transformedDocument = this.transform(document);
      // eslint-disable-next-line no-restricted-syntax
      if (transformedDocument === null) {
        const TRANSFORM_TO_NULL_ERROR =
          'Cursor returned a `null` document, but the cursor is not exhausted.  Mapping documents to `null` is not supported in the cursor transform.';
        throw new MongoAPIError(TRANSFORM_TO_NULL_ERROR);
      }
      return transformedDocument;
    } catch (transformError) {
      try {
        await this.close();
      } catch (closeError) {
        squashError(closeError);
      }
      throw transformError;
    }
  }
 
  /** @internal */
  protected throwIfInitialized() {
    if (this.initialized) throw new MongoCursorInUseError();
  }
}
 
class ReadableCursorStream extends Readable {
  private _cursor: AbstractCursor;
  private _readInProgress = false;
 
  constructor(cursor: AbstractCursor) {
    super({
      objectMode: true,
      autoDestroy: false,
      highWaterMark: 1
    });
    this._cursor = cursor;
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  override _read(size: number): void {
    if (!this._readInProgress) {
      this._readInProgress = true;
      this._readNext();
    }
  }
 
  override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {
    this._cursor.close().then(
      () => callback(error),
      closeError => callback(closeError)
    );
  }
 
  private _readNext() {
    if (this._cursor.id === Long.ZERO) {
      this.push(null);
      return;
    }
 
    this._cursor
      .next()
      .then(
        // result from next()
        result => {
          if (result == null) {
            this.push(null);
          } else if (this.destroyed) {
            this._cursor.close().then(undefined, squashError);
          } else {
            if (this.push(result)) {
              return this._readNext();
            }
 
            this._readInProgress = false;
          }
        },
        // error from next()
        err => {
          // NOTE: This is questionable, but we have a test backing the behavior. It seems the
          //       desired behavior is that a stream ends cleanly when a user explicitly closes
          //       a client during iteration. Alternatively, we could do the "right" thing and
          //       propagate the error message by removing this special case.
          Iif (err.message.match(/server is closed/)) {
            this._cursor.close().then(undefined, squashError);
            return this.push(null);
          }
 
          // NOTE: This is also perhaps questionable. The rationale here is that these errors tend
          //       to be "operation was interrupted", where a cursor has been closed but there is an
          //       active getMore in-flight. This used to check if the cursor was killed but once
          //       that changed to happen in cleanup legitimate errors would not destroy the
          //       stream. There are change streams test specifically test these cases.
          if (err.message.match(/operation was interrupted/)) {
            return this.push(null);
          }
 
          // NOTE: The two above checks on the message of the error will cause a null to be pushed
          //       to the stream, thus closing the stream before the destroy call happens. This means
          //       that either of those error messages on a change stream will not get a proper
          //       'error' event to be emitted (the error passed to destroy). Change stream resumability
          //       relies on that error event to be emitted to create its new cursor and thus was not
          //       working on 4.4 servers because the error emitted on failover was "interrupted at
          //       shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down".
          //       See NODE-4475.
          return this.destroy(err);
        }
      )
      // if either of the above handlers throw
      .catch(error => {
        this._readInProgress = false;
        this.destroy(error);
      });
  }
}
 
configureResourceManagement(AbstractCursor.prototype);
 
/**
 * @internal
 * The cursor timeout context is a wrapper around a timeout context
 * that keeps track of the "owner" of the cursor.  For timeout contexts
 * instantiated inside a cursor, the owner will be the cursor.
 *
 * All timeout behavior is exactly the same as the wrapped timeout context's.
 */
export class CursorTimeoutContext extends TimeoutContext {
  constructor(
    public timeoutContext: TimeoutContext,
    public owner: symbol | AbstractCursor
  ) {
    super();
  }
  override get serverSelectionTimeout(): Timeout | null {
    return this.timeoutContext.serverSelectionTimeout;
  }
  override get connectionCheckoutTimeout(): Timeout | null {
    return this.timeoutContext.connectionCheckoutTimeout;
  }
  override get clearServerSelectionTimeout(): boolean {
    return this.timeoutContext.clearServerSelectionTimeout;
  }
  override get timeoutForSocketWrite(): Timeout | null {
    return this.timeoutContext.timeoutForSocketWrite;
  }
  override get timeoutForSocketRead(): Timeout | null {
    return this.timeoutContext.timeoutForSocketRead;
  }
  override csotEnabled(): this is CSOTTimeoutContext {
    return this.timeoutContext.csotEnabled();
  }
  override refresh(): void {
    if (typeof this.owner !== 'symbol') return this.timeoutContext.refresh();
  }
  override clear(): void {
    if (typeof this.owner !== 'symbol') return this.timeoutContext.clear();
  }
  override get maxTimeMS(): number | null {
    return this.timeoutContext.maxTimeMS;
  }
  get timeoutMS(): number | null {
    return this.timeoutContext.csotEnabled() ? this.timeoutContext.timeoutMS : null;
  }
  override refreshed(): CursorTimeoutContext {
    return new CursorTimeoutContext(this.timeoutContext.refreshed(), this.owner);
  }
  override addMaxTimeMSToCommand(command: Document, options: { omitMaxTimeMS?: boolean }): void {
    this.timeoutContext.addMaxTimeMSToCommand(command, options);
  }
  override getSocketTimeoutMS(): number | undefined {
    return this.timeoutContext.getSocketTimeoutMS();
  }
}