All files / src/operations command.ts

97.61% Statements 41/42
97.67% Branches 42/43
100% Functions 3/3
97.56% Lines 40/41

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    504x 504x           504x     504x     504x 504x   504x                                                                                                                 504x             7140729x 7140729x         7140729x 7140729x 190353x   6950376x         7140729x 7140729x   7140729x 4200640x 4200640x 2940089x           5180786x 3237583x   1943203x                                                 3482465x   3482465x               3482465x 3482465x   3482465x 2254x     3482465x 1228x     3482465x 999537x     3482465x         4047x     3482465x 4510x     3482465x 14104x     3482465x      
import type { BSONSerializeOptions, Document } from '../bson';
import { type MongoDBResponseConstructor } from '../cmap/wire_protocol/responses';
import { MongoInvalidArgumentError } from '../error';
import {
  decorateWithExplain,
  Explain,
  type ExplainOptions,
  validateExplainTimeoutOptions
} from '../explain';
import { ReadConcern } from '../read_concern';
import type { ReadPreference } from '../read_preference';
import type { Server } from '../sdam/server';
import { MIN_SECONDARY_WRITE_WIRE_VERSION } from '../sdam/server_selection';
import type { ClientSession } from '../sessions';
import { type TimeoutContext } from '../timeout';
import { commandSupportsReadConcern, maxWireVersion, MongoDBNamespace } from '../utils';
import { WriteConcern, type WriteConcernOptions } from '../write_concern';
import type { ReadConcernLike } from './../read_concern';
import { AbstractOperation, Aspect, type OperationOptions } from './operation';
 
/** @public */
export interface CollationOptions {
  locale: string;
  caseLevel?: boolean;
  caseFirst?: string;
  strength?: number;
  numericOrdering?: boolean;
  alternate?: string;
  maxVariable?: string;
  backwards?: boolean;
  normalization?: boolean;
}
 
/** @public */
export interface CommandOperationOptions
  extends OperationOptions,
    WriteConcernOptions,
    ExplainOptions {
  /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */
  readConcern?: ReadConcernLike;
  /** Collation */
  collation?: CollationOptions;
  /**
   * maxTimeMS is a server-side time limit in milliseconds for processing an operation.
   */
  maxTimeMS?: 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;
  /** Should retry failed writes */
  retryWrites?: boolean;
 
  // Admin command overrides.
  dbName?: string;
  authdb?: string;
  noResponse?: boolean;
}
 
/** @internal */
export interface OperationParent {
  s: { namespace: MongoDBNamespace };
  readConcern?: ReadConcern;
  writeConcern?: WriteConcern;
  readPreference?: ReadPreference;
  bsonOptions?: BSONSerializeOptions;
  timeoutMS?: number;
}
 
/** @internal */
export abstract class CommandOperation<T> extends AbstractOperation<T> {
  override options: CommandOperationOptions;
  readConcern?: ReadConcern;
  writeConcern?: WriteConcern;
  explain?: Explain;
 
  constructor(parent?: OperationParent, options?: CommandOperationOptions) {
    super(options);
    this.options = options ?? {};
 
    // NOTE: this was explicitly added for the add/remove user operations, it's likely
    //       something we'd want to reconsider. Perhaps those commands can use `Admin`
    //       as a parent?
    const dbNameOverride = options?.dbName || options?.authdb;
    if (dbNameOverride) {
      this.ns = new MongoDBNamespace(dbNameOverride, '$cmd');
    } else {
      this.ns = parent
        ? parent.s.namespace.withCollection('$cmd')
        : new MongoDBNamespace('admin', '$cmd');
    }
 
    this.readConcern = ReadConcern.fromOptions(options);
    this.writeConcern = WriteConcern.fromOptions(options);
 
    if (this.hasAspect(Aspect.EXPLAINABLE)) {
      this.explain = Explain.fromOptions(options);
      if (this.explain) validateExplainTimeoutOptions(this.options, this.explain);
    } else Iif (options?.explain != null) {
      throw new MongoInvalidArgumentError(`Option "explain" is not supported on this command`);
    }
  }
 
  override get canRetryWrite(): boolean {
    if (this.hasAspect(Aspect.EXPLAINABLE)) {
      return this.explain == null;
    }
    return super.canRetryWrite;
  }
 
  public async executeCommand<T extends MongoDBResponseConstructor>(
    server: Server,
    session: ClientSession | undefined,
    cmd: Document,
    timeoutContext: TimeoutContext,
    responseType: T | undefined
  ): Promise<typeof responseType extends undefined ? Document : InstanceType<T>>;
 
  public async executeCommand(
    server: Server,
    session: ClientSession | undefined,
    cmd: Document,
    timeoutContext: TimeoutContext
  ): Promise<Document>;
 
  async executeCommand(
    server: Server,
    session: ClientSession | undefined,
    cmd: Document,
    timeoutContext: TimeoutContext,
    responseType?: MongoDBResponseConstructor
  ): Promise<Document> {
    this.server = server;
 
    const options = {
      ...this.options,
      ...this.bsonOptions,
      timeoutContext,
      readPreference: this.readPreference,
      session
    };
 
    const serverWireVersion = maxWireVersion(server);
    const inTransaction = this.session && this.session.inTransaction();
 
    if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) {
      Object.assign(cmd, { readConcern: this.readConcern });
    }
 
    if (this.trySecondaryWrite && serverWireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION) {
      options.omitReadPreference = true;
    }
 
    if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) {
      WriteConcern.apply(cmd, this.writeConcern);
    }
 
    if (
      options.collation &&
      typeof options.collation === 'object' &&
      !this.hasAspect(Aspect.SKIP_COLLATION)
    ) {
      Object.assign(cmd, { collation: options.collation });
    }
 
    if (typeof options.maxTimeMS === 'number') {
      cmd.maxTimeMS = options.maxTimeMS;
    }
 
    if (this.hasAspect(Aspect.EXPLAINABLE) && this.explain) {
      cmd = decorateWithExplain(cmd, this.explain);
    }
 
    return await server.command(this.ns, cmd, options, responseType);
  }
}