@depup/mongodb 7.1.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (396) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +33 -0
  3. package/etc/prepare.js +12 -0
  4. package/lib/admin.js +136 -0
  5. package/lib/admin.js.map +1 -0
  6. package/lib/bson.js +85 -0
  7. package/lib/bson.js.map +1 -0
  8. package/lib/bulk/common.js +835 -0
  9. package/lib/bulk/common.js.map +1 -0
  10. package/lib/bulk/ordered.js +67 -0
  11. package/lib/bulk/ordered.js.map +1 -0
  12. package/lib/bulk/unordered.js +92 -0
  13. package/lib/bulk/unordered.js.map +1 -0
  14. package/lib/change_stream.js +513 -0
  15. package/lib/change_stream.js.map +1 -0
  16. package/lib/client-side-encryption/auto_encrypter.js +272 -0
  17. package/lib/client-side-encryption/auto_encrypter.js.map +1 -0
  18. package/lib/client-side-encryption/client_encryption.js +609 -0
  19. package/lib/client-side-encryption/client_encryption.js.map +1 -0
  20. package/lib/client-side-encryption/errors.js +138 -0
  21. package/lib/client-side-encryption/errors.js.map +1 -0
  22. package/lib/client-side-encryption/mongocryptd_manager.js +85 -0
  23. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -0
  24. package/lib/client-side-encryption/providers/aws.js +23 -0
  25. package/lib/client-side-encryption/providers/aws.js.map +1 -0
  26. package/lib/client-side-encryption/providers/azure.js +132 -0
  27. package/lib/client-side-encryption/providers/azure.js.map +1 -0
  28. package/lib/client-side-encryption/providers/gcp.js +16 -0
  29. package/lib/client-side-encryption/providers/gcp.js.map +1 -0
  30. package/lib/client-side-encryption/providers/index.js +43 -0
  31. package/lib/client-side-encryption/providers/index.js.map +1 -0
  32. package/lib/client-side-encryption/state_machine.js +427 -0
  33. package/lib/client-side-encryption/state_machine.js.map +1 -0
  34. package/lib/cmap/auth/auth_provider.js +51 -0
  35. package/lib/cmap/auth/auth_provider.js.map +1 -0
  36. package/lib/cmap/auth/aws4.js +161 -0
  37. package/lib/cmap/auth/aws4.js.map +1 -0
  38. package/lib/cmap/auth/aws_temporary_credentials.js +103 -0
  39. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -0
  40. package/lib/cmap/auth/gssapi.js +155 -0
  41. package/lib/cmap/auth/gssapi.js.map +1 -0
  42. package/lib/cmap/auth/mongo_credentials.js +169 -0
  43. package/lib/cmap/auth/mongo_credentials.js.map +1 -0
  44. package/lib/cmap/auth/mongodb_aws.js +128 -0
  45. package/lib/cmap/auth/mongodb_aws.js.map +1 -0
  46. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js +84 -0
  47. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -0
  48. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js +62 -0
  49. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -0
  50. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js +141 -0
  51. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -0
  52. package/lib/cmap/auth/mongodb_oidc/command_builders.js +44 -0
  53. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -0
  54. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js +39 -0
  55. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -0
  56. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js +122 -0
  57. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -0
  58. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js +32 -0
  59. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js.map +1 -0
  60. package/lib/cmap/auth/mongodb_oidc/token_cache.js +52 -0
  61. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -0
  62. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js +23 -0
  63. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -0
  64. package/lib/cmap/auth/mongodb_oidc.js +73 -0
  65. package/lib/cmap/auth/mongodb_oidc.js.map +1 -0
  66. package/lib/cmap/auth/plain.js +26 -0
  67. package/lib/cmap/auth/plain.js.map +1 -0
  68. package/lib/cmap/auth/providers.js +22 -0
  69. package/lib/cmap/auth/providers.js.map +1 -0
  70. package/lib/cmap/auth/scram.js +254 -0
  71. package/lib/cmap/auth/scram.js.map +1 -0
  72. package/lib/cmap/auth/x509.js +36 -0
  73. package/lib/cmap/auth/x509.js.map +1 -0
  74. package/lib/cmap/command_monitoring_events.js +223 -0
  75. package/lib/cmap/command_monitoring_events.js.map +1 -0
  76. package/lib/cmap/commands.js +535 -0
  77. package/lib/cmap/commands.js.map +1 -0
  78. package/lib/cmap/connect.js +381 -0
  79. package/lib/cmap/connect.js.map +1 -0
  80. package/lib/cmap/connection.js +571 -0
  81. package/lib/cmap/connection.js.map +1 -0
  82. package/lib/cmap/connection_pool.js +558 -0
  83. package/lib/cmap/connection_pool.js.map +1 -0
  84. package/lib/cmap/connection_pool_events.js +190 -0
  85. package/lib/cmap/connection_pool_events.js.map +1 -0
  86. package/lib/cmap/errors.js +108 -0
  87. package/lib/cmap/errors.js.map +1 -0
  88. package/lib/cmap/handshake/client_metadata.js +242 -0
  89. package/lib/cmap/handshake/client_metadata.js.map +1 -0
  90. package/lib/cmap/metrics.js +62 -0
  91. package/lib/cmap/metrics.js.map +1 -0
  92. package/lib/cmap/stream_description.js +70 -0
  93. package/lib/cmap/stream_description.js.map +1 -0
  94. package/lib/cmap/wire_protocol/compression.js +178 -0
  95. package/lib/cmap/wire_protocol/compression.js.map +1 -0
  96. package/lib/cmap/wire_protocol/constants.js +21 -0
  97. package/lib/cmap/wire_protocol/constants.js.map +1 -0
  98. package/lib/cmap/wire_protocol/on_data.js +111 -0
  99. package/lib/cmap/wire_protocol/on_data.js.map +1 -0
  100. package/lib/cmap/wire_protocol/on_demand/document.js +222 -0
  101. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -0
  102. package/lib/cmap/wire_protocol/responses.js +315 -0
  103. package/lib/cmap/wire_protocol/responses.js.map +1 -0
  104. package/lib/cmap/wire_protocol/shared.js +35 -0
  105. package/lib/cmap/wire_protocol/shared.js.map +1 -0
  106. package/lib/collection.js +751 -0
  107. package/lib/collection.js.map +1 -0
  108. package/lib/connection_string.js +1090 -0
  109. package/lib/connection_string.js.map +1 -0
  110. package/lib/constants.js +170 -0
  111. package/lib/constants.js.map +1 -0
  112. package/lib/cursor/abstract_cursor.js +924 -0
  113. package/lib/cursor/abstract_cursor.js.map +1 -0
  114. package/lib/cursor/aggregation_cursor.js +164 -0
  115. package/lib/cursor/aggregation_cursor.js.map +1 -0
  116. package/lib/cursor/change_stream_cursor.js +104 -0
  117. package/lib/cursor/change_stream_cursor.js.map +1 -0
  118. package/lib/cursor/client_bulk_write_cursor.js +52 -0
  119. package/lib/cursor/client_bulk_write_cursor.js.map +1 -0
  120. package/lib/cursor/explainable_cursor.js +36 -0
  121. package/lib/cursor/explainable_cursor.js.map +1 -0
  122. package/lib/cursor/find_cursor.js +399 -0
  123. package/lib/cursor/find_cursor.js.map +1 -0
  124. package/lib/cursor/list_collections_cursor.js +34 -0
  125. package/lib/cursor/list_collections_cursor.js.map +1 -0
  126. package/lib/cursor/list_indexes_cursor.js +32 -0
  127. package/lib/cursor/list_indexes_cursor.js.map +1 -0
  128. package/lib/cursor/list_search_indexes_cursor.js +14 -0
  129. package/lib/cursor/list_search_indexes_cursor.js.map +1 -0
  130. package/lib/cursor/run_command_cursor.js +94 -0
  131. package/lib/cursor/run_command_cursor.js.map +1 -0
  132. package/lib/db.js +419 -0
  133. package/lib/db.js.map +1 -0
  134. package/lib/deps.js +112 -0
  135. package/lib/deps.js.map +1 -0
  136. package/lib/encrypter.js +106 -0
  137. package/lib/encrypter.js.map +1 -0
  138. package/lib/error.js +1380 -0
  139. package/lib/error.js.map +1 -0
  140. package/lib/explain.js +59 -0
  141. package/lib/explain.js.map +1 -0
  142. package/lib/gridfs/download.js +305 -0
  143. package/lib/gridfs/download.js.map +1 -0
  144. package/lib/gridfs/index.js +164 -0
  145. package/lib/gridfs/index.js.map +1 -0
  146. package/lib/gridfs/upload.js +358 -0
  147. package/lib/gridfs/upload.js.map +1 -0
  148. package/lib/index.js +193 -0
  149. package/lib/index.js.map +1 -0
  150. package/lib/mongo_client.js +557 -0
  151. package/lib/mongo_client.js.map +1 -0
  152. package/lib/mongo_client_auth_providers.js +80 -0
  153. package/lib/mongo_client_auth_providers.js.map +1 -0
  154. package/lib/mongo_logger.js +655 -0
  155. package/lib/mongo_logger.js.map +1 -0
  156. package/lib/mongo_types.js +56 -0
  157. package/lib/mongo_types.js.map +1 -0
  158. package/lib/operations/aggregate.js +90 -0
  159. package/lib/operations/aggregate.js.map +1 -0
  160. package/lib/operations/client_bulk_write/client_bulk_write.js +51 -0
  161. package/lib/operations/client_bulk_write/client_bulk_write.js.map +1 -0
  162. package/lib/operations/client_bulk_write/command_builder.js +340 -0
  163. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  164. package/lib/operations/client_bulk_write/common.js +3 -0
  165. package/lib/operations/client_bulk_write/common.js.map +1 -0
  166. package/lib/operations/client_bulk_write/executor.js +120 -0
  167. package/lib/operations/client_bulk_write/executor.js.map +1 -0
  168. package/lib/operations/client_bulk_write/results_merger.js +204 -0
  169. package/lib/operations/client_bulk_write/results_merger.js.map +1 -0
  170. package/lib/operations/command.js +83 -0
  171. package/lib/operations/command.js.map +1 -0
  172. package/lib/operations/count.js +45 -0
  173. package/lib/operations/count.js.map +1 -0
  174. package/lib/operations/create_collection.js +109 -0
  175. package/lib/operations/create_collection.js.map +1 -0
  176. package/lib/operations/delete.js +125 -0
  177. package/lib/operations/delete.js.map +1 -0
  178. package/lib/operations/distinct.js +61 -0
  179. package/lib/operations/distinct.js.map +1 -0
  180. package/lib/operations/drop.js +93 -0
  181. package/lib/operations/drop.js.map +1 -0
  182. package/lib/operations/end_sessions.js +34 -0
  183. package/lib/operations/end_sessions.js.map +1 -0
  184. package/lib/operations/estimated_document_count.js +41 -0
  185. package/lib/operations/estimated_document_count.js.map +1 -0
  186. package/lib/operations/execute_operation.js +239 -0
  187. package/lib/operations/execute_operation.js.map +1 -0
  188. package/lib/operations/find.js +148 -0
  189. package/lib/operations/find.js.map +1 -0
  190. package/lib/operations/find_and_modify.js +158 -0
  191. package/lib/operations/find_and_modify.js.map +1 -0
  192. package/lib/operations/get_more.js +62 -0
  193. package/lib/operations/get_more.js.map +1 -0
  194. package/lib/operations/indexes.js +186 -0
  195. package/lib/operations/indexes.js.map +1 -0
  196. package/lib/operations/insert.js +70 -0
  197. package/lib/operations/insert.js.map +1 -0
  198. package/lib/operations/kill_cursors.js +43 -0
  199. package/lib/operations/kill_cursors.js.map +1 -0
  200. package/lib/operations/list_collections.js +53 -0
  201. package/lib/operations/list_collections.js.map +1 -0
  202. package/lib/operations/list_databases.js +40 -0
  203. package/lib/operations/list_databases.js.map +1 -0
  204. package/lib/operations/operation.js +102 -0
  205. package/lib/operations/operation.js.map +1 -0
  206. package/lib/operations/profiling_level.js +43 -0
  207. package/lib/operations/profiling_level.js.map +1 -0
  208. package/lib/operations/remove_user.js +27 -0
  209. package/lib/operations/remove_user.js.map +1 -0
  210. package/lib/operations/rename.js +38 -0
  211. package/lib/operations/rename.js.map +1 -0
  212. package/lib/operations/run_command.js +47 -0
  213. package/lib/operations/run_command.js.map +1 -0
  214. package/lib/operations/search_indexes/create.js +33 -0
  215. package/lib/operations/search_indexes/create.js.map +1 -0
  216. package/lib/operations/search_indexes/drop.js +43 -0
  217. package/lib/operations/search_indexes/drop.js.map +1 -0
  218. package/lib/operations/search_indexes/update.js +35 -0
  219. package/lib/operations/search_indexes/update.js.map +1 -0
  220. package/lib/operations/set_profiling_level.js +53 -0
  221. package/lib/operations/set_profiling_level.js.map +1 -0
  222. package/lib/operations/stats.js +27 -0
  223. package/lib/operations/stats.js.map +1 -0
  224. package/lib/operations/update.js +188 -0
  225. package/lib/operations/update.js.map +1 -0
  226. package/lib/operations/validate_collection.js +37 -0
  227. package/lib/operations/validate_collection.js.map +1 -0
  228. package/lib/read_concern.js +73 -0
  229. package/lib/read_concern.js.map +1 -0
  230. package/lib/read_preference.js +191 -0
  231. package/lib/read_preference.js.map +1 -0
  232. package/lib/sdam/common.js +49 -0
  233. package/lib/sdam/common.js.map +1 -0
  234. package/lib/sdam/events.js +146 -0
  235. package/lib/sdam/events.js.map +1 -0
  236. package/lib/sdam/monitor.js +544 -0
  237. package/lib/sdam/monitor.js.map +1 -0
  238. package/lib/sdam/server.js +404 -0
  239. package/lib/sdam/server.js.map +1 -0
  240. package/lib/sdam/server_description.js +204 -0
  241. package/lib/sdam/server_description.js.map +1 -0
  242. package/lib/sdam/server_selection.js +294 -0
  243. package/lib/sdam/server_selection.js.map +1 -0
  244. package/lib/sdam/server_selection_events.js +85 -0
  245. package/lib/sdam/server_selection_events.js.map +1 -0
  246. package/lib/sdam/srv_polling.js +108 -0
  247. package/lib/sdam/srv_polling.js.map +1 -0
  248. package/lib/sdam/topology.js +652 -0
  249. package/lib/sdam/topology.js.map +1 -0
  250. package/lib/sdam/topology_description.js +383 -0
  251. package/lib/sdam/topology_description.js.map +1 -0
  252. package/lib/sessions.js +892 -0
  253. package/lib/sessions.js.map +1 -0
  254. package/lib/sort.js +103 -0
  255. package/lib/sort.js.map +1 -0
  256. package/lib/timeout.js +296 -0
  257. package/lib/timeout.js.map +1 -0
  258. package/lib/transactions.js +135 -0
  259. package/lib/transactions.js.map +1 -0
  260. package/lib/utils.js +1163 -0
  261. package/lib/utils.js.map +1 -0
  262. package/lib/write_concern.js +100 -0
  263. package/lib/write_concern.js.map +1 -0
  264. package/mongodb.d.ts +9018 -0
  265. package/package.json +197 -0
  266. package/src/admin.ts +173 -0
  267. package/src/bson.ts +149 -0
  268. package/src/bulk/common.ts +1251 -0
  269. package/src/bulk/ordered.ts +83 -0
  270. package/src/bulk/unordered.ts +115 -0
  271. package/src/change_stream.ts +1160 -0
  272. package/src/client-side-encryption/auto_encrypter.ts +469 -0
  273. package/src/client-side-encryption/client_encryption.ts +1150 -0
  274. package/src/client-side-encryption/errors.ts +144 -0
  275. package/src/client-side-encryption/mongocryptd_manager.ts +100 -0
  276. package/src/client-side-encryption/providers/aws.ts +33 -0
  277. package/src/client-side-encryption/providers/azure.ts +181 -0
  278. package/src/client-side-encryption/providers/gcp.ts +16 -0
  279. package/src/client-side-encryption/providers/index.ts +207 -0
  280. package/src/client-side-encryption/state_machine.ts +651 -0
  281. package/src/cmap/auth/auth_provider.ts +77 -0
  282. package/src/cmap/auth/aws4.ts +207 -0
  283. package/src/cmap/auth/aws_temporary_credentials.ts +129 -0
  284. package/src/cmap/auth/gssapi.ts +203 -0
  285. package/src/cmap/auth/mongo_credentials.ts +292 -0
  286. package/src/cmap/auth/mongodb_aws.ts +179 -0
  287. package/src/cmap/auth/mongodb_oidc/automated_callback_workflow.ts +88 -0
  288. package/src/cmap/auth/mongodb_oidc/azure_machine_workflow.ts +73 -0
  289. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +188 -0
  290. package/src/cmap/auth/mongodb_oidc/command_builders.ts +53 -0
  291. package/src/cmap/auth/mongodb_oidc/gcp_machine_workflow.ts +46 -0
  292. package/src/cmap/auth/mongodb_oidc/human_callback_workflow.ts +141 -0
  293. package/src/cmap/auth/mongodb_oidc/k8s_machine_workflow.ts +31 -0
  294. package/src/cmap/auth/mongodb_oidc/token_cache.ts +62 -0
  295. package/src/cmap/auth/mongodb_oidc/token_machine_workflow.ts +22 -0
  296. package/src/cmap/auth/mongodb_oidc.ts +185 -0
  297. package/src/cmap/auth/plain.ts +25 -0
  298. package/src/cmap/auth/providers.ts +22 -0
  299. package/src/cmap/auth/scram.ts +344 -0
  300. package/src/cmap/auth/x509.ts +43 -0
  301. package/src/cmap/command_monitoring_events.ts +316 -0
  302. package/src/cmap/commands.ts +788 -0
  303. package/src/cmap/connect.ts +518 -0
  304. package/src/cmap/connection.ts +931 -0
  305. package/src/cmap/connection_pool.ts +831 -0
  306. package/src/cmap/connection_pool_events.ts +300 -0
  307. package/src/cmap/errors.ts +119 -0
  308. package/src/cmap/handshake/client_metadata.ts +353 -0
  309. package/src/cmap/metrics.ts +58 -0
  310. package/src/cmap/stream_description.ts +96 -0
  311. package/src/cmap/wire_protocol/compression.ts +211 -0
  312. package/src/cmap/wire_protocol/constants.ts +17 -0
  313. package/src/cmap/wire_protocol/on_data.ts +139 -0
  314. package/src/cmap/wire_protocol/on_demand/document.ts +358 -0
  315. package/src/cmap/wire_protocol/responses.ts +393 -0
  316. package/src/cmap/wire_protocol/shared.ts +48 -0
  317. package/src/collection.ts +1314 -0
  318. package/src/connection_string.ts +1297 -0
  319. package/src/constants.ts +176 -0
  320. package/src/cursor/abstract_cursor.ts +1247 -0
  321. package/src/cursor/aggregation_cursor.ts +245 -0
  322. package/src/cursor/change_stream_cursor.ts +171 -0
  323. package/src/cursor/client_bulk_write_cursor.ts +83 -0
  324. package/src/cursor/explainable_cursor.ts +51 -0
  325. package/src/cursor/find_cursor.ts +497 -0
  326. package/src/cursor/list_collections_cursor.ts +50 -0
  327. package/src/cursor/list_indexes_cursor.ts +37 -0
  328. package/src/cursor/list_search_indexes_cursor.ts +20 -0
  329. package/src/cursor/run_command_cursor.ts +178 -0
  330. package/src/db.ts +621 -0
  331. package/src/deps.ts +227 -0
  332. package/src/encrypter.ts +127 -0
  333. package/src/error.ts +1567 -0
  334. package/src/explain.ts +124 -0
  335. package/src/gridfs/download.ts +483 -0
  336. package/src/gridfs/index.ts +264 -0
  337. package/src/gridfs/upload.ts +537 -0
  338. package/src/index.ts +633 -0
  339. package/src/mongo_client.ts +1155 -0
  340. package/src/mongo_client_auth_providers.ts +87 -0
  341. package/src/mongo_logger.ts +1081 -0
  342. package/src/mongo_types.ts +678 -0
  343. package/src/operations/aggregate.ts +153 -0
  344. package/src/operations/client_bulk_write/client_bulk_write.ts +72 -0
  345. package/src/operations/client_bulk_write/command_builder.ts +487 -0
  346. package/src/operations/client_bulk_write/common.ts +276 -0
  347. package/src/operations/client_bulk_write/executor.ts +149 -0
  348. package/src/operations/client_bulk_write/results_merger.ts +260 -0
  349. package/src/operations/command.ts +171 -0
  350. package/src/operations/count.ts +74 -0
  351. package/src/operations/create_collection.ts +218 -0
  352. package/src/operations/delete.ts +183 -0
  353. package/src/operations/distinct.ts +92 -0
  354. package/src/operations/drop.ts +130 -0
  355. package/src/operations/end_sessions.ts +44 -0
  356. package/src/operations/estimated_document_count.ts +61 -0
  357. package/src/operations/execute_operation.ts +319 -0
  358. package/src/operations/find.ts +254 -0
  359. package/src/operations/find_and_modify.ts +319 -0
  360. package/src/operations/get_more.ts +108 -0
  361. package/src/operations/indexes.ts +418 -0
  362. package/src/operations/insert.ts +108 -0
  363. package/src/operations/kill_cursors.ts +64 -0
  364. package/src/operations/list_collections.ts +108 -0
  365. package/src/operations/list_databases.ts +68 -0
  366. package/src/operations/operation.ts +181 -0
  367. package/src/operations/profiling_level.ts +46 -0
  368. package/src/operations/remove_user.ts +36 -0
  369. package/src/operations/rename.ts +60 -0
  370. package/src/operations/run_command.ts +79 -0
  371. package/src/operations/search_indexes/create.ts +56 -0
  372. package/src/operations/search_indexes/drop.ts +58 -0
  373. package/src/operations/search_indexes/update.ts +45 -0
  374. package/src/operations/set_profiling_level.ts +74 -0
  375. package/src/operations/stats.ts +37 -0
  376. package/src/operations/update.ts +318 -0
  377. package/src/operations/validate_collection.ts +50 -0
  378. package/src/read_concern.ts +88 -0
  379. package/src/read_preference.ts +256 -0
  380. package/src/sdam/common.ts +74 -0
  381. package/src/sdam/events.ts +219 -0
  382. package/src/sdam/monitor.ts +771 -0
  383. package/src/sdam/server.ts +595 -0
  384. package/src/sdam/server_description.ts +297 -0
  385. package/src/sdam/server_selection.ts +415 -0
  386. package/src/sdam/server_selection_events.ts +142 -0
  387. package/src/sdam/srv_polling.ts +146 -0
  388. package/src/sdam/topology.ts +1100 -0
  389. package/src/sdam/topology_description.ts +548 -0
  390. package/src/sessions.ts +1244 -0
  391. package/src/sort.ts +141 -0
  392. package/src/timeout.ts +405 -0
  393. package/src/transactions.ts +181 -0
  394. package/src/utils.ts +1434 -0
  395. package/src/write_concern.ts +183 -0
  396. package/tsconfig.json +46 -0
