topology_description.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.TopologyDescription = void 0;
  4. const WIRE_CONSTANTS = require("../cmap/wire_protocol/constants");
  5. const error_1 = require("../error");
  6. const utils_1 = require("../utils");
  7. const common_1 = require("./common");
  8. const server_description_1 = require("./server_description");
  9. // constants related to compatibility checks
  10. const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION;
  11. const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION;
  12. const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION;
  13. const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION;
  14. const MONGOS_OR_UNKNOWN = new Set([common_1.ServerType.Mongos, common_1.ServerType.Unknown]);
  15. const MONGOS_OR_STANDALONE = new Set([common_1.ServerType.Mongos, common_1.ServerType.Standalone]);
  16. const NON_PRIMARY_RS_MEMBERS = new Set([
  17. common_1.ServerType.RSSecondary,
  18. common_1.ServerType.RSArbiter,
  19. common_1.ServerType.RSOther
  20. ]);
  21. /**
  22. * Representation of a deployment of servers
  23. * @public
  24. */
  25. class TopologyDescription {
  26. /**
  27. * Create a TopologyDescription
  28. */
  29. constructor(topologyType, serverDescriptions = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) {
  30. options = options ?? {};
  31. this.type = topologyType ?? common_1.TopologyType.Unknown;
  32. this.servers = serverDescriptions ?? new Map();
  33. this.stale = false;
  34. this.compatible = true;
  35. this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0;
  36. this.localThresholdMS = options.localThresholdMS ?? 15;
  37. this.setName = setName ?? null;
  38. this.maxElectionId = maxElectionId ?? null;
  39. this.maxSetVersion = maxSetVersion ?? null;
  40. this.commonWireVersion = commonWireVersion ?? 0;
  41. // determine server compatibility
  42. for (const serverDescription of this.servers.values()) {
  43. // Load balancer mode is always compatible.
  44. if (serverDescription.type === common_1.ServerType.Unknown ||
  45. serverDescription.type === common_1.ServerType.LoadBalancer) {
  46. continue;
  47. }
  48. if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) {
  49. this.compatible = false;
  50. 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})`;
  51. }
  52. if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) {
  53. this.compatible = false;
  54. 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}).`;
  55. break;
  56. }
  57. }
  58. // Whenever a client updates the TopologyDescription from a hello response, it MUST set
  59. // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes
  60. // value among ServerDescriptions of all data-bearing server types. If any have a null
  61. // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be
  62. // set to null.
  63. this.logicalSessionTimeoutMinutes = null;
  64. for (const [, server] of this.servers) {
  65. if (server.isReadable) {
  66. if (server.logicalSessionTimeoutMinutes == null) {
  67. // If any of the servers have a null logicalSessionsTimeout, then the whole topology does
  68. this.logicalSessionTimeoutMinutes = null;
  69. break;
  70. }
  71. if (this.logicalSessionTimeoutMinutes == null) {
  72. // First server with a non null logicalSessionsTimeout
  73. this.logicalSessionTimeoutMinutes = server.logicalSessionTimeoutMinutes;
  74. continue;
  75. }
  76. // Always select the smaller of the:
  77. // current server logicalSessionsTimeout and the topologies logicalSessionsTimeout
  78. this.logicalSessionTimeoutMinutes = Math.min(this.logicalSessionTimeoutMinutes, server.logicalSessionTimeoutMinutes);
  79. }
  80. }
  81. }
  82. /**
  83. * Returns a new TopologyDescription based on the SrvPollingEvent
  84. * @internal
  85. */
  86. updateFromSrvPollingEvent(ev, srvMaxHosts = 0) {
  87. /** The SRV addresses defines the set of addresses we should be using */
  88. const incomingHostnames = ev.hostnames();
  89. const currentHostnames = new Set(this.servers.keys());
  90. const hostnamesToAdd = new Set(incomingHostnames);
  91. const hostnamesToRemove = new Set();
  92. for (const hostname of currentHostnames) {
  93. // filter hostnamesToAdd (made from incomingHostnames) down to what is *not* present in currentHostnames
  94. hostnamesToAdd.delete(hostname);
  95. if (!incomingHostnames.has(hostname)) {
  96. // If the SRV Records no longer include this hostname
  97. // we have to stop using it
  98. hostnamesToRemove.add(hostname);
  99. }
  100. }
  101. if (hostnamesToAdd.size === 0 && hostnamesToRemove.size === 0) {
  102. // No new hosts to add and none to remove
  103. return this;
  104. }
  105. const serverDescriptions = new Map(this.servers);
  106. for (const removedHost of hostnamesToRemove) {
  107. serverDescriptions.delete(removedHost);
  108. }
  109. if (hostnamesToAdd.size > 0) {
  110. if (srvMaxHosts === 0) {
  111. // Add all!
  112. for (const hostToAdd of hostnamesToAdd) {
  113. serverDescriptions.set(hostToAdd, new server_description_1.ServerDescription(hostToAdd));
  114. }
  115. }
  116. else if (serverDescriptions.size < srvMaxHosts) {
  117. // Add only the amount needed to get us back to srvMaxHosts
  118. const selectedHosts = (0, utils_1.shuffle)(hostnamesToAdd, srvMaxHosts - serverDescriptions.size);
  119. for (const selectedHostToAdd of selectedHosts) {
  120. serverDescriptions.set(selectedHostToAdd, new server_description_1.ServerDescription(selectedHostToAdd));
  121. }
  122. }
  123. }
  124. return new TopologyDescription(this.type, serverDescriptions, this.setName, this.maxSetVersion, this.maxElectionId, this.commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  125. }
  126. /**
  127. * Returns a copy of this description updated with a given ServerDescription
  128. * @internal
  129. */
  130. update(serverDescription) {
  131. const address = serverDescription.address;
  132. // potentially mutated values
  133. let { type: topologyType, setName, maxSetVersion, maxElectionId, commonWireVersion } = this;
  134. const serverType = serverDescription.type;
  135. const serverDescriptions = new Map(this.servers);
  136. // update common wire version
  137. if (serverDescription.maxWireVersion !== 0) {
  138. if (commonWireVersion == null) {
  139. commonWireVersion = serverDescription.maxWireVersion;
  140. }
  141. else {
  142. commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion);
  143. }
  144. }
  145. if (typeof serverDescription.setName === 'string' &&
  146. typeof setName === 'string' &&
  147. serverDescription.setName !== setName) {
  148. if (topologyType === common_1.TopologyType.Single) {
  149. // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove
  150. serverDescription = new server_description_1.ServerDescription(address);
  151. }
  152. else {
  153. serverDescriptions.delete(address);
  154. }
  155. }
  156. // update the actual server description
  157. serverDescriptions.set(address, serverDescription);
  158. if (topologyType === common_1.TopologyType.Single) {
  159. // once we are defined as single, that never changes
  160. return new TopologyDescription(common_1.TopologyType.Single, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  161. }
  162. if (topologyType === common_1.TopologyType.Unknown) {
  163. if (serverType === common_1.ServerType.Standalone && this.servers.size !== 1) {
  164. serverDescriptions.delete(address);
  165. }
  166. else {
  167. topologyType = topologyTypeForServerType(serverType);
  168. }
  169. }
  170. if (topologyType === common_1.TopologyType.Sharded) {
  171. if (!MONGOS_OR_UNKNOWN.has(serverType)) {
  172. serverDescriptions.delete(address);
  173. }
  174. }
  175. if (topologyType === common_1.TopologyType.ReplicaSetNoPrimary) {
  176. if (MONGOS_OR_STANDALONE.has(serverType)) {
  177. serverDescriptions.delete(address);
  178. }
  179. if (serverType === common_1.ServerType.RSPrimary) {
  180. const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
  181. topologyType = result[0];
  182. setName = result[1];
  183. maxSetVersion = result[2];
  184. maxElectionId = result[3];
  185. }
  186. else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
  187. const result = updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName);
  188. topologyType = result[0];
  189. setName = result[1];
  190. }
  191. }
  192. if (topologyType === common_1.TopologyType.ReplicaSetWithPrimary) {
  193. if (MONGOS_OR_STANDALONE.has(serverType)) {
  194. serverDescriptions.delete(address);
  195. topologyType = checkHasPrimary(serverDescriptions);
  196. }
  197. else if (serverType === common_1.ServerType.RSPrimary) {
  198. const result = updateRsFromPrimary(serverDescriptions, serverDescription, setName, maxSetVersion, maxElectionId);
  199. topologyType = result[0];
  200. setName = result[1];
  201. maxSetVersion = result[2];
  202. maxElectionId = result[3];
  203. }
  204. else if (NON_PRIMARY_RS_MEMBERS.has(serverType)) {
  205. topologyType = updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName);
  206. }
  207. else {
  208. topologyType = checkHasPrimary(serverDescriptions);
  209. }
  210. }
  211. return new TopologyDescription(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, commonWireVersion, { heartbeatFrequencyMS: this.heartbeatFrequencyMS, localThresholdMS: this.localThresholdMS });
  212. }
  213. get error() {
  214. const descriptionsWithError = Array.from(this.servers.values()).filter((sd) => sd.error);
  215. if (descriptionsWithError.length > 0) {
  216. return descriptionsWithError[0].error;
  217. }
  218. return null;
  219. }
  220. /**
  221. * Determines if the topology description has any known servers
  222. */
  223. get hasKnownServers() {
  224. return Array.from(this.servers.values()).some((sd) => sd.type !== common_1.ServerType.Unknown);
  225. }
  226. /**
  227. * Determines if this topology description has a data-bearing server available.
  228. */
  229. get hasDataBearingServers() {
  230. return Array.from(this.servers.values()).some((sd) => sd.isDataBearing);
  231. }
  232. /**
  233. * Determines if the topology has a definition for the provided address
  234. * @internal
  235. */
  236. hasServer(address) {
  237. return this.servers.has(address);
  238. }
  239. }
  240. exports.TopologyDescription = TopologyDescription;
  241. function topologyTypeForServerType(serverType) {
  242. switch (serverType) {
  243. case common_1.ServerType.Standalone:
  244. return common_1.TopologyType.Single;
  245. case common_1.ServerType.Mongos:
  246. return common_1.TopologyType.Sharded;
  247. case common_1.ServerType.RSPrimary:
  248. return common_1.TopologyType.ReplicaSetWithPrimary;
  249. case common_1.ServerType.RSOther:
  250. case common_1.ServerType.RSSecondary:
  251. return common_1.TopologyType.ReplicaSetNoPrimary;
  252. default:
  253. return common_1.TopologyType.Unknown;
  254. }
  255. }
  256. function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) {
  257. setName = setName || serverDescription.setName;
  258. if (setName !== serverDescription.setName) {
  259. serverDescriptions.delete(serverDescription.address);
  260. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  261. }
  262. if (serverDescription.maxWireVersion >= 17) {
  263. const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId);
  264. const maxElectionIdIsEqual = electionIdComparison === 0;
  265. const maxElectionIdIsLess = electionIdComparison === -1;
  266. const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1);
  267. if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) {
  268. // The reported electionId was greater
  269. // or the electionId was equal and reported setVersion was greater
  270. // Always update both values, they are a tuple
  271. maxElectionId = serverDescription.electionId;
  272. maxSetVersion = serverDescription.setVersion;
  273. }
  274. else {
  275. // Stale primary
  276. // replace serverDescription with a default ServerDescription of type "Unknown"
  277. serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address));
  278. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  279. }
  280. }
  281. else {
  282. const electionId = serverDescription.electionId ? serverDescription.electionId : null;
  283. if (serverDescription.setVersion && electionId) {
  284. if (maxSetVersion && maxElectionId) {
  285. if (maxSetVersion > serverDescription.setVersion ||
  286. (0, utils_1.compareObjectId)(maxElectionId, electionId) > 0) {
  287. // this primary is stale, we must remove it
  288. serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address));
  289. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  290. }
  291. }
  292. maxElectionId = serverDescription.electionId;
  293. }
  294. if (serverDescription.setVersion != null &&
  295. (maxSetVersion == null || serverDescription.setVersion > maxSetVersion)) {
  296. maxSetVersion = serverDescription.setVersion;
  297. }
  298. }
  299. // We've heard from the primary. Is it the same primary as before?
  300. for (const [address, server] of serverDescriptions) {
  301. if (server.type === common_1.ServerType.RSPrimary && server.address !== serverDescription.address) {
  302. // Reset old primary's type to Unknown.
  303. serverDescriptions.set(address, new server_description_1.ServerDescription(server.address));
  304. // There can only be one primary
  305. break;
  306. }
  307. }
  308. // Discover new hosts from this primary's response.
  309. serverDescription.allHosts.forEach((address) => {
  310. if (!serverDescriptions.has(address)) {
  311. serverDescriptions.set(address, new server_description_1.ServerDescription(address));
  312. }
  313. });
  314. // Remove hosts not in the response.
  315. const currentAddresses = Array.from(serverDescriptions.keys());
  316. const responseAddresses = serverDescription.allHosts;
  317. currentAddresses
  318. .filter((addr) => responseAddresses.indexOf(addr) === -1)
  319. .forEach((address) => {
  320. serverDescriptions.delete(address);
  321. });
  322. return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId];
  323. }
  324. function updateRsWithPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
  325. if (setName == null) {
  326. // TODO(NODE-3483): should be an appropriate runtime error
  327. throw new error_1.MongoRuntimeError('Argument "setName" is required if connected to a replica set');
  328. }
  329. if (setName !== serverDescription.setName ||
  330. (serverDescription.me && serverDescription.address !== serverDescription.me)) {
  331. serverDescriptions.delete(serverDescription.address);
  332. }
  333. return checkHasPrimary(serverDescriptions);
  334. }
  335. function updateRsNoPrimaryFromMember(serverDescriptions, serverDescription, setName = null) {
  336. const topologyType = common_1.TopologyType.ReplicaSetNoPrimary;
  337. setName = setName ?? serverDescription.setName;
  338. if (setName !== serverDescription.setName) {
  339. serverDescriptions.delete(serverDescription.address);
  340. return [topologyType, setName];
  341. }
  342. serverDescription.allHosts.forEach((address) => {
  343. if (!serverDescriptions.has(address)) {
  344. serverDescriptions.set(address, new server_description_1.ServerDescription(address));
  345. }
  346. });
  347. if (serverDescription.me && serverDescription.address !== serverDescription.me) {
  348. serverDescriptions.delete(serverDescription.address);
  349. }
  350. return [topologyType, setName];
  351. }
  352. function checkHasPrimary(serverDescriptions) {
  353. for (const serverDescription of serverDescriptions.values()) {
  354. if (serverDescription.type === common_1.ServerType.RSPrimary) {
  355. return common_1.TopologyType.ReplicaSetWithPrimary;
  356. }
  357. }
  358. return common_1.TopologyType.ReplicaSetNoPrimary;
  359. }
  360. //# sourceMappingURL=topology_description.js.map