topology_description.js 17 KB

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