All files / src/sdam server_selection.ts

96.42% Statements 108/112
90.36% Branches 75/83
100% Functions 25/25
96.26% Lines 103/107

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 335568x 568x 568x         568x 568x     568x                       568x 64x       64x   92x                 568x 611489x       617043x     617039x 1062079x                 568x               5473x         5457x   16x                                     28827x 28743x     84x   84x 84x 4x         80x 4x         76x 40x       40x   104x         104x 104x 104x 68x     104x       36x 36x       36x 60x     36x   96x   96x 96x 96x 64x     96x                           1763x 1763x 1763x 1767x 1767x 1635x       128x                           28819x       27055x     1764x 1780x 1780x   1763x 1763x         1780x 76x       1688x                                 9965147x 11063343x       9965147x 9965147x 11063343x 11063343x           17597104x       35113x       48562x       11076756x       1455631x               568x 16752568x       16752568x         18813957x 18813957x                   18813957x 1455631x     17358326x 1130238x     16228088x 3862334x     12365754x 6073930x 7214522x   6073930x 6073930x     6291824x 6291824x 5024952x     1266872x 1247109x 1247109x 1238045x       28827x 28827x               28819x 16x     28803x      
import { MongoCompatibilityError, MongoInvalidArgumentError } from '../error';
import { ReadPreference } from '../read_preference';
import { ServerType, TopologyType } from './common';
import type { ServerDescription, TagSet } from './server_description';
import type { TopologyDescription } from './topology_description';
 
// max staleness constants
const IDLE_WRITE_PERIOD = 10000;
const SMALLEST_MAX_STALENESS_SECONDS = 90;
 
//  Minimum version to try writes on secondaries.
export const MIN_SECONDARY_WRITE_WIRE_VERSION = 13;
 
/** @internal */
export type ServerSelector = (
  topologyDescription: TopologyDescription,
  servers: ServerDescription[],
  deprioritized?: ServerDescription[]
) => ServerDescription[];
 
/**
 * Returns a server selector that selects for writable servers
 */
export function writableServerSelector(): ServerSelector {
  return function writableServer(
    topologyDescription: TopologyDescription,
    servers: ServerDescription[]
  ): ServerDescription[] {
    return latencyWindowReducer(
      topologyDescription,
      servers.filter((s: ServerDescription) => s.isWritable)
    );
  };
}
 
/**
 * The purpose of this selector is to select the same server, only
 * if it is in a state that it can have commands sent to it.
 */
export function sameServerSelector(description?: ServerDescription): ServerSelector {
  return function sameServerSelector(
    topologyDescription: TopologyDescription,
    servers: ServerDescription[]
  ): ServerDescription[] {
    if (!description) return [];
    // Filter the servers to match the provided description only if
    // the type is not unknown.
    return servers.filter(sd => {
      return sd.address === description.address && sd.type !== ServerType.Unknown;
    });
  };
}
 
/**
 * Returns a server selector that uses a read preference to select a
 * server potentially for a write on a secondary.
 */
export function secondaryWritableServerSelector(
  wireVersion?: number,
  readPreference?: ReadPreference
): ServerSelector {
  // If server version < 5.0, read preference always primary.
  // If server version >= 5.0...
  // - If read preference is supplied, use that.
  // - If no read preference is supplied, use primary.
  if (
    !readPreference ||
    !wireVersion ||
    (wireVersion && wireVersion < MIN_SECONDARY_WRITE_WIRE_VERSION)
  ) {
    return readPreferenceServerSelector(ReadPreference.primary);
  }
  return readPreferenceServerSelector(readPreference);
}
 
/**
 * Reduces the passed in array of servers by the rules of the "Max Staleness" specification
 * found here:
 *
 * @see https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.md
 *
 * @param readPreference - The read preference providing max staleness guidance
 * @param topologyDescription - The topology description
 * @param servers - The list of server descriptions to be reduced
 * @returns The list of servers that satisfy the requirements of max staleness
 */
function maxStalenessReducer(
  readPreference: ReadPreference,
  topologyDescription: TopologyDescription,
  servers: ServerDescription[]
): ServerDescription[] {
  if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) {
    return servers;
  }
 
  const maxStaleness = readPreference.maxStalenessSeconds;
  const maxStalenessVariance =
    (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000;
  if (maxStaleness < maxStalenessVariance) {
    throw new MongoInvalidArgumentError(
      `Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`
    );
  }
 
  if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) {
    throw new MongoInvalidArgumentError(
      `Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`
    );
  }
 
  if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) {
    const primary: ServerDescription = Array.from(topologyDescription.servers.values()).filter(
      primaryFilter
    )[0];
 
    return servers.reduce((result: ServerDescription[], server: ServerDescription) => {
      const stalenessMS =
        server.lastUpdateTime -
        server.lastWriteDate -
        (primary.lastUpdateTime - primary.lastWriteDate) +
        topologyDescription.heartbeatFrequencyMS;
 
      const staleness = stalenessMS / 1000;
      const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
      if (staleness <= maxStalenessSeconds) {
        result.push(server);
      }
 
      return result;
    }, []);
  }
 
  Eif (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) {
    Iif (servers.length === 0) {
      return servers;
    }
 
    const sMax = servers.reduce((max: ServerDescription, s: ServerDescription) =>
      s.lastWriteDate > max.lastWriteDate ? s : max
    );
 
    return servers.reduce((result: ServerDescription[], server: ServerDescription) => {
      const stalenessMS =
        sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS;
 
      const staleness = stalenessMS / 1000;
      const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0;
      if (staleness <= maxStalenessSeconds) {
        result.push(server);
      }
 
      return result;
    }, []);
  }
 
  return servers;
}
 
