topology_description.js 19 KB

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