All files / src/sdam topology_description.ts

96.33% Statements 184/191
93.82% Branches 152/162
80.95% Functions 17/21
96.84% Lines 184/190

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 549568x 568x 568x 568x 568x 568x       568x 568x 568x 568x   568x 568x 568x                               568x                                                 7316754x   7316754x 7316754x 7316754x 7316754x 7316754x 7316754x 7316754x 7316754x 7316754x 7316754x     7316754x   9668795x       4191025x     5477770x 20x 20x     5477770x 68x 68x 68x                 7316754x 7316754x 9667075x 4870399x   212195x 212195x     4658204x   3233678x 3233678x         1424526x                           13x 13x   13x 13x 13x   21x 21x     15x       13x         13x 13x 15x     13x 12x   10x 13x   2x   2x 2x 3x         13x                               3509334x     3509334x   3509334x 3509334x     3509334x 3215505x     3215505x       3509334x         32x   4x   28x         3509334x   3509334x   56142x                     3453192x 1103286x 12x   1103274x       3453192x 728425x 4x       3453192x 935604x 16x     935604x 640348x               640348x 640348x 640348x 640348x 295256x 293119x 293119x 293119x       3453192x 1821123x 8x 8x 1821115x 716057x               716057x 716057x 716057x 716057x 1105058x 1074823x           30235x       3453192x                       8814x 9346x     8814x 8184x     630x                                               11279997x                   427x         1103274x   395048x   627733x   44635x     28739x   7119x                     1356405x         48x               1356405x 1356405x 12x 12x     1356393x 953765x 953765x 953765x   953765x   953765x       953725x 953725x       40x                 40x     402628x 402628x 399860x 209005x         8x                 8x       399852x     402620x       190863x         1356345x 3317996x   152x                   152x         1356345x 4063071x 751688x         1356345x 1356345x 1356345x 4069842x   6795x     1356345x               1074823x         1074823x       8x     1074823x               293119x 293119x 293119x 8x 8x     293111x 879277x 560006x       293111x 1703x     293111x       2461471x 3441147x 2424444x       37027x    
import { EJSON, type ObjectId } from '../bson';
import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants';
import { type MongoError, MongoRuntimeError, MongoStalePrimaryError } from '../error';
import { compareObjectId, shuffle } from '../utils';
import { ServerType, TopologyType } from './common';
import { ServerDescription } from './server_description';
import type { SrvPollingEvent } from './srv_polling';
 
// constants related to compatibility checks
const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
 
const MONGOS_OR_UNKNOWN = new Set<ServerType>([ServerType.Mongos, ServerType.Unknown]);
const MONGOS_OR_STANDALONE = new Set<ServerType>([ServerType.Mongos, ServerType.Standalone]);
const NON_PRIMARY_RS_MEMBERS = new Set<ServerType>([
  ServerType.RSSecondary,
  ServerType.RSArbiter,
  ServerType.RSOther
]);
 
/** @public */
export interface TopologyDescriptionOptions {
  heartbeatFrequencyMS?: number;
  localThresholdMS?: number;
}
 
/**
 * Representation of a deployment of servers
 * @public
 */
export class TopologyDescription {
  type: TopologyType;
  setName: string | null;
  maxSetVersion: number | null;
  maxElectionId: ObjectId | null;
  servers: Map<string, ServerDescription>;
  stale: boolean;
  compatible: boolean;
  compatibilityError?: string;
  logicalSessionTimeoutMinutes: number | null;
  heartbeatFrequencyMS: number;
  localThresholdMS: number;
  commonWireVersion: number;
  /**
   * Create a TopologyDescription
   */
  constructor(
    topologyType: TopologyType,
    serverDescriptions: Map<string, ServerDescription> | null = null,
    setName: string | null = null,
    maxSetVersion: number | null = null,
    maxElectionId: ObjectId | null = null,
    commonWireVersion: number | null = null,
    options: TopologyDescriptionOptions | null = null
  ) {
    options = options ?? {};
 
    this.type = topologyType ?? TopologyType.Unknown;
    this.servers = serverDescriptions ?? new Map();
    this.stale = false;
    this.compatible = true;
    this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0;
    this.localThresholdMS = options.localThresholdMS ?? 15;
    this.setName = setName ?? null;
    this.maxElectionId = maxElectionId ?? null;
    this.maxSetVersion = maxSetVersion ?? null;
    this.commonWireVersion = commonWireVersion ?? 0;
 
    // determine server compatibility
    for (const serverDescription of this.servers.values()) {
      // Load balancer mode is always compatible.
      if (
        serverDescription.type === ServerType.Unknown ||
        serverDescription.type === ServerType.LoadBalancer
      ) {
        continue;
      }
 
      if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {
        this.compatible = false;
        this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`;
      }
 
      if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {
        this.compatible = false;
        this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`;
        break;
      }
    }
 
    // Whenever a client updates the TopologyDescription from a hello response, it MUST set
    // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes
    // value among ServerDescriptions of all data-bearing server types. If any have a null
    // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be
    // set to null.
    this.logicalSessionTimeoutMinutes = null;
    for (const [, server] of this.servers) {
      if (server.isReadable) {
        if (server.logicalSessionTimeoutMinutes == null) {
          // If any of the servers have a null logicalSessionsTimeout, then the whole topology does
          this.logicalSessionTimeoutMinutes = null;
          break;
        }
 
        if (this.logicalSessionTimeoutMinutes == null) {
          // First server with a non null logicalSessionsTimeout
          this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes;
          continue;
        }
 
        // Always select the smaller of the:
        // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout
        this.logicalSessionTimeoutMinutes = Math.min(
          this.logicalSessionTimeoutMinutes,
          server.logicalSessionTimeoutMinutes
        );
      }
    }
  }
 
  /**
   * Returns a new TopologyDescription based on the SrvPollingEvent
   * @internal
   */
  updateFromSrvPollingEvent(ev: SrvPollingEvent, srvMaxHosts = 0): TopologyDescription {
    /** The SRV addresses defines the set of addresses we should be using */
    const incomingHostnames = ev.hostnames();
    const currentHostnames = new Set(this.servers.keys());
 
    const hostnamesToAdd = new Set<string>(incomingHostnames);
    const hostnamesToRemove = new Set<string>();
    for (const hostname of currentHostnames) {
      // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames
      hostnamesToAdd.delete(hostname);
      if (!incomingHostnames.has(hostname)) {
        // If the SRV Records no longer include this hostname
        // we have to stop using it
        hostnamesToRemove.add(hostname);
      }
    }
 
    Iif (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) {
      // No new hosts to add and none to remove
      return this;
    }
 
    const serverDescriptions = new Map(this.servers);
    for (const removedHost of hostnamesToRemove) {
      serverDescriptions.delete(removedHost);
    }
 
    if (hostnamesToAdd.size > 0) {
      if (srvMaxHosts === 0) {
        // Add all!
        for (const hostToAdd of hostnamesToAdd) {
          serverDescriptions.set(hostToAdd, new ServerDescription(hostToAdd));
        }
      } else Eif (serverDescriptions.size < srvMaxHosts) {
        // Add only the amount needed to get us back to srvMaxHosts
        const selectedHosts = shuffle(hostnamesToAdd, srvMaxHosts - serverDescriptions.size);
        for (const selectedHostToAdd of selectedHosts) {
          serverDescriptions.set(selectedHostToAdd, new ServerDescription(selectedHostToAdd));
        }
      }
    }
 
    return new TopologyDescription(
      this.type,
      serverDescriptions,
      this.setName,
      this.maxSetVersion,
      this.maxElectionId,
      this.commonWireVersion,
      { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }
    );
  }
 
  /**
   * Returns a copy of this description updated with a given ServerDescription
   * @internal
   */
  update(serverDescription: ServerDescription): TopologyDescription {
    const address = serverDescription.address;
 
    // potentially mutated values
    let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this;
 
    const serverType = serverDescription.type;
    const serverDescriptions = new Map(this.servers);
 
    // update common wire version
    if (serverDescription.maxWireVersion !== 0) {
      Iif (commonWireVersion == null) {
        commonWireVersion = serverDescription.maxWireVersion;
      } else {
        commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);
      }
    }
 
    if (
      typeof serverDescription.setName === 'string' &&
      typeof setName === 'string' &&
      serverDescription.setName !== setName
    ) {
      if (topologyType === TopologyType.Single) {
        // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove
        serverDescription = new ServerDescription(address);
      } else {
        serverDescriptions.delete(address);
      }
    }
 
    // update the actual server description
    serverDescriptions.set(address, serverDescription);
 
    if (topologyType === TopologyType.Single) {
      // once we are defined as single, that never changes
      return new TopologyDescription(
        TopologyType.Single,
        serverDescriptions,
        setName,
        maxSetVersion,
        maxElectionId,
        commonWireVersion,
        { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }
      );
    }
 
    if (topologyType === TopologyType.Unknown) {
      if (serverType === ServerType.Standalone && this.servers.size !== 1) {
        serverDescriptions.delete(address);
      } else {
        topologyType = topologyTypeForServerType(serverType);
      }
    }
 
    if (topologyType === TopologyType.Sharded) {
      if (!MONGOS_OR_UNKNOWN.has(serverType)) {
        serverDescriptions.delete(address);
      }
    }
 
    if (topologyType === TopologyType.ReplicaSetNoPrimary) {
      if (MONGOS_OR_STANDALONE.has(serverType)) {
        serverDescriptions.delete(address);
      }
 
      if (serverType === ServerType.RSPrimary) {
        const result = updateRsFromPrimary(
          serverDescriptions,
          serverDescription,
          setName,
          maxSetVersion,
          maxElectionId
        );
 
        topologyType = result[0];
        setName = result[1];
        maxSetVersion = result[2];
        maxElectionId = result[3];
      } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
        const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName);
        topologyType = result[0];
        setName = result[1];
      }
    }
 
    if (topologyType === TopologyType.ReplicaSetWithPrimary) {
      if (MONGOS_OR_STANDALONE.has(serverType)) {
        serverDescriptions.delete(address);
        topologyType = checkHasPrimary(serverDescriptions);
      } else if (serverType === ServerType.RSPrimary) {
        const result = updateRsFromPrimary(
          serverDescriptions,
          serverDescription,
          setName,
          maxSetVersion,
          maxElectionId
        );
 
        topologyType = result[0];
        setName = result[1];
        maxSetVersion = result[2];
        maxElectionId = result[3];
      } else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
        topologyType = updateRsWithPrimaryFromMember(
          serverDescriptions,
          serverDescription,
          setName
        );
      } else {
        topologyType = checkHasPrimary(serverDescriptions);
      }
    }
 
    return new TopologyDescription(
      topologyType,
      serverDescriptions,
      setName,
      maxSetVersion,
      maxElectionId,
      commonWireVersion,
      { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS }
    );
  }
 
  get error(): MongoError | null {
    const descriptionsWithError = Array.from(this.servers.values()).filter(
      (sd: ServerDescription) => sd.error
    );
 
    if (descriptionsWithError.length > 0) {
      return descriptionsWithError[0].error;
    }
 
    return null;
  }
 
  /**
   * Determines if the topology description has any known servers
   */
  get hasKnownServers(): boolean {
    return Array.from(this.servers.values()).some(
      (sd: ServerDescription) => sd.type !== ServerType.Unknown
    );
  }
 
  /**
   * Determines if this topology description has a data-bearing server available.
   */
  get hasDataBearingServers(): boolean {
    return Array.from(this.servers.values()).some((sd: ServerDescription) => sd.isDataBearing);
  }
 
  /**
   * Determines if the topology has a definition for the provided address
   * @internal
   */
  hasServer(address: string): boolean {
    return this.servers.has(address);
  }
 
  /**
   * Returns a JSON-serializable representation of the TopologyDescription.  This is primarily
   * intended for use with JSON.stringify().
   *
   * This method will not throw.
   */
  toJSON() {
    return EJSON.serialize(this);
  }
}
 
function topologyTypeForServerType(serverType: ServerType): TopologyType {
  switch (serverType) {
    case ServerType.Standalone:
      return TopologyType.Single;
    case ServerType.Mongos:
      return TopologyType.Sharded;
    case ServerType.RSPrimary:
      return TopologyType.ReplicaSetWithPrimary;
    case ServerType.RSOther:
    case ServerType.RSSecondary:
      return TopologyType.ReplicaSetNoPrimary;
    default:
      return TopologyType.Unknown;
  }
}
 
function updateRsFromPrimary(
  serverDescriptions: Map<string, ServerDescription>,
  serverDescription: ServerDescription,
  setName: string | null = null,
  maxSetVersion: number | null = null,
  maxElectionId: ObjectId | null = null
): [TopologyType, string | null, number | null, ObjectId | null] {
  const setVersionElectionIdMismatch = (
    serverDescription: ServerDescription,
    maxSetVersion: number | null,
    maxElectionId: ObjectId | null
  ) => {
    return (
      `primary marked stale due to electionId/setVersion mismatch:` +
      ` server setVersion: ${serverDescription.setVersion},` +
      ` server electionId: ${serverDescription.electionId},` +
      ` topology setVersion: ${maxSetVersion},` +
      ` topology electionId: ${maxElectionId}`
    );
  };
  setName = setName || serverDescription.setName;
  if (setName !== serverDescription.setName) {
    serverDescriptions.delete(serverDescription.address);
    return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  }
 
  if (serverDescription.maxWireVersion >= 17) {
    const electionIdComparison = compareObjectId(maxElectionId, serverDescription.electionId);
    const maxElectionIdIsEqual = electionIdComparison === 0;
    const maxElectionIdIsLess = electionIdComparison === -1;
    const maxSetVersionIsLessOrEqual =
      (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1);
 
    if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) {
      // The reported electionId was greater
      // or the electionId was equal and reported setVersion was greater
      // Always update both values, they are a tuple
      maxElectionId = serverDescription.electionId;
      maxSetVersion = serverDescription.setVersion;
    } else {
      // Stale primary
      // replace serverDescription with a default ServerDescription of type "Unknown"
      serverDescriptions.set(
        serverDescription.address,
        new ServerDescription(serverDescription.address, undefined, {
          error: new MongoStalePrimaryError(
            setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId)
          )
        })
      );
 
      return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
    }
  } else {
    const electionId = serverDescription.electionId ? serverDescription.electionId : null;
    if (serverDescription.setVersion && electionId) {
      if (maxSetVersion && maxElectionId) {
        if (
          maxSetVersion > serverDescription.setVersion ||
          compareObjectId(maxElectionId, electionId) > 0
        ) {
          // this primary is stale, we must remove it
          serverDescriptions.set(
            serverDescription.address,
            new ServerDescription(serverDescription.address, undefined, {
              error: new MongoStalePrimaryError(
                setVersionElectionIdMismatch(serverDescription, maxSetVersion, maxElectionId)
              )
            })
          );
 
          return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
        }
      }
 
      maxElectionId = serverDescription.electionId;
    }
 
    if (
      serverDescription.setVersion != null &&
      (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)
    ) {
      maxSetVersion = serverDescription.setVersion;
    }
  }
 
  // We've heard from the primary. Is it the same primary as before?
  for (const [address, server] of serverDescriptions) {
    if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) {
      // Reset old primary's type to Unknown.
      serverDescriptions.set(
        address,
        new ServerDescription(server.address, undefined, {
          error: new MongoStalePrimaryError(
            'primary marked stale due to discovery of newer primary'
          )
        })
      );
 
      // There can only be one primary
      break;
    }
  }
 
  // Discover new hosts from this primary's response.
  serverDescription.allHosts.forEach((address: string) => {
    if (!serverDescriptions.has(address)) {
      serverDescriptions.set(address, new ServerDescription(address));
    }
  });
 
  // Remove hosts not in the response.
  const currentAddresses = Array.from(serverDescriptions.keys());
  const responseAddresses = serverDescription.allHosts;
  currentAddresses
    .filter((addr: string) => responseAddresses.indexOf(addr) === -1)
    .forEach((address: string) => {
      serverDescriptions.delete(address);
    });
 
  return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
}
 
function updateRsWithPrimaryFromMember(
  serverDescriptions: Map<string, ServerDescription>,
  serverDescription: ServerDescription,
  setName: string | null = null
): TopologyType {
  Iif (setName == null) {
    // TODO(NODE-3483): should be an appropriate runtime error
    throw new MongoRuntimeError('Argument "setName" is required if connected to a replica set');
  }
 
  if (
    setName !== serverDescription.setName ||
    (serverDescription.me && serverDescription.address !== serverDescription.me)
  ) {
    serverDescriptions.delete(serverDescription.address);
  }
 
  return checkHasPrimary(serverDescriptions);
}
 
function updateRsNoPrimaryFromMember(
  serverDescriptions: Map<string, ServerDescription>,
  serverDescription: ServerDescription,
  setName: string | null = null
): [TopologyType, string | null] {
  const topologyType = TopologyType.ReplicaSetNoPrimary;
  setName = setName ?? serverDescription.setName;
  if (setName !== serverDescription.setName) {
    serverDescriptions.delete(serverDescription.address);
    return [topologyType, setName];
  }
 
  serverDescription.allHosts.forEach((address: string) => {
    if (!serverDescriptions.has(address)) {
      serverDescriptions.set(address, new ServerDescription(address));
    }
  });
 
  if (serverDescription.me && serverDescription.address !== serverDescription.me) {
    serverDescriptions.delete(serverDescription.address);
  }
 
  return [topologyType, setName];
}
 
function checkHasPrimary(serverDescriptions: Map<string, ServerDescription>): TopologyType {
  for (const serverDescription of serverDescriptions.values()) {
    if (serverDescription.type === ServerType.RSPrimary) {
      return TopologyType.ReplicaSetWithPrimary;
    }
  }
 
  return TopologyType.ReplicaSetNoPrimary;
}