@@ -0,0 +1,831 @@
1
+ import { clearTimeout, setTimeout } from 'timers';
2
+
3
+ import type { ObjectId } from '../bson';
4
+ import {
5
+ APM_EVENTS,
6
+ CONNECTION_CHECK_OUT_FAILED,
7
+ CONNECTION_CHECK_OUT_STARTED,
8
+ CONNECTION_CHECKED_IN,
9
+ CONNECTION_CHECKED_OUT,
10
+ CONNECTION_CLOSED,
11
+ CONNECTION_CREATED,
12
+ CONNECTION_POOL_CLEARED,
13
+ CONNECTION_POOL_CLOSED,
14
+ CONNECTION_POOL_CREATED,
15
+ CONNECTION_POOL_READY,
16
+ CONNECTION_READY
17
+ } from '../constants';
18
+ import {
19
+ type AnyError,
20
+ MongoClientClosedError,
21
+ type MongoError,
22
+ MongoInvalidArgumentError,
23
+ MongoMissingCredentialsError,
24
+ MongoNetworkError,
25
+ MongoOperationTimeoutError,
26
+ MongoRuntimeError,
27
+ MongoServerError
28
+ } from '../error';
29
+ import { type Abortable, CancellationToken, TypedEventEmitter } from '../mongo_types';
30
+ import type { Server } from '../sdam/server';
31
+ import { type TimeoutContext, TimeoutError } from '../timeout';
32
+ import {
33
+ addAbortListener,
34
+ type Callback,
35
+ kDispose,
36
+ List,
37
+ makeCounter,
38
+ noop,
39
+ processTimeMS,
40
+ promiseWithResolvers
41
+ } from '../utils';
42
+ import { connect } from './connect';
43
+ import { Connection, type ConnectionEvents, type ConnectionOptions } from './connection';
44
+ import {
45
+ ConnectionCheckedInEvent,
46
+ ConnectionCheckedOutEvent,
47
+ ConnectionCheckOutFailedEvent,
48
+ ConnectionCheckOutStartedEvent,
49
+ ConnectionClosedEvent,
50
+ ConnectionCreatedEvent,
51
+ ConnectionPoolClearedEvent,
52
+ ConnectionPoolClosedEvent,
53
+ ConnectionPoolCreatedEvent,
54
+ ConnectionPoolReadyEvent,
55
+ ConnectionReadyEvent
56
+ } from './connection_pool_events';
57
+ import {
58
+ PoolClearedError,
59
+ PoolClearedOnNetworkError,
60
+ PoolClosedError,
61
+ WaitQueueTimeoutError
62
+ } from './errors';
63
+ import { ConnectionPoolMetrics } from './metrics';
64
+
65
+ /** @public */
66
+ export interface ConnectionPoolOptions extends Omit<ConnectionOptions, 'id' | 'generation'> {
67
+ /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */
68
+ maxPoolSize: number;
69
+ /** The minimum number of connections that MUST exist at any moment in a single connection pool. */
70
+ minPoolSize: number;
71
+ /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
72
+ maxConnecting: number;
73
+ /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */
74
+ maxIdleTimeMS: number;
75
+ /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */
76
+ waitQueueTimeoutMS: number;
77
+ /** If we are in load balancer mode. */
78
+ loadBalanced: boolean;
79
+ /** @internal */
80
+ minPoolSizeCheckFrequencyMS?: number;
81
+ }
82
+
83
+ /** @internal */
84
+ export interface WaitQueueMember {
85
+ resolve: (conn: Connection) => void;
86
+ reject: (err: AnyError) => void;
87
+ cancelled: boolean;
88
+ checkoutTime: number;
89
+ }
90
+
91
+ /** @internal */
92
+ export const PoolState = Object.freeze({
93
+ paused: 'paused',
94
+ ready: 'ready',
95
+ closed: 'closed'
96
+ } as const);
97
+
98
+ type PoolState = (typeof PoolState)[keyof typeof PoolState];
99
+
100
+ /** @public */
101
+ export type ConnectionPoolEvents = {
102
+ connectionPoolCreated(event: ConnectionPoolCreatedEvent): void;
103
+ connectionPoolReady(event: ConnectionPoolReadyEvent): void;
104
+ connectionPoolClosed(event: ConnectionPoolClosedEvent): void;
105
+ connectionPoolCleared(event: ConnectionPoolClearedEvent): void;
106
+ connectionCreated(event: ConnectionCreatedEvent): void;
107
+ connectionReady(event: ConnectionReadyEvent): void;
108
+ connectionClosed(event: ConnectionClosedEvent): void;
109
+ connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void;
110
+ connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void;
111
+ connectionCheckedOut(event: ConnectionCheckedOutEvent): void;
112
+ connectionCheckedIn(event: ConnectionCheckedInEvent): void;
113
+ } & Omit<ConnectionEvents, 'close' | 'message'>;
114
+
115
+ /**
116
+ * A pool of connections which dynamically resizes, and emit events related to pool activity
117
+ * @internal
118
+ */
119
+ export class ConnectionPool extends TypedEventEmitter<ConnectionPoolEvents> {
120
+ public options: Readonly<ConnectionPoolOptions>;
121
+ /** An integer representing the SDAM generation of the pool */
122
+ public generation: number;
123
+ /** A map of generations to service ids */
124
+ public serviceGenerations: Map<string, number>;
125
+
126
+ private poolState: PoolState;
127
+ private server: Server;
128
+ private connections: List<Connection>;
129
+ private pending: number;
130
+ private checkedOut: Set<Connection>;
131
+ private minPoolSizeTimer?: NodeJS.Timeout;
132
+ private connectionCounter: Generator<number>;
133
+ private cancellationToken: CancellationToken;
134
+ private waitQueue: List<WaitQueueMember>;
135
+ private metrics: ConnectionPoolMetrics;
136
+ private processingWaitQueue: boolean;
137
+
138
+ /**
139
+ * Emitted when the connection pool is created.
140
+ * @event
141
+ */
142
+ static readonly CONNECTION_POOL_CREATED = CONNECTION_POOL_CREATED;
143
+ /**
144
+ * Emitted once when the connection pool is closed
145
+ * @event
146
+ */
147
+ static readonly CONNECTION_POOL_CLOSED = CONNECTION_POOL_CLOSED;
148
+ /**
149
+ * Emitted each time the connection pool is cleared and it's generation incremented
150
+ * @event
151
+ */
152
+ static readonly CONNECTION_POOL_CLEARED = CONNECTION_POOL_CLEARED;
153
+ /**
154
+ * Emitted each time the connection pool is marked ready
155
+ * @event
156
+ */
157
+ static readonly CONNECTION_POOL_READY = CONNECTION_POOL_READY;
158
+ /**
159
+ * Emitted when a connection is created.
160
+ * @event
161
+ */
162
+ static readonly CONNECTION_CREATED = CONNECTION_CREATED;
163
+ /**
164
+ * Emitted when a connection becomes established, and is ready to use
165
+ * @event
166
+ */
167
+ static readonly CONNECTION_READY = CONNECTION_READY;
168
+ /**
169
+ * Emitted when a connection is closed
170
+ * @event
171
+ */
172
+ static readonly CONNECTION_CLOSED = CONNECTION_CLOSED;
173
+ /**
174
+ * Emitted when an attempt to check out a connection begins
175
+ * @event
176
+ */
177
+ static readonly CONNECTION_CHECK_OUT_STARTED = CONNECTION_CHECK_OUT_STARTED;
178
+ /**
179
+ * Emitted when an attempt to check out a connection fails
180
+ * @event
181
+ */
182
+ static readonly CONNECTION_CHECK_OUT_FAILED = CONNECTION_CHECK_OUT_FAILED;
183
+ /**
184
+ * Emitted each time a connection is successfully checked out of the connection pool
185
+ * @event
186
+ */
187
+ static readonly CONNECTION_CHECKED_OUT = CONNECTION_CHECKED_OUT;
188
+ /**
189
+ * Emitted each time a connection is successfully checked into the connection pool
190
+ * @event
191
+ */
192
+ static readonly CONNECTION_CHECKED_IN = CONNECTION_CHECKED_IN;
193
+
194
+ constructor(server: Server, options: ConnectionPoolOptions) {
195
+ super();
196
+ this.on('error', noop);
197
+
198
+ this.options = Object.freeze({
199
+ connectionType: Connection,
200
+ ...options,
201
+ maxPoolSize: options.maxPoolSize ?? 100,
202
+ minPoolSize: options.minPoolSize ?? 0,
203
+ maxConnecting: options.maxConnecting ?? 2,
204
+ maxIdleTimeMS: options.maxIdleTimeMS ?? 0,
205
+ waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0,
206
+ minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100,
207
+ autoEncrypter: options.autoEncrypter
208
+ });
209
+
210
+ if (this.options.minPoolSize > this.options.maxPoolSize) {
211
+ throw new MongoInvalidArgumentError(
212
+ 'Connection pool minimum size must not be greater than maximum pool size'
213
+ );
214
+ }
215
+
216
+ this.poolState = PoolState.paused;
217
+ this.server = server;
218
+ this.connections = new List();
219
+ this.pending = 0;
220
+ this.checkedOut = new Set();
221
+ this.minPoolSizeTimer = undefined;
222
+ this.generation = 0;
223
+ this.serviceGenerations = new Map();
224
+ this.connectionCounter = makeCounter(1);
225
+ this.cancellationToken = new CancellationToken();
226
+ this.cancellationToken.setMaxListeners(Infinity);
227
+ this.waitQueue = new List();
228
+ this.metrics = new ConnectionPoolMetrics();
229
+ this.processingWaitQueue = false;
230
+
231
+ this.mongoLogger = this.server.topology.client?.mongoLogger;
232
+ this.component = 'connection';
233
+
234
+ queueMicrotask(() => {
235
+ this.emitAndLog(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this));
236
+ });
237
+ }
238
+
239
+ /** The address of the endpoint the pool is connected to */
240
+ get address(): string {
241
+ return this.options.hostAddress.toString();
242
+ }
243
+
244
+ /**
245
+ * Check if the pool has been closed
246
+ *
247
+ * TODO(NODE-3263): We can remove this property once shell no longer needs it
248
+ */
249
+ get closed(): boolean {
250
+ return this.poolState === PoolState.closed;
251
+ }
252
+
253
+ /** An integer expressing how many total connections (available + pending + in use) the pool currently has */
254
+ get totalConnectionCount(): number {
255
+ return (
256
+ this.availableConnectionCount + this.pendingConnectionCount + this.currentCheckedOutCount
257
+ );
258
+ }
259
+
260
+ /** An integer expressing how many connections are currently available in the pool. */
261
+ get availableConnectionCount(): number {
262
+ return this.connections.length;
263
+ }
264
+
265
+ get pendingConnectionCount(): number {
266
+ return this.pending;
267
+ }
268
+
269
+ get currentCheckedOutCount(): number {
270
+ return this.checkedOut.size;
271
+ }
272
+
273
+ get waitQueueSize(): number {
274
+ return this.waitQueue.length;
275
+ }
276
+
277
+ get loadBalanced(): boolean {
278
+ return this.options.loadBalanced;
279
+ }
280
+
281
+ get serverError() {
282
+ return this.server.description.error;
283
+ }
284
+
285
+ /**
286
+ * This is exposed ONLY for use in mongosh, to enable
287
+ * killing all connections if a user quits the shell with
288
+ * operations in progress.
289
+ *
290
+ * This property may be removed as a part of NODE-3263.
291
+ */
292
+ get checkedOutConnections() {
293
+ return this.checkedOut;
294
+ }
295
+
296
+ /**
297
+ * Get the metrics information for the pool when a wait queue timeout occurs.
298
+ */
299
+ private waitQueueErrorMetrics(): string {
300
+ return this.metrics.info(this.options.maxPoolSize);
301
+ }
302
+
303
+ /**
304
+ * Set the pool state to "ready"
305
+ */
306
+ ready(): void {
307
+ if (this.poolState !== PoolState.paused) {
308
+ return;
309
+ }
310
+ this.poolState = PoolState.ready;
311
+ this.emitAndLog(ConnectionPool.CONNECTION_POOL_READY, new ConnectionPoolReadyEvent(this));
312
+ clearTimeout(this.minPoolSizeTimer);
313
+ this.ensureMinPoolSize();
314
+ }
315
+
316
+ /**
317
+ * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it
318
+ * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or
319
+ * explicitly destroyed by the new owner.
320
+ */
321
+ async checkOut(options: { timeoutContext: TimeoutContext } & Abortable): Promise<Connection> {
322
+ const checkoutTime = processTimeMS();
323
+ this.emitAndLog(
324
+ ConnectionPool.CONNECTION_CHECK_OUT_STARTED,
325
+ new ConnectionCheckOutStartedEvent(this)
326
+ );
327
+
328
+ const { promise, resolve, reject } = promiseWithResolvers<Connection>();
329
+
330
+ const timeout = options.timeoutContext.connectionCheckoutTimeout;
331
+
332
+ const waitQueueMember: WaitQueueMember = {
333
+ resolve,
334
+ reject,
335
+ cancelled: false,
336
+ checkoutTime
337
+ };
338
+
339
+ const abortListener = addAbortListener(options.signal, function () {
340
+ waitQueueMember.cancelled = true;
341
+ reject(this.reason);
342
+ });
343
+
344
+ this.waitQueue.push(waitQueueMember);
345
+ queueMicrotask(() => this.processWaitQueue());
346
+
347
+ try {
348
+ timeout?.throwIfExpired();
349
+ return await (timeout ? Promise.race([promise, timeout]) : promise);
350
+ } catch (error) {
351
+ if (TimeoutError.is(error)) {
352
+ timeout?.clear();
353
+ waitQueueMember.cancelled = true;
354
+
355
+ this.emitAndLog(
356
+ ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
357
+ new ConnectionCheckOutFailedEvent(this, 'timeout', waitQueueMember.checkoutTime)
358
+ );
359
+ const timeoutError = new WaitQueueTimeoutError(
360
+ this.loadBalanced
361
+ ? this.waitQueueErrorMetrics()
362
+ : 'Timed out while checking out a connection from connection pool',
363
+ this.address
364
+ );
365
+ if (options.timeoutContext.csotEnabled()) {
366
+ throw new MongoOperationTimeoutError('Timed out during connection checkout', {
367
+ cause: timeoutError
368
+ });
369
+ }
370
+ throw timeoutError;
371
+ }
372
+ throw error;
373
+ } finally {
374
+ abortListener?.[kDispose]();
375
+ timeout?.clear();
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Check a connection into the pool.
381
+ *
382
+ * @param connection - The connection to check in
383
+ */
384
+ checkIn(connection: Connection): void {
385
+ if (!this.checkedOut.has(connection)) {
386
+ return;
387
+ }
388
+ const poolClosed = this.closed;
389
+ const stale = this.connectionIsStale(connection);
390
+ const willDestroy = !!(poolClosed || stale || connection.closed);
391
+
392
+ if (!willDestroy) {
393
+ connection.markAvailable();
394
+ this.connections.unshift(connection);
395
+ }
396
+
397
+ this.checkedOut.delete(connection);
398
+ this.emitAndLog(
399
+ ConnectionPool.CONNECTION_CHECKED_IN,
400
+ new ConnectionCheckedInEvent(this, connection)
401
+ );
402
+
403
+ if (willDestroy) {
404
+ const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale';
405
+ this.destroyConnection(connection, reason);
406
+ }
407
+
408
+ queueMicrotask(() => this.processWaitQueue());
409
+ }
410
+
411
+ /**
412
+ * Clear the pool
413
+ *
414
+ * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a
415
+ * previous generation will eventually be pruned during subsequent checkouts.
416
+ */
417
+ clear(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void {
418
+ if (this.closed) {
419
+ return;
420
+ }
421
+
422
+ // handle load balanced case
423
+ if (this.loadBalanced) {
424
+ const { serviceId } = options;
425
+ if (!serviceId) {
426
+ throw new MongoRuntimeError(
427
+ 'ConnectionPool.clear() called in load balanced mode with no serviceId.'
428
+ );
429
+ }
430
+ const sid = serviceId.toHexString();
431
+ const generation = this.serviceGenerations.get(sid);
432
+ // Only need to worry if the generation exists, since it should
433
+ // always be there but typescript needs the check.
434
+ if (generation == null) {
435
+ throw new MongoRuntimeError('Service generations are required in load balancer mode.');
436
+ } else {
437
+ // Increment the generation for the service id.
438
+ this.serviceGenerations.set(sid, generation + 1);
439
+ }
440
+ this.emitAndLog(
441
+ ConnectionPool.CONNECTION_POOL_CLEARED,
442
+ new ConnectionPoolClearedEvent(this, { serviceId })
443
+ );
444
+ return;
445
+ }
446
+ // handle non load-balanced case
447
+ const interruptInUseConnections = options.interruptInUseConnections ?? false;
448
+ const oldGeneration = this.generation;
449
+ this.generation += 1;
450
+ const alreadyPaused = this.poolState === PoolState.paused;
451
+ this.poolState = PoolState.paused;
452
+
453
+ this.clearMinPoolSizeTimer();
454
+ if (!alreadyPaused) {
455
+ this.emitAndLog(
456
+ ConnectionPool.CONNECTION_POOL_CLEARED,
457
+ new ConnectionPoolClearedEvent(this, {
458
+ interruptInUseConnections
459
+ })
460
+ );
461
+ }
462
+
463
+ if (interruptInUseConnections) {
464
+ queueMicrotask(() => this.interruptInUseConnections(oldGeneration));
465
+ }
466
+
467
+ this.processWaitQueue();
468
+ }
469
+
470
+ /**
471
+ * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError.
472
+ *
473
+ * Only connections where `connection.generation <= minGeneration` are killed.
474
+ */
475
+ private interruptInUseConnections(minGeneration: number) {
476
+ for (const connection of this.checkedOut) {
477
+ if (connection.generation <= minGeneration) {
478
+ connection.onError(new PoolClearedOnNetworkError(this));
479
+ }
480
+ }
481
+ }
482
+
483
+ /** For MongoClient.close() procedures */
484
+ public closeCheckedOutConnections() {
485
+ for (const conn of this.checkedOut) {
486
+ conn.onError(new MongoClientClosedError());
487
+ }
488
+ }
489
+
490
+ /** Close the pool */
491
+ close(): void {
492
+ if (this.closed) {
493
+ return;
494
+ }
495
+
496
+ // immediately cancel any in-flight connections
497
+ this.cancellationToken.emit('cancel');
498
+
499
+ // end the connection counter
500
+ if (typeof this.connectionCounter.return === 'function') {
501
+ this.connectionCounter.return(undefined);
502
+ }
503
+
504
+ this.poolState = PoolState.closed;
505
+ this.clearMinPoolSizeTimer();
506
+ this.processWaitQueue();
507
+
508
+ for (const conn of this.connections) {
509
+ this.emitAndLog(
510
+ ConnectionPool.CONNECTION_CLOSED,
511
+ new ConnectionClosedEvent(this, conn, 'poolClosed')
512
+ );
513
+ conn.destroy();
514
+ }
515
+ this.connections.clear();
516
+ this.emitAndLog(ConnectionPool.CONNECTION_POOL_CLOSED, new ConnectionPoolClosedEvent(this));
517
+ }
518
+
519
+ /**
520
+ * @internal
521
+ * Reauthenticate a connection
522
+ */
523
+ async reauthenticate(connection: Connection): Promise<void> {
524
+ const authContext = connection.authContext;
525
+ if (!authContext) {
526
+ throw new MongoRuntimeError('No auth context found on connection.');
527
+ }
528
+ const credentials = authContext.credentials;
529
+ if (!credentials) {
530
+ throw new MongoMissingCredentialsError(
531
+ 'Connection is missing credentials when asked to reauthenticate'
532
+ );
533
+ }
534
+
535
+ const resolvedCredentials = credentials.resolveAuthMechanism(connection.hello);
536
+ const provider = this.server.topology.client.s.authProviders.getOrCreateProvider(
537
+ resolvedCredentials.mechanism,
538
+ resolvedCredentials.mechanismProperties
539
+ );
540
+
541
+ if (!provider) {
542
+ throw new MongoMissingCredentialsError(
543
+ `Reauthenticate failed due to no auth provider for ${credentials.mechanism}`
544
+ );
545
+ }
546
+
547
+ await provider.reauth(authContext);
548
+
549
+ return;
550
+ }
551
+
552
+ /** Clear the min pool size timer */
553
+ private clearMinPoolSizeTimer(): void {
554
+ const minPoolSizeTimer = this.minPoolSizeTimer;
555
+ if (minPoolSizeTimer) {
556
+ clearTimeout(minPoolSizeTimer);
557
+ }
558
+ }
559
+
560
+ private destroyConnection(
561
+ connection: Connection,
562
+ reason: 'error' | 'idle' | 'stale' | 'poolClosed'
563
+ ) {
564
+ this.emitAndLog(
565
+ ConnectionPool.CONNECTION_CLOSED,
566
+ new ConnectionClosedEvent(this, connection, reason)
567
+ );
568
+ // destroy the connection
569
+ connection.destroy();
570
+ }
571
+
572
+ private connectionIsStale(connection: Connection) {
573
+ const serviceId = connection.serviceId;
574
+ if (this.loadBalanced && serviceId) {
575
+ const sid = serviceId.toHexString();
576
+ const generation = this.serviceGenerations.get(sid);
577
+ return connection.generation !== generation;
578
+ }
579
+
580
+ return connection.generation !== this.generation;
581
+ }
582
+
583
+ private connectionIsIdle(connection: Connection) {
584
+ return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS);
585
+ }
586
+
587
+ /**
588
+ * Destroys a connection if the connection is perished.
589
+ *
590
+ * @returns `true` if the connection was destroyed, `false` otherwise.
591
+ */
592
+ private destroyConnectionIfPerished(connection: Connection): boolean {
593
+ const isStale = this.connectionIsStale(connection);
594
+ const isIdle = this.connectionIsIdle(connection);
595
+ if (!isStale && !isIdle && !connection.closed) {
596
+ return false;
597
+ }
598
+ const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle';
599
+ this.destroyConnection(connection, reason);
600
+ return true;
601
+ }
602
+
603
+ private createConnection(callback: Callback<Connection>) {
604
+ // Note that metadata may have changed on the client but have
605
+ // been frozen here, so we pull the metadata promise always from the client
606
+ // no matter what options were set at the construction of the pool.
607
+ const connectOptions: ConnectionOptions = {
608
+ ...this.options,
609
+ id: this.connectionCounter.next().value,
610
+ generation: this.generation,
611
+ cancellationToken: this.cancellationToken,
612
+ mongoLogger: this.mongoLogger,
613
+ authProviders: this.server.topology.client.s.authProviders,
614
+ metadata: this.server.topology.client.options.metadata
615
+ };
616
+
617
+ this.pending++;
618
+ // This is our version of a "virtual" no-I/O connection as the spec requires
619
+ const connectionCreatedTime = processTimeMS();
620
+ this.emitAndLog(
621
+ ConnectionPool.CONNECTION_CREATED,
622
+ new ConnectionCreatedEvent(this, { id: connectOptions.id })
623
+ );
624
+
625
+ connect(connectOptions).then(
626
+ connection => {
627
+ // The pool might have closed since we started trying to create a connection
628
+ if (this.poolState !== PoolState.ready) {
629
+ this.pending--;
630
+ connection.destroy();
631
+ callback(this.closed ? new PoolClosedError(this) : new PoolClearedError(this));
632
+ return;
633
+ }
634
+
635
+ // forward all events from the connection to the pool
636
+ for (const event of [...APM_EVENTS, Connection.CLUSTER_TIME_RECEIVED]) {
637
+ connection.on(event, (e: any) => this.emit(event, e));
638
+ }
639
+
640
+ if (this.loadBalanced) {
641
+ connection.on(Connection.PINNED, pinType => this.metrics.markPinned(pinType));
642
+ connection.on(Connection.UNPINNED, pinType => this.metrics.markUnpinned(pinType));
643
+
644
+ const serviceId = connection.serviceId;
645
+ if (serviceId) {
646
+ let generation;
647
+ const sid = serviceId.toHexString();
648
+ if ((generation = this.serviceGenerations.get(sid))) {
649
+ connection.generation = generation;
650
+ } else {
651
+ this.serviceGenerations.set(sid, 0);
652
+ connection.generation = 0;
653
+ }
654
+ }
655
+ }
656
+
657
+ connection.markAvailable();
658
+ this.emitAndLog(
659
+ ConnectionPool.CONNECTION_READY,
660
+ new ConnectionReadyEvent(this, connection, connectionCreatedTime)
661
+ );
662
+
663
+ this.pending--;
664
+ callback(undefined, connection);
665
+ },
666
+ error => {
667
+ this.pending--;
668
+ this.server.handleError(error);
669
+ this.emitAndLog(
670
+ ConnectionPool.CONNECTION_CLOSED,
671
+ new ConnectionClosedEvent(
672
+ this,
673
+ { id: connectOptions.id, serviceId: undefined },
674
+ 'error',
675
+ // TODO(NODE-5192): Remove this cast
676
+ error as MongoError
677
+ )
678
+ );
679
+ if (error instanceof MongoNetworkError || error instanceof MongoServerError) {
680
+ error.connectionGeneration = connectOptions.generation;
681
+ }
682
+ callback(error ?? new MongoRuntimeError('Connection creation failed without error'));
683
+ }
684
+ );
685
+ }
686
+
687
+ private ensureMinPoolSize() {
688
+ const minPoolSize = this.options.minPoolSize;
689
+ if (this.poolState !== PoolState.ready) {
690
+ return;
691
+ }
692
+
693
+ this.connections.prune(connection => this.destroyConnectionIfPerished(connection));
694
+
695
+ if (
696
+ this.totalConnectionCount < minPoolSize &&
697
+ this.pendingConnectionCount < this.options.maxConnecting
698
+ ) {
699
+ // NOTE: ensureMinPoolSize should not try to get all the pending
700
+ // connection permits because that potentially delays the availability of
701
+ // the connection to a checkout request
702
+ this.createConnection((err, connection) => {
703
+ if (!err && connection) {
704
+ this.connections.push(connection);
705
+ queueMicrotask(() => this.processWaitQueue());
706
+ }
707
+ if (this.poolState === PoolState.ready) {
708
+ clearTimeout(this.minPoolSizeTimer);
709
+ this.minPoolSizeTimer = setTimeout(
710
+ () => this.ensureMinPoolSize(),
711
+ this.options.minPoolSizeCheckFrequencyMS
712
+ );
713
+ }
714
+ });
715
+ } else {
716
+ clearTimeout(this.minPoolSizeTimer);
717
+ this.minPoolSizeTimer = setTimeout(
718
+ () => this.ensureMinPoolSize(),
719
+ this.options.minPoolSizeCheckFrequencyMS
720
+ );
721
+ }
722
+ }
723
+
724
+ private processWaitQueue() {
725
+ if (this.processingWaitQueue) {
726
+ return;
727
+ }
728
+ this.processingWaitQueue = true;
729
+
730
+ while (this.waitQueueSize) {
731
+ const waitQueueMember = this.waitQueue.first();
732
+ if (!waitQueueMember) {
733
+ this.waitQueue.shift();
734
+ continue;
735
+ }
736
+
737
+ if (waitQueueMember.cancelled) {
738
+ this.waitQueue.shift();
739
+ continue;
740
+ }
741
+
742
+ if (this.poolState !== PoolState.ready) {
743
+ const reason = this.closed ? 'poolClosed' : 'connectionError';
744
+ const error = this.closed ? new PoolClosedError(this) : new PoolClearedError(this);
745
+ this.emitAndLog(
746
+ ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
747
+ new ConnectionCheckOutFailedEvent(this, reason, waitQueueMember.checkoutTime, error)
748
+ );
749
+ this.waitQueue.shift();
750
+ waitQueueMember.reject(error);
751
+ continue;
752
+ }
753
+
754
+ if (!this.availableConnectionCount) {
755
+ break;
756
+ }
757
+
758
+ const connection = this.connections.shift();
759
+ if (!connection) {
760
+ break;
761
+ }
762
+
763
+ if (!this.destroyConnectionIfPerished(connection)) {
764
+ this.checkedOut.add(connection);
765
+ this.emitAndLog(
766
+ ConnectionPool.CONNECTION_CHECKED_OUT,
767
+ new ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)
768
+ );
769
+
770
+ this.waitQueue.shift();
771
+ waitQueueMember.resolve(connection);
772
+ }
773
+ }
774
+
775
+ const { maxPoolSize, maxConnecting } = this.options;
776
+ while (
777
+ this.waitQueueSize > 0 &&
778
+ this.pendingConnectionCount < maxConnecting &&
779
+ (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)
780
+ ) {
781
+ const waitQueueMember = this.waitQueue.shift();
782
+ if (!waitQueueMember || waitQueueMember.cancelled) {
783
+ continue;
784
+ }
785
+ this.createConnection((err, connection) => {
786
+ if (waitQueueMember.cancelled) {
787
+ if (!err && connection) {
788
+ this.connections.push(connection);
789
+ }
790
+ } else {
791
+ if (err) {
792
+ this.emitAndLog(
793
+ ConnectionPool.CONNECTION_CHECK_OUT_FAILED,
794
+ // TODO(NODE-5192): Remove this cast
795
+ new ConnectionCheckOutFailedEvent(
796
+ this,
797
+ 'connectionError',
798
+ waitQueueMember.checkoutTime,
799
+ err as MongoError
800
+ )
801
+ );
802
+ waitQueueMember.reject(err);
803
+ } else if (connection) {
804
+ this.checkedOut.add(connection);
805
+ this.emitAndLog(
806
+ ConnectionPool.CONNECTION_CHECKED_OUT,
807
+ new ConnectionCheckedOutEvent(this, connection, waitQueueMember.checkoutTime)
808
+ );
809
+ waitQueueMember.resolve(connection);
810
+ }
811
+ }
812
+ queueMicrotask(() => this.processWaitQueue());
813
+ });
814
+ }
815
+ this.processingWaitQueue = false;
816
+ }
817
+ }
818
+
819
+ /**
820
+ * A callback provided to `withConnection`
821
+ * @internal
822
+ *
823
+ * @param error - An error instance representing the error during the execution.
824
+ * @param connection - The managed connection which was checked out of the pool.
825
+ * @param callback - A function to call back after connection management is complete
826
+ */
827
+ export type WithConnectionCallback = (
828
+ error: MongoError | undefined,
829
+ connection: Connection | undefined,
830
+ callback: Callback<Connection>
831
+ ) => void;