/**
 * Determines whether a server's tags match a given set of tags
 *
 * @param tagSet - The requested tag set to match
 * @param serverTags - The server's tags
 */
function tagSetMatch(tagSet: TagSet, serverTags: TagSet) {
  const keys = Object.keys(tagSet);
  const serverTagKeys = Object.keys(serverTags);
  for (let i = 0; i < keys.length; ++i) {
    const key = keys[i];
    if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) {
      return false;
    }
  }
 
  return true;
}
 
/**
 * Reduces a set of server descriptions based on tags requested by the read preference
 *
 * @param readPreference - The read preference providing the requested tags
 * @param servers - The list of server descriptions to reduce
 * @returns The list of servers matching the requested tags
 */
function tagSetReducer(
  readPreference: ReadPreference,
  servers: ServerDescription[]
): ServerDescription[] {
  if (
    readPreference.tags == null ||
    (Array.isArray(readPreference.tags) && readPreference.tags.length === 0)
  ) {
    return servers;
  }
 
  for (let i = 0; i < readPreference.tags.length; ++i) {
    const tagSet = readPreference.tags[i];
    const serversMatchingTagset = servers.reduce(
      (matched: ServerDescription[], server: ServerDescription) => {
        if (tagSetMatch(tagSet, server.tags)) matched.push(server);
        return matched;
      },
      []
    );
 
    if (serversMatchingTagset.length) {
      return serversMatchingTagset;
    }
  }
 
  return [];
}
 
/**
 * Reduces a list of servers to ensure they fall within an acceptable latency window. This is
 * further specified in the "Server Selection" specification, found here:
 *
 * @see https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.md
 *
 * @param topologyDescription - The topology description
 * @param servers - The list of servers to reduce
 * @returns The servers which fall within an acceptable latency window
 */
function latencyWindowReducer(
  topologyDescription: TopologyDescription,
  servers: ServerDescription[]
): ServerDescription[] {
  const low = servers.reduce(
    (min: number, server: ServerDescription) => Math.min(server.roundTripTime, min),
    Infinity
  );
 
  const high = low + topologyDescription.localThresholdMS;
  return servers.reduce((result: ServerDescription[], server: ServerDescription) => {
    if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server);
    return result;
  }, []);
}
 
// filters
function primaryFilter(server: ServerDescription): boolean {
  return server.type === ServerType.RSPrimary;
}
 
function secondaryFilter(server: ServerDescription): boolean {
  return server.type === ServerType.RSSecondary;
}
 
function nearestFilter(server: ServerDescription): boolean {
  return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary;
}
 
function knownFilter(server: ServerDescription): boolean {
  return server.type !== ServerType.Unknown;
}
 
function loadBalancerFilter(server: ServerDescription): boolean {
  return server.type === ServerType.LoadBalancer;
}
 
/**
 * Returns a function which selects servers based on a provided read preference
 *
 * @param readPreference - The read preference to select with
 */
export function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector {
  Iif (!readPreference.isValid()) {
    throw new MongoInvalidArgumentError('Invalid read preference specified');
  }
 
  return function readPreferenceServers(
    topologyDescription: TopologyDescription,
    servers: ServerDescription[],
    deprioritized: ServerDescription[] = []
  ): ServerDescription[] {
    const commonWireVersion = topologyDescription.commonWireVersion;
    Iif (
      commonWireVersion &&
      readPreference.minWireVersion &&
      readPreference.minWireVersion > commonWireVersion
    ) {
      throw new MongoCompatibilityError(
        `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'`
      );
    }
 
    if (topologyDescription.type === TopologyType.LoadBalanced) {
      return servers.filter(loadBalancerFilter);
    }
 
    if (topologyDescription.type === TopologyType.Unknown) {
      return [];
    }
 
    if (topologyDescription.type === TopologyType.Single) {
      return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));
    }
 
    if (topologyDescription.type === TopologyType.Sharded) {
      const filtered = servers.filter(server => {
        return !deprioritized.includes(server);
      });
      const selectable = filtered.length > 0 ? filtered : deprioritized;
      return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter));
    }
 
    const mode = readPreference.mode;
    if (mode === ReadPreference.PRIMARY) {
      return servers.filter(primaryFilter);
    }
 
    if (mode === ReadPreference.PRIMARY_PREFERRED) {
      const result = servers.filter(primaryFilter);
      if (result.length) {
        return result;
      }
    }
 
    const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter;
    const selectedServers = latencyWindowReducer(
      topologyDescription,
      tagSetReducer(
        readPreference,
        maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter))
      )
    );
 
    if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) {
      return servers.filter(primaryFilter);
    }
 
    return selectedServers;
  };
}