@contember/database 2.1.0-beta.1 → 2.2.0-alpha.1

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 (316) hide show
  1. package/CLAUDE.md +3 -0
  2. package/dist/development/index.cjs +4 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +4 -0
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/builders/CaseStatement.cjs.map +1 -1
  7. package/dist/development/src/builders/CaseStatement.js.map +1 -1
  8. package/dist/development/src/builders/ColumnExpressionFactory.cjs.map +1 -1
  9. package/dist/development/src/builders/ColumnExpressionFactory.js.map +1 -1
  10. package/dist/development/src/builders/Compiler.cjs.map +1 -1
  11. package/dist/development/src/builders/Compiler.js.map +1 -1
  12. package/dist/development/src/builders/ConditionBuilder.cjs +6 -0
  13. package/dist/development/src/builders/ConditionBuilder.cjs.map +1 -1
  14. package/dist/development/src/builders/ConditionBuilder.js +6 -0
  15. package/dist/development/src/builders/ConditionBuilder.js.map +1 -1
  16. package/dist/development/src/builders/DeleteBuilder.cjs.map +1 -1
  17. package/dist/development/src/builders/DeleteBuilder.js.map +1 -1
  18. package/dist/development/src/builders/InsertBuilder.cjs.map +1 -1
  19. package/dist/development/src/builders/InsertBuilder.js.map +1 -1
  20. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  21. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
  22. package/dist/development/src/builders/SelectBuilder.cjs.map +1 -1
  23. package/dist/development/src/builders/SelectBuilder.js.map +1 -1
  24. package/dist/development/src/builders/UpdateBuilder.cjs.map +1 -1
  25. package/dist/development/src/builders/UpdateBuilder.js.map +1 -1
  26. package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
  27. package/dist/development/src/builders/WindowFunction.js.map +1 -1
  28. package/dist/development/src/builders/internal/Returning.cjs.map +1 -1
  29. package/dist/development/src/builders/internal/Returning.js.map +1 -1
  30. package/dist/development/src/builders/internal/Subqueries.cjs.map +1 -1
  31. package/dist/development/src/builders/internal/Subqueries.js.map +1 -1
  32. package/dist/development/src/builders/internal/Where.cjs.map +1 -1
  33. package/dist/development/src/builders/internal/Where.js.map +1 -1
  34. package/dist/development/src/builders/internal/With.cjs.map +1 -1
  35. package/dist/development/src/builders/internal/With.js.map +1 -1
  36. package/dist/development/src/builders/utils.cjs.map +1 -1
  37. package/dist/development/src/builders/utils.js.map +1 -1
  38. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  39. package/dist/development/src/client/AcquiredConnection.js.map +1 -1
  40. package/dist/development/src/client/Client.cjs.map +1 -1
  41. package/dist/development/src/client/Client.js.map +1 -1
  42. package/dist/development/src/client/Connection.cjs +11 -0
  43. package/dist/development/src/client/Connection.cjs.map +1 -1
  44. package/dist/development/src/client/Connection.js +11 -0
  45. package/dist/development/src/client/Connection.js.map +1 -1
  46. package/dist/development/src/client/EventManager.cjs.map +1 -1
  47. package/dist/development/src/client/EventManager.js.map +1 -1
  48. package/dist/development/src/client/Pool.cjs.map +1 -1
  49. package/dist/development/src/client/Pool.js.map +1 -1
  50. package/dist/development/src/client/ScopeLimitedConnection.cjs +37 -0
  51. package/dist/development/src/client/ScopeLimitedConnection.cjs.map +1 -0
  52. package/dist/development/src/client/ScopeLimitedConnection.js +37 -0
  53. package/dist/development/src/client/ScopeLimitedConnection.js.map +1 -0
  54. package/dist/development/src/client/Transaction.cjs.map +1 -1
  55. package/dist/development/src/client/Transaction.js.map +1 -1
  56. package/dist/development/src/metadata/DatabaseMetadata.cjs.map +1 -1
  57. package/dist/development/src/metadata/DatabaseMetadata.js.map +1 -1
  58. package/dist/development/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
  59. package/dist/development/src/metadata/DatabaseMetadataResolver.js.map +1 -1
  60. package/dist/development/src/metadata/IndexMetadata.cjs.map +1 -1
  61. package/dist/development/src/metadata/IndexMetadata.js.map +1 -1
  62. package/dist/development/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
  63. package/dist/development/src/metadata/UniqueConstraintMetadata.js.map +1 -1
  64. package/dist/development/src/queryable/DatabaseQuery.cjs.map +1 -1
  65. package/dist/development/src/queryable/DatabaseQuery.js.map +1 -1
  66. package/dist/development/src/queryable/DatabaseQueryable.cjs.map +1 -1
  67. package/dist/development/src/queryable/DatabaseQueryable.js.map +1 -1
  68. package/dist/development/src/utils/ConstraintHelper.cjs.map +1 -1
  69. package/dist/development/src/utils/ConstraintHelper.js.map +1 -1
  70. package/dist/development/src/utils/Semaphore.cjs +43 -0
  71. package/dist/development/src/utils/Semaphore.cjs.map +1 -0
  72. package/dist/development/src/utils/Semaphore.js +43 -0
  73. package/dist/development/src/utils/Semaphore.js.map +1 -0
  74. package/dist/development/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
  75. package/dist/development/src/utils/createDatabaseIfNotExists.js.map +1 -1
  76. package/dist/development/src/utils/listen.cjs.map +1 -1
  77. package/dist/development/src/utils/listen.js.map +1 -1
  78. package/dist/development/src/utils/pgClientFactory.cjs +5 -3
  79. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
  80. package/dist/development/src/utils/pgClientFactory.js +5 -3
  81. package/dist/development/src/utils/pgClientFactory.js.map +1 -1
  82. package/dist/development/src/utils/retryTransaction.cjs.map +1 -1
  83. package/dist/development/src/utils/retryTransaction.js.map +1 -1
  84. package/dist/development/src/utils/sql.cjs.map +1 -1
  85. package/dist/development/src/utils/sql.js.map +1 -1
  86. package/dist/development/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
  87. package/dist/development/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  88. package/dist/production/index.cjs +4 -0
  89. package/dist/production/index.cjs.map +1 -1
  90. package/dist/production/index.js +4 -0
  91. package/dist/production/index.js.map +1 -1
  92. package/dist/production/src/builders/CaseStatement.cjs.map +1 -1
  93. package/dist/production/src/builders/CaseStatement.js.map +1 -1
  94. package/dist/production/src/builders/ColumnExpressionFactory.cjs.map +1 -1
  95. package/dist/production/src/builders/ColumnExpressionFactory.js.map +1 -1
  96. package/dist/production/src/builders/Compiler.cjs.map +1 -1
  97. package/dist/production/src/builders/Compiler.js.map +1 -1
  98. package/dist/production/src/builders/ConditionBuilder.cjs +6 -0
  99. package/dist/production/src/builders/ConditionBuilder.cjs.map +1 -1
  100. package/dist/production/src/builders/ConditionBuilder.js +6 -0
  101. package/dist/production/src/builders/ConditionBuilder.js.map +1 -1
  102. package/dist/production/src/builders/DeleteBuilder.cjs.map +1 -1
  103. package/dist/production/src/builders/DeleteBuilder.js.map +1 -1
  104. package/dist/production/src/builders/InsertBuilder.cjs.map +1 -1
  105. package/dist/production/src/builders/InsertBuilder.js.map +1 -1
  106. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  107. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
  108. package/dist/production/src/builders/SelectBuilder.cjs.map +1 -1
  109. package/dist/production/src/builders/SelectBuilder.js.map +1 -1
  110. package/dist/production/src/builders/UpdateBuilder.cjs.map +1 -1
  111. package/dist/production/src/builders/UpdateBuilder.js.map +1 -1
  112. package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
  113. package/dist/production/src/builders/WindowFunction.js.map +1 -1
  114. package/dist/production/src/builders/internal/Returning.cjs.map +1 -1
  115. package/dist/production/src/builders/internal/Returning.js.map +1 -1
  116. package/dist/production/src/builders/internal/Subqueries.cjs.map +1 -1
  117. package/dist/production/src/builders/internal/Subqueries.js.map +1 -1
  118. package/dist/production/src/builders/internal/Where.cjs.map +1 -1
  119. package/dist/production/src/builders/internal/Where.js.map +1 -1
  120. package/dist/production/src/builders/internal/With.cjs.map +1 -1
  121. package/dist/production/src/builders/internal/With.js.map +1 -1
  122. package/dist/production/src/builders/utils.cjs.map +1 -1
  123. package/dist/production/src/builders/utils.js.map +1 -1
  124. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  125. package/dist/production/src/client/AcquiredConnection.js.map +1 -1
  126. package/dist/production/src/client/Client.cjs.map +1 -1
  127. package/dist/production/src/client/Client.js.map +1 -1
  128. package/dist/production/src/client/Connection.cjs +11 -0
  129. package/dist/production/src/client/Connection.cjs.map +1 -1
  130. package/dist/production/src/client/Connection.js +11 -0
  131. package/dist/production/src/client/Connection.js.map +1 -1
  132. package/dist/production/src/client/EventManager.cjs.map +1 -1
  133. package/dist/production/src/client/EventManager.js.map +1 -1
  134. package/dist/production/src/client/Pool.cjs.map +1 -1
  135. package/dist/production/src/client/Pool.js.map +1 -1
  136. package/dist/production/src/client/ScopeLimitedConnection.cjs +37 -0
  137. package/dist/production/src/client/ScopeLimitedConnection.cjs.map +1 -0
  138. package/dist/production/src/client/ScopeLimitedConnection.js +37 -0
  139. package/dist/production/src/client/ScopeLimitedConnection.js.map +1 -0
  140. package/dist/production/src/client/Transaction.cjs.map +1 -1
  141. package/dist/production/src/client/Transaction.js.map +1 -1
  142. package/dist/production/src/metadata/DatabaseMetadata.cjs.map +1 -1
  143. package/dist/production/src/metadata/DatabaseMetadata.js.map +1 -1
  144. package/dist/production/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
  145. package/dist/production/src/metadata/DatabaseMetadataResolver.js.map +1 -1
  146. package/dist/production/src/metadata/IndexMetadata.cjs.map +1 -1
  147. package/dist/production/src/metadata/IndexMetadata.js.map +1 -1
  148. package/dist/production/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
  149. package/dist/production/src/metadata/UniqueConstraintMetadata.js.map +1 -1
  150. package/dist/production/src/queryable/DatabaseQuery.cjs.map +1 -1
  151. package/dist/production/src/queryable/DatabaseQuery.js.map +1 -1
  152. package/dist/production/src/queryable/DatabaseQueryable.cjs.map +1 -1
  153. package/dist/production/src/queryable/DatabaseQueryable.js.map +1 -1
  154. package/dist/production/src/utils/ConstraintHelper.cjs.map +1 -1
  155. package/dist/production/src/utils/ConstraintHelper.js.map +1 -1
  156. package/dist/production/src/utils/Semaphore.cjs +43 -0
  157. package/dist/production/src/utils/Semaphore.cjs.map +1 -0
  158. package/dist/production/src/utils/Semaphore.js +43 -0
  159. package/dist/production/src/utils/Semaphore.js.map +1 -0
  160. package/dist/production/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
  161. package/dist/production/src/utils/createDatabaseIfNotExists.js.map +1 -1
  162. package/dist/production/src/utils/listen.cjs.map +1 -1
  163. package/dist/production/src/utils/listen.js.map +1 -1
  164. package/dist/production/src/utils/pgClientFactory.cjs +5 -3
  165. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
  166. package/dist/production/src/utils/pgClientFactory.js +5 -3
  167. package/dist/production/src/utils/pgClientFactory.js.map +1 -1
  168. package/dist/production/src/utils/retryTransaction.cjs.map +1 -1
  169. package/dist/production/src/utils/retryTransaction.js.map +1 -1
  170. package/dist/production/src/utils/sql.cjs.map +1 -1
  171. package/dist/production/src/utils/sql.js.map +1 -1
  172. package/dist/production/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
  173. package/dist/production/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  174. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +1 -1
  175. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
  176. package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts +2 -0
  177. package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts.map +1 -0
  178. package/dist/tests/cases/unit/semaphore.test.d.ts +2 -0
  179. package/dist/tests/cases/unit/semaphore.test.d.ts.map +1 -0
  180. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  181. package/dist/types/builders/CaseStatement.d.ts +2 -2
  182. package/dist/types/builders/CaseStatement.d.ts.map +1 -1
  183. package/dist/types/builders/ColumnExpressionFactory.d.ts +6 -6
  184. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
  185. package/dist/types/builders/Compiler.d.ts +5 -5
  186. package/dist/types/builders/Compiler.d.ts.map +1 -1
  187. package/dist/types/builders/ConditionBuilder.d.ts +8 -6
  188. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
  189. package/dist/types/builders/DeleteBuilder.d.ts +8 -8
  190. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
  191. package/dist/types/builders/InsertBuilder.d.ts +10 -10
  192. package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
  193. package/dist/types/builders/LimitByGroupWrapper.d.ts +3 -3
  194. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
  195. package/dist/types/builders/QueryBuilder.d.ts +5 -5
  196. package/dist/types/builders/QueryBuilder.d.ts.map +1 -1
  197. package/dist/types/builders/SelectBuilder.d.ts +9 -9
  198. package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
  199. package/dist/types/builders/UpdateBuilder.d.ts +9 -9
  200. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
  201. package/dist/types/builders/WindowFunction.d.ts +2 -2
  202. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  203. package/dist/types/builders/index.d.ts +12 -12
  204. package/dist/types/builders/index.d.ts.map +1 -1
  205. package/dist/types/builders/internal/Returning.d.ts +3 -3
  206. package/dist/types/builders/internal/Returning.d.ts.map +1 -1
  207. package/dist/types/builders/internal/Subqueries.d.ts +4 -4
  208. package/dist/types/builders/internal/Subqueries.d.ts.map +1 -1
  209. package/dist/types/builders/internal/Where.d.ts +3 -3
  210. package/dist/types/builders/internal/Where.d.ts.map +1 -1
  211. package/dist/types/builders/internal/With.d.ts +3 -3
  212. package/dist/types/builders/internal/With.d.ts.map +1 -1
  213. package/dist/types/builders/utils.d.ts +2 -2
  214. package/dist/types/builders/utils.d.ts.map +1 -1
  215. package/dist/types/client/AcquiredConnection.d.ts +3 -3
  216. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  217. package/dist/types/client/Client.d.ts +4 -4
  218. package/dist/types/client/Client.d.ts.map +1 -1
  219. package/dist/types/client/Connection.d.ts +12 -4
  220. package/dist/types/client/Connection.d.ts.map +1 -1
  221. package/dist/types/client/EventManager.d.ts +1 -1
  222. package/dist/types/client/EventManager.d.ts.map +1 -1
  223. package/dist/types/client/Pool.d.ts +3 -3
  224. package/dist/types/client/Pool.d.ts.map +1 -1
  225. package/dist/types/client/ScopeLimitedConnection.d.ts +34 -0
  226. package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -0
  227. package/dist/types/client/Transaction.d.ts +2 -2
  228. package/dist/types/client/Transaction.d.ts.map +1 -1
  229. package/dist/types/client/index.d.ts +8 -7
  230. package/dist/types/client/index.d.ts.map +1 -1
  231. package/dist/types/index.d.ts +10 -10
  232. package/dist/types/index.d.ts.map +1 -1
  233. package/dist/types/metadata/DatabaseMetadata.d.ts +3 -3
  234. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
  235. package/dist/types/metadata/DatabaseMetadataResolver.d.ts +2 -2
  236. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
  237. package/dist/types/metadata/index.d.ts +5 -5
  238. package/dist/types/metadata/index.d.ts.map +1 -1
  239. package/dist/types/queryable/DatabaseQuery.d.ts +1 -1
  240. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
  241. package/dist/types/queryable/DatabaseQueryable.d.ts +1 -1
  242. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
  243. package/dist/types/queryable/index.d.ts +2 -2
  244. package/dist/types/queryable/index.d.ts.map +1 -1
  245. package/dist/types/tsconfig.tsbuildinfo +1 -1
  246. package/dist/types/types.d.ts +1 -0
  247. package/dist/types/types.d.ts.map +1 -1
  248. package/dist/types/utils/ConstraintHelper.d.ts +2 -2
  249. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
  250. package/dist/types/utils/Semaphore.d.ts +17 -0
  251. package/dist/types/utils/Semaphore.d.ts.map +1 -0
  252. package/dist/types/utils/createDatabaseIfNotExists.d.ts +1 -1
  253. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  254. package/dist/types/utils/index.d.ts +11 -10
  255. package/dist/types/utils/index.d.ts.map +1 -1
  256. package/dist/types/utils/listen.d.ts +1 -1
  257. package/dist/types/utils/listen.d.ts.map +1 -1
  258. package/dist/types/utils/pgClientFactory.d.ts +3 -3
  259. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  260. package/dist/types/utils/sql.d.ts +1 -1
  261. package/dist/types/utils/sql.d.ts.map +1 -1
  262. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts +1 -1
  263. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  264. package/package.json +3 -3
  265. package/src/builders/CaseStatement.ts +3 -3
  266. package/src/builders/ColumnExpressionFactory.ts +7 -7
  267. package/src/builders/Compiler.ts +9 -9
  268. package/src/builders/ConditionBuilder.ts +13 -7
  269. package/src/builders/DeleteBuilder.ts +8 -8
  270. package/src/builders/InsertBuilder.ts +11 -11
  271. package/src/builders/LimitByGroupWrapper.ts +5 -5
  272. package/src/builders/QueryBuilder.ts +5 -5
  273. package/src/builders/SelectBuilder.ts +11 -11
  274. package/src/builders/UpdateBuilder.ts +10 -10
  275. package/src/builders/WindowFunction.ts +4 -4
  276. package/src/builders/index.ts +12 -12
  277. package/src/builders/internal/Returning.ts +4 -4
  278. package/src/builders/internal/Subqueries.ts +4 -4
  279. package/src/builders/internal/Where.ts +4 -4
  280. package/src/builders/internal/With.ts +4 -4
  281. package/src/builders/utils.ts +4 -4
  282. package/src/client/AcquiredConnection.ts +7 -7
  283. package/src/client/Client.ts +5 -5
  284. package/src/client/Connection.ts +18 -6
  285. package/src/client/EventManager.ts +1 -1
  286. package/src/client/Pool.ts +5 -5
  287. package/src/client/ScopeLimitedConnection.ts +65 -0
  288. package/src/client/Transaction.ts +4 -4
  289. package/src/client/index.ts +8 -7
  290. package/src/index.ts +11 -10
  291. package/src/metadata/DatabaseMetadata.ts +3 -3
  292. package/src/metadata/DatabaseMetadataResolver.ts +5 -5
  293. package/src/metadata/IndexMetadata.ts +1 -1
  294. package/src/metadata/UniqueConstraintMetadata.ts +1 -1
  295. package/src/metadata/index.ts +5 -5
  296. package/src/queryable/DatabaseQuery.ts +2 -2
  297. package/src/queryable/DatabaseQueryable.ts +1 -1
  298. package/src/queryable/index.ts +2 -2
  299. package/src/types.ts +1 -0
  300. package/src/utils/ConstraintHelper.ts +3 -3
  301. package/src/utils/Semaphore.ts +49 -0
  302. package/src/utils/createDatabaseIfNotExists.ts +3 -3
  303. package/src/utils/index.ts +11 -10
  304. package/src/utils/listen.ts +2 -2
  305. package/src/utils/pgClientFactory.ts +15 -10
  306. package/src/utils/retryTransaction.ts +1 -1
  307. package/src/utils/sql.ts +1 -1
  308. package/src/utils/withDatabaseAdvisoryLock.ts +1 -1
  309. package/tests/cases/unit/connection.test.ts +2 -2
  310. package/tests/cases/unit/createConnectionMockAlt.ts +2 -2
  311. package/tests/cases/unit/eventManager.test.ts +2 -2
  312. package/tests/cases/unit/pool.test.ts +1 -1
  313. package/tests/cases/unit/queryBuilder.test.ts +7 -3
  314. package/tests/cases/unit/scopeLimitedConnection.test.ts +204 -0
  315. package/tests/cases/unit/semaphore.test.ts +53 -0
  316. package/vitest.config.ts +0 -3
@@ -1 +1 @@
1
- {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection'\nimport { EventManager } from './EventManager'\nimport { Mutex } from '../utils'\nimport { executeTransaction, Transaction } from './Transaction'\nimport { ClientErrorCodes } from './errorCodes'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors'\nimport { PgClient } from './PgClient'\nimport { Notification } from 'pg'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\ttry {\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, { sql, parameters, meta })\n\n\t\t\t\tlet result: Connection.Result<Row>\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tresult = await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\t\t\t\tresult = {\n\t\t\t\t\t...result,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, { sql, parameters, meta }, result)\n\n\t\t\t\treturn result\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryError, { sql, parameters, meta }, error)\n\n\t\t\t\tswitch ((error as any).code) {\n\t\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAiBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACf;AAFgB,SAAA,WAAA;AACD,SAAA,eAAA;AAJjB,kBAAA,MAAQ,SAAQ,IAAI,MAAA,CAAM;AAAA,EAM1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,QAAQ,YAAY;AAC3C,aAAO,MAAM,SAAS,I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,YAAY,KAAK;AAAA,UAC1D,KAAK,iBAAiB;AACrB,kBAAM,IAAI,qBAAqB,KAAK,YAAY,KAAK;AAAA,UACtD,KAAK,iBAAiB;AACrB,kBAAM,IAAI,0BAA0B,KAAK,YAAY,KAAK;AAAA,UAC3D,KAAK,iBAAiB;AAAA,UACtB,KAAK,iBAAiB;AACrB,kBAAM,IAAI,iBAAiB,KAAK,YAAY,KAAK;AAAA,UAClD,KAAK,iBAAiB;AACrB,kBAAM,IAAI,wBAAwB,KAAK,YAAY,KAAK;AAAA,UACzD;AACC,kBAAM,IAAI,WAAW,KAAK,YAAY,KAAK;AAAA,QAAA;AAAA,MAE9C;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
1
+ {"version":3,"file":"AcquiredConnection.js","sources":["../../../../../packages/database/src/client/AcquiredConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Mutex } from '../utils/index.js'\nimport { executeTransaction, Transaction } from './Transaction.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport {\n\tForeignKeyViolationError,\n\tInvalidDataError,\n\tNotNullViolationError,\n\tQueryError,\n\tSerializationFailureError,\n\tTransactionAbortedError,\n\tUniqueViolationError,\n} from './errors.js'\nimport { PgClient } from './PgClient.js'\nimport { Notification } from 'pg'\n\nexport class AcquiredConnection implements Connection.AcquiredConnectionLike {\n\tprivate mutex = new Mutex()\n\n\tconstructor(\n\t\tprivate readonly pgClient: PgClient,\n\t\tpublic readonly eventManager: EventManager,\n\t) {\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\treturn await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager))\n\t\t})\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\tawait connection.query('BEGIN', [])\n\t\t\tconst transaction = new Transaction(connection)\n\t\t\treturn await executeTransaction(transaction, callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.mutex.execute(async () => {\n\t\t\ttry {\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryStart, { sql, parameters, meta })\n\n\t\t\t\tlet result: Connection.Result<Row>\n\t\t\t\tconst startHrTime = process.hrtime.bigint()\n\n\t\t\t\tresult = await this.pgClient.query(prepareSql(sql), parameters)\n\n\t\t\t\tconst endHrTime = process.hrtime.bigint()\n\t\t\t\tconst durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)\n\t\t\t\tresult = {\n\t\t\t\t\t...result,\n\t\t\t\t\ttiming: {\n\t\t\t\t\t\tselfDuration: durationUs,\n\t\t\t\t\t\ttotalDuration: durationUs,\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryEnd, { sql, parameters, meta }, result)\n\n\t\t\t\treturn result\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t\tthis.eventManager.fire(EventManager.Event.queryError, { sql, parameters, meta }, error)\n\n\t\t\t\tswitch ((error as any).code) {\n\t\t\t\t\tcase ClientErrorCodes.NOT_NULL_VIOLATION:\n\t\t\t\t\t\tthrow new NotNullViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.FOREIGN_KEY_VIOLATION:\n\t\t\t\t\t\tthrow new ForeignKeyViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.UNIQUE_VIOLATION:\n\t\t\t\t\t\tthrow new UniqueViolationError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.T_R_SERIALIZATION_FAILURE:\n\t\t\t\t\t\tthrow new SerializationFailureError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.INVALID_TEXT_REPRESENTATION:\n\t\t\t\t\tcase ClientErrorCodes.DATETIME_FIELD_OVERFLOW:\n\t\t\t\t\t\tthrow new InvalidDataError(sql, parameters, error)\n\t\t\t\t\tcase ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:\n\t\t\t\t\t\tthrow new TransactionAbortedError(sql, parameters, error)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new QueryError(sql, parameters, error)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\ton(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {\n\t\tthis.pgClient.on(event as any, cb)\n\t\treturn () => this.pgClient.off(event as any, cb)\n\t}\n}\n\nfunction prepareSql(sql: string) {\n\tlet parameterIndex = 0\n\treturn sql.replace(/(\\\\*)\\?/g, ({}, numOfEscapes) => (numOfEscapes.length % 2 ? '?' : `$${++parameterIndex}`))\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAiBO,MAAM,mBAAgE;AAAA,EAG5E,YACkB,UACD,cACf;AAFgB,SAAA,WAAA;AACD,SAAA,eAAA;AAJjB,kBAAA,MAAQ,SAAQ,IAAI,MAAA,CAAM;AAAA,EAM1B;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WA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K;AAAA,UACvD,KAAK,iBAAiB;AACrB,kBAAM,IAAI,yBAAyB,KAAK,YAAY,KAAK;AAAA,UAC1D,KAAK,iBAAiB;AACrB,kBAAM,IAAI,qBAAqB,KAAK,YAAY,KAAK;AAAA,UACtD,KAAK,iBAAiB;AACrB,kBAAM,IAAI,0BAA0B,KAAK,YAAY,KAAK;AAAA,UAC3D,KAAK,iBAAiB;AAAA,UACtB,KAAK,iBAAiB;AACrB,kBAAM,IAAI,iBAAiB,KAAK,YAAY,KAAK;AAAA,UAClD,KAAK,iBAAiB;AACrB,kBAAM,IAAI,wBAAwB,KAAK,YAAY,KAAK;AAAA,UACzD;AACC,kBAAM,IAAI,WAAW,KAAK,YAAY,KAAK;AAAA,QAAA;AAAA,MAE9C;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAEA,GAAG,OAAyC,IAAoF;AAC/H,SAAK,SAAS,GAAG,OAAc,EAAE;AACjC,WAAO,MAAM,KAAK,SAAS,IAAI,OAAc,EAAE;AAAA,EAChD;AACD;AAEA,SAAS,WAAW,KAAa;AAChC,MAAI,iBAAiB;AACrB,SAAO,IAAI,QAAQ,YAAY,CAAC,CAAA,GAAI,iBAAkB,aAAa,SAAS,IAAI,MAAM,IAAI,EAAE,cAAc,EAAG;AAC9G;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Client.cjs","sources":["../../../../../packages/database/src/client/Client.ts"],"sourcesContent":["import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders'\nimport { DatabaseQueryable } from '../queryable'\nimport { Connection } from './Connection'\nimport { EventManager } from './EventManager'\nimport { QueryHandler } from '@contember/queryable'\nimport { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils'\n\nclass Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {\n\tconstructor(\n\t\tpublic readonly connection: ConnectionType,\n\t\tpublic readonly schema: string,\n\t\tpublic readonly queryMeta: Record<string, any>,\n\t\tpublic readonly eventManager: EventManager = new EventManager(connection.eventManager),\n\t) {\n\t}\n\n\tpublic forSchema(schema: string): Client<ConnectionType> {\n\t\tconst eventManager = new EventManager(this.eventManager.parent)\n\t\treturn new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)\n\t}\n\n\tasync scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.scope(\n\t\t\tconnection =>\n\t\t\t\tcallback(\n\t\t\t\t\tnew Client(\n\t\t\t\t\t\tconnection as ConnectionType & Connection.AcquiredConnectionLike,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(connection.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync transaction<T>(transactionScope: (wrapper: Client<Connection.TransactionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.transaction(\n\t\t\ttransaction =>\n\t\t\t\ttransactionScope(\n\t\t\t\t\tnew Client<Connection.TransactionLike>(\n\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(transaction.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync locked<T>(lock: number, callback: (wrapper: Client<Connection.ConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.scope(client => withDatabaseAdvisoryLock(client.connection, lock, () => callback(client)))\n\t}\n\n\tselectBuilder<Result = SelectBuilder.Result>(): SelectBuilder<Result> {\n\t\treturn SelectBuilder.create<Result>()\n\t}\n\n\tinsertBuilder(): InsertBuilder<InsertBuilder.AffectedRows> {\n\t\treturn InsertBuilder.create()\n\t}\n\n\tupdateBuilder(): UpdateBuilder<UpdateBuilder.AffectedRows> {\n\t\treturn UpdateBuilder.create()\n\t}\n\n\tdeleteBuilder(): DeleteBuilder<DeleteBuilder.AffectedRows> {\n\t\treturn DeleteBuilder.create()\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: readonly any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn this.connection.scope(\n\t\t\tconnection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tcreateQueryHandler(): QueryHandler<DatabaseQueryable> {\n\t\tconst handler = new QueryHandler(\n\t\t\tnew DatabaseQueryable(this, {\n\t\t\t\tget(): QueryHandler<DatabaseQueryable> {\n\t\t\t\t\treturn handler\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\treturn handler\n\t}\n}\n\nexport { Client }\n"],"names":["EventManager","withDatabaseAdvisoryLock","SelectBuilder","InsertBuilder","UpdateBuilder","DeleteBuilder","QueryHandler","DatabaseQueryable"],"mappings":";;;;;;;;;;;;;;;;AAOA,MAAM,OAAqH;AAAA,EAC1H,YACiB,YACA,QACA,WACA,eAA6B,IAAIA,aAAAA,aAAa,WAAW,YAAY,GACpF;AAJe,SAAA,aAAA;AACA,SAAA,SAAA;AACA,SAAA,YAAA;AACA,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEO,UAAU,QAAwC;AACxD,UAAM,eAAe,IAAIA,aAAAA,aAAa,KAAK,aAAa,MAAM;AAC9D,WAAO,IAAI,OAAuB,KAAK,YAAY,QAAQ,KAAK,WAAW,YAAY;AAAA,EACxF;AAAA,EAEA,MAAM,MAAS,UAA+G;AAC7H,WAAO,MAAM,KAAK,WAAW;AAAA,MAC5B,CAAA,eACC;AAAA,QACC,IAAI;AAAA,UACH;AAAA,UACA,KAAK;AAAA,UACL,KAAK;AAAA,UACL,IAAIA,aAAAA,aAAa,WAAW,YAAY;AAAA,QAAA;AAAA,MACzC;AAAA,MAEF,EAAE,cAAc,KAAK,aAA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":["import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders/index.js'\nimport { DatabaseQueryable } from '../queryable/index.js'\nimport { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { QueryHandler } from '@contember/queryable'\nimport { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils/index.js'\n\nclass Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {\n\tconstructor(\n\t\tpublic readonly connection: ConnectionType,\n\t\tpublic readonly schema: string,\n\t\tpublic readonly queryMeta: Record<string, any>,\n\t\tpublic readonly eventManager: EventManager = new EventManager(connection.eventManager),\n\t) {\n\t}\n\n\tpublic forSchema(schema: string): Client<ConnectionType> {\n\t\tconst eventManager = new EventManager(this.eventManager.parent)\n\t\treturn new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)\n\t}\n\n\tasync scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.scope(\n\t\t\tconnection =>\n\t\t\t\tcallback(\n\t\t\t\t\tnew Client(\n\t\t\t\t\t\tconnection as ConnectionType & Connection.AcquiredConnectionLike,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(connection.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync transaction<T>(transactionScope: (wrapper: Client<Connection.TransactionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.transaction(\n\t\t\ttransaction =>\n\t\t\t\ttransactionScope(\n\t\t\t\t\tnew Client<Connection.TransactionLike>(\n\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(transaction.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync locked<T>(lock: number, callback: (wrapper: Client<Connection.ConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.scope(client => withDatabaseAdvisoryLock(client.connection, lock, () => callback(client)))\n\t}\n\n\tselectBuilder<Result = SelectBuilder.Result>(): SelectBuilder<Result> {\n\t\treturn SelectBuilder.create<Result>()\n\t}\n\n\tinsertBuilder(): InsertBuilder<InsertBuilder.AffectedRows> {\n\t\treturn InsertBuilder.create()\n\t}\n\n\tupdateBuilder(): UpdateBuilder<UpdateBuilder.AffectedRows> {\n\t\treturn UpdateBuilder.create()\n\t}\n\n\tdeleteBuilder(): DeleteBuilder<DeleteBuilder.AffectedRows> {\n\t\treturn DeleteBuilder.create()\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: readonly any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn this.connection.scope(\n\t\t\tconnection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tcreateQueryHandler(): QueryHandler<DatabaseQueryable> {\n\t\tconst handler = new QueryHandler(\n\t\t\tnew DatabaseQueryable(this, {\n\t\t\t\tget(): QueryHandler<DatabaseQueryable> {\n\t\t\t\t\treturn handler\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\treturn handler\n\t}\n}\n\nexport { Client }\n"],"names":["EventManager","withDatabaseAdvisoryLock","SelectBuilder","InsertBuilder","UpdateBuilder","DeleteBuilder","QueryHandler","DatabaseQueryable"],"mappings":";;;;;;;;;;;;;;;;AAOA,MAAM,OAAqH;AAAA,EAC1H,YACiB,YACA,QACA,WACA,eAA6B,IAAIA,aAAAA,aAAa,WAAW,YAAY,GACpF;AAJe,SAAA,aAAA;AACA,SAAA,SAAA;AACA,SAAA,YAAA;AACA,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEO,UAAU,QAAwC;AAC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M,KAAK,YAAY,EAAE,GAAG,KAAK,WAAW,GAAG,MAAM;AAAA,MAC9E,EAAE,cAAc,KAAK,aAAA;AAAA,IAAa;AAAA,EAEpC;AAAA,EAEA,qBAAsD;AACrD,UAAM,UAAU,IAAIC,UAAAA;AAAAA,MACnB,IAAIC,kBAAAA,kBAAkB,MAAM;AAAA,QAC3B,MAAuC;AACtC,iBAAO;AAAA,QACR;AAAA,MAAA,CACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACR;AACD;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Client.js","sources":["../../../../../packages/database/src/client/Client.ts"],"sourcesContent":["import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders'\nimport { DatabaseQueryable } from '../queryable'\nimport { Connection } from './Connection'\nimport { EventManager } from './EventManager'\nimport { QueryHandler } from '@contember/queryable'\nimport { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils'\n\nclass Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {\n\tconstructor(\n\t\tpublic readonly connection: ConnectionType,\n\t\tpublic readonly schema: string,\n\t\tpublic readonly queryMeta: Record<string, any>,\n\t\tpublic readonly eventManager: EventManager = new EventManager(connection.eventManager),\n\t) {\n\t}\n\n\tpublic forSchema(schema: string): Client<ConnectionType> {\n\t\tconst eventManager = new EventManager(this.eventManager.parent)\n\t\treturn new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)\n\t}\n\n\tasync scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.scope(\n\t\t\tconnection =>\n\t\t\t\tcallback(\n\t\t\t\t\tnew Client(\n\t\t\t\t\t\tconnection as ConnectionType & Connection.AcquiredConnectionLike,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(connection.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync transaction<T>(transactionScope: (wrapper: Client<Connection.TransactionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.transaction(\n\t\t\ttransaction =>\n\t\t\t\ttransactionScope(\n\t\t\t\t\tnew Client<Connection.TransactionLike>(\n\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(transaction.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync locked<T>(lock: number, callback: (wrapper: Client<Connection.ConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.scope(client => withDatabaseAdvisoryLock(client.connection, lock, () => callback(client)))\n\t}\n\n\tselectBuilder<Result = SelectBuilder.Result>(): SelectBuilder<Result> {\n\t\treturn SelectBuilder.create<Result>()\n\t}\n\n\tinsertBuilder(): InsertBuilder<InsertBuilder.AffectedRows> {\n\t\treturn InsertBuilder.create()\n\t}\n\n\tupdateBuilder(): UpdateBuilder<UpdateBuilder.AffectedRows> {\n\t\treturn UpdateBuilder.create()\n\t}\n\n\tdeleteBuilder(): DeleteBuilder<DeleteBuilder.AffectedRows> {\n\t\treturn DeleteBuilder.create()\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: readonly any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn this.connection.scope(\n\t\t\tconnection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tcreateQueryHandler(): QueryHandler<DatabaseQueryable> {\n\t\tconst handler = new QueryHandler(\n\t\t\tnew DatabaseQueryable(this, {\n\t\t\t\tget(): QueryHandler<DatabaseQueryable> {\n\t\t\t\t\treturn handler\n\t\t\t\t},\n\t\t\t}),\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cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,gBAA2D;AAC1D,WAAO,cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,MAAM,MACL,KACA,aAA6B,CAAA,GAC7B,OAA4B,CAAA,GACM;AAClC,WAAO,KAAK,WAAW;AAAA,MACtB,CAAA,eAAc,WAAW,MAAM,KAAK,YAAY,EAAE,GAAG,KAAK,WAAW,GAAG,MAAM;AAAA,MAC9E,EAAE,cAAc,KAAK,aAAA;AAAA,IAAa;AAAA,EAEpC;AAAA,EAEA,qBAAsD;AACrD,UAAM,UAAU,IAAI;AAAA,MACnB,IAAI,kBAAkB,MAAM;AAAA,QAC3B,MAAuC;AACtC,iBAAO;AAAA,QACR;AAAA,MAAA,CACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACR;AACD;"}
1
+ {"version":3,"file":"Client.js","sources":["../../../../../packages/database/src/client/Client.ts"],"sourcesContent":["import { DeleteBuilder, InsertBuilder, SelectBuilder, UpdateBuilder } from '../builders/index.js'\nimport { DatabaseQueryable } from '../queryable/index.js'\nimport { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { QueryHandler } from '@contember/queryable'\nimport { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils/index.js'\n\nclass Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {\n\tconstructor(\n\t\tpublic readonly connection: ConnectionType,\n\t\tpublic readonly schema: string,\n\t\tpublic readonly queryMeta: Record<string, any>,\n\t\tpublic readonly eventManager: EventManager = new EventManager(connection.eventManager),\n\t) {\n\t}\n\n\tpublic forSchema(schema: string): Client<ConnectionType> {\n\t\tconst eventManager = new EventManager(this.eventManager.parent)\n\t\treturn new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)\n\t}\n\n\tasync scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.scope(\n\t\t\tconnection =>\n\t\t\t\tcallback(\n\t\t\t\t\tnew Client(\n\t\t\t\t\t\tconnection as ConnectionType & Connection.AcquiredConnectionLike,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(connection.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync transaction<T>(transactionScope: (wrapper: Client<Connection.TransactionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.connection.transaction(\n\t\t\ttransaction =>\n\t\t\t\ttransactionScope(\n\t\t\t\t\tnew Client<Connection.TransactionLike>(\n\t\t\t\t\t\ttransaction,\n\t\t\t\t\t\tthis.schema,\n\t\t\t\t\t\tthis.queryMeta,\n\t\t\t\t\t\tnew EventManager(transaction.eventManager),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tasync locked<T>(lock: number, callback: (wrapper: Client<Connection.ConnectionLike>) => Promise<T> | T): Promise<T> {\n\t\treturn await this.scope(client => withDatabaseAdvisoryLock(client.connection, lock, () => callback(client)))\n\t}\n\n\tselectBuilder<Result = SelectBuilder.Result>(): SelectBuilder<Result> {\n\t\treturn SelectBuilder.create<Result>()\n\t}\n\n\tinsertBuilder(): InsertBuilder<InsertBuilder.AffectedRows> {\n\t\treturn InsertBuilder.create()\n\t}\n\n\tupdateBuilder(): UpdateBuilder<UpdateBuilder.AffectedRows> {\n\t\treturn UpdateBuilder.create()\n\t}\n\n\tdeleteBuilder(): DeleteBuilder<DeleteBuilder.AffectedRows> {\n\t\treturn DeleteBuilder.create()\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: readonly any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn this.connection.scope(\n\t\t\tconnection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),\n\t\t\t{ eventManager: this.eventManager },\n\t\t)\n\t}\n\n\tcreateQueryHandler(): QueryHandler<DatabaseQueryable> {\n\t\tconst handler = new QueryHandler(\n\t\t\tnew DatabaseQueryable(this, {\n\t\t\t\tget(): QueryHandler<DatabaseQueryable> {\n\t\t\t\t\treturn handler\n\t\t\t\t},\n\t\t\t}),\n\t\t)\n\t\treturn handler\n\t}\n}\n\nexport { Client }\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAOA,MAAM,OAAqH;AAAA,EAC1H,YACiB,YACA,QACA,WACA,eAA6B,IAAI,aAAa,WAAW,YAAY,GACpF;AAJe,SAAA,aAAA;AACA,SAAA,SAAA;AACA,SAAA,YAAA;AACA,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEO,UAAU,QAAwC;AACxD,UAAM,eAAe,IAAI,aAAa,KAAK,aAAa,MAAM;AAC9D,WAAO,IAAI,OAAuB,KAAK,YAAY,QAAQ,KAAK,WAAW,YAAY;AAAA,EACxF;AAAA,EAEA,MAAM,MAAS,UAA+G;AAC7H,WAAO,MAAM,KAAK,WAAW;AAAA,MAC5B,CAAA,eACC;AAAA,QACC,IAAI;AAAA,UACH;AAAA,UACA,KAAK;AAAA,UACL,KAAK;AAAA,UACL,IAAI,aAAa,WAAW,YAAY;AAAA,QAAA;AAAA,MACzC;AAAA,MAEF,EAAE,cAAc,KAAK,aAAA;AAAA,IAAa;AAAA,EAEpC;AAAA,EAEA,MAAM,YAAe,kBAA+F;AACnH,WAAO,MAAM,KAAK,WAAW;AAAA,MAC5B,CAAA,gBACC;AAAA,QACC,IAAI;AAAA,UACH;AAAA,UACA,KAAK;AAAA,UACL,KAAK;AAAA,UACL,IAAI,aAAa,YAAY,YAAY;AAAA,QAAA;AAAA,MAC1C;AAAA,MAEF,EAAE,cAAc,KAAK,aAAA;AAAA,IAAa;AAAA,EAEpC;AAAA,EAEA,MAAM,OAAU,MAAc,UAAsF;AACnH,WAAO,MAAM,KAAK,MAAM,CAAA,WAAU,yBAAyB,OAAO,YAAY,MAAM,MAAM,SAAS,MAAM,CAAC,CAAC;AAAA,EAC5G;AAAA,EAEA,gBAAsE;AACrE,WAAO,cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,gBAA2D;AAC1D,WAAO,cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,gBAA2D;AAC1D,WAAO,cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,gBAA2D;AAC1D,WAAO,cAAc,OAAA;AAAA,EACtB;AAAA,EAEA,MAAM,MACL,KACA,aAA6B,CAAA,GAC7B,OAA4B,CAAA,GACM;AAClC,WAAO,KAAK,WAAW;AAAA,MACtB,CAAA,eAAc,WAAW,MAAM,KAAK,YAAY,EAAE,GAAG,KAAK,WAAW,GAAG,MAAM;AAAA,MAC9E,EAAE,cAAc,KAAK,aAAA;AAAA,IAAa;AAAA,EAEpC;AAAA,EAEA,qBAAsD;AACrD,UAAM,UAAU,IAAI;AAAA,MACnB,IAAI,kBAAkB,MAAM;AAAA,QAC3B,MAAuC;AACtC,iBAAO;AAAA,QACR;AAAA,MAAA,CACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACR;AACD;"}
@@ -4,6 +4,7 @@ const EventManager = require("./EventManager.cjs");
4
4
  const Client = require("./Client.cjs");
5
5
  const Pool = require("./Pool.cjs");
6
6
  require("../Literal.cjs");
7
+ const ScopeLimitedConnection = require("./ScopeLimitedConnection.cjs");
7
8
  require("node:timers");
8
9
  require("../utils/Mutex.cjs");
9
10
  const pgClientFactory = require("../utils/pgClientFactory.cjs");
@@ -22,6 +23,16 @@ class Connection {
22
23
  createClient(schema, queryMeta) {
23
24
  return new Client.Client(this, schema, queryMeta, new EventManager.EventManager(this.eventManager));
24
25
  }
26
+ /**
27
+ * Returns a view of this connection that limits how many pool connections may be
28
+ * acquired concurrently through it. Intended to be created per HTTP request so that
29
+ * a single request cannot starve the shared pool. The returned view shares the same
30
+ * underlying pool; only top-level scopes are counted (nested scopes reuse the already
31
+ * acquired connection), so the limit must be at least 1.
32
+ */
33
+ withMaxConnections(maxConnections) {
34
+ return new ScopeLimitedConnection.ScopeLimitedConnection(this, maxConnections);
35
+ }
25
36
  async scope(callback, options = {}) {
26
37
  const acquired = await this.pool.acquire();
27
38
  const eventManager = new EventManager.EventManager(options.eventManager ?? this.eventManager);
@@ -1 +1 @@
1
- {"version":3,"file":"Connection.cjs","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager'\nimport { Client } from './Client'\nimport { Pool, PoolConfig, PoolStatus } from './Pool'\nimport { createPgClientFactory } from '../utils'\nimport { DatabaseConfig } from '../types'\nimport { AcquiredConnection } from './AcquiredConnection'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\tconst acquired = await this.pool.acquire()\n\t\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.transaction(callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["EventManager","Pool","createPgClientFactory","Client","AcquiredConnection","Connection"],"mappings":";;;;;;;;;;AAQA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAIA,aAAAA,aAAa,IAAI,GACjE;AAFgB,SAAA,OAAA;AACD,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,OAAA,GAChB,UACa;AACb,WAAO,IAAI,WAAW,IAAIC,KAAAA,KAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,SAAA,CAAU,CAAC;AAAA,EACrF;AAAA,EAEA,OAAc,aACb,QACA,UACa;AACb,WAAO,IAAI,WAAW,IAAID,UAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,SAAA,CAAU,CAAC;AAAA,EAC3G;AAAA,EAEO,aAAa,QAAgB,WAAwC;AAC3E,WAAO,IAAIC,OAAAA,OAAO,MAAM,QAAQ,WAAW,IAAIH,aAAAA,aAAa,KAAK,YAAY,CAAC;AAAA,EAC/E;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,UAAM,WAAW,MAAM,KAAK,KAAK,QAAA;AACjC,UAAM,eAAe,IAAIA,aAAAA,aAAa,QAAQ,gBAAgB,KAAK,YAAY;AAC/E,QAAI;AACH,YAAM,aAAa,IAAII,mBAAAA,mBAAmB,SAAS,QAAQ,YAAY;AACvE,YAAM,SAAS,MAAM,SAAS,UAAU;AACxC,WAAK,KAAK,QAAQ,QAAQ;AAE1B,aAAO;AAAA,IACR,SAAS,GAAG;AACX,WAAK,KAAK,QAAQ,QAAQ;AAC1B,YAAM;AAAA,IACP;AAAA,EACD;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUC,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;;"}
1
+ {"version":3,"file":"Connection.cjs","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\tconst acquired = await this.pool.acquire()\n\t\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.transaction(callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["EventManager","Pool","createPgClientFactory","Client","ScopeLimitedConnection","AcquiredConnection","Connection"],"mappings":";;;;;;;;;;;AASA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAIA,aAAAA,aAAa,IAAI,GACjE;AAFgB,SAAA,OAAA;AACD,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,OAAA,GAChB,UACa;AACb,WAAO,IAAI,WAAW,IAAIC,KAAAA,KAAKC,gBAAAA,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,SAAA,CAAU,CAAC;AAAA,EACrF;AAAA,EAEA,OAAc,aACb,QACA,UACa;AACb,WAAO,IAAI,WAAW,IAAID,UAAKC,gBAAAA,sBAAsB,MAAM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AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUC,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;;"}
@@ -2,6 +2,7 @@ import { EventManager } from "./EventManager.js";
2
2
  import { Client } from "./Client.js";
3
3
  import { Pool } from "./Pool.js";
4
4
  import "../Literal.js";
5
+ import { ScopeLimitedConnection } from "./ScopeLimitedConnection.js";
5
6
  import "node:timers";
6
7
  import "../utils/Mutex.js";
7
8
  import { createPgClientFactory } from "../utils/pgClientFactory.js";
@@ -20,6 +21,16 @@ class Connection {
20
21
  createClient(schema, queryMeta) {
21
22
  return new Client(this, schema, queryMeta, new EventManager(this.eventManager));
22
23
  }
24
+ /**
25
+ * Returns a view of this connection that limits how many pool connections may be
26
+ * acquired concurrently through it. Intended to be created per HTTP request so that
27
+ * a single request cannot starve the shared pool. The returned view shares the same
28
+ * underlying pool; only top-level scopes are counted (nested scopes reuse the already
29
+ * acquired connection), so the limit must be at least 1.
30
+ */
31
+ withMaxConnections(maxConnections) {
32
+ return new ScopeLimitedConnection(this, maxConnections);
33
+ }
23
34
  async scope(callback, options = {}) {
24
35
  const acquired = await this.pool.acquire();
25
36
  const eventManager = new EventManager(options.eventManager ?? this.eventManager);
@@ -1 +1 @@
1
- {"version":3,"file":"Connection.js","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager'\nimport { Client } from './Client'\nimport { Pool, PoolConfig, PoolStatus } from './Pool'\nimport { createPgClientFactory } from '../utils'\nimport { DatabaseConfig } from '../types'\nimport { AcquiredConnection } from './AcquiredConnection'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\tconst acquired = await this.pool.acquire()\n\t\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.transaction(callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\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ACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUA,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;"}
1
+ {"version":3,"file":"Connection.js","sources":["../../../../../packages/database/src/client/Connection.ts"],"sourcesContent":["import { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { Pool, PoolConfig, PoolStatus } from './Pool.js'\nimport { createPgClientFactory } from '../utils/index.js'\nimport { DatabaseConfig } from '../types.js'\nimport { AcquiredConnection } from './AcquiredConnection.js'\nimport { ScopeLimitedConnection } from './ScopeLimitedConnection.js'\nimport { Notification } from 'pg'\n\nclass Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {\n\tconstructor(\n\t\tprivate readonly pool: Pool,\n\t\tpublic readonly eventManager: EventManager = new EventManager(null),\n\t) {\n\t}\n\n\tpublic static create(\n\t\t{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))\n\t}\n\n\tpublic static createSingle(\n\t\tconfig: DatabaseConfig,\n\t\tlogError: (error: Error) => void,\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }))\n\t}\n\n\tpublic createClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\t/**\n\t * Returns a view of this connection that limits how many pool connections may be\n\t * acquired concurrently through it. Intended to be created per HTTP request so that\n\t * a single request cannot starve the shared pool. The returned view shares the same\n\t * underlying pool; only top-level scopes are counted (nested scopes reuse the already\n\t * acquired connection), so the limit must be at least 1.\n\t */\n\tpublic withMaxConnections(maxConnections: number): Connection.ConnectionType {\n\t\treturn new ScopeLimitedConnection(this, maxConnections)\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\tconst acquired = await this.pool.acquire()\n\t\tconst eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\ttry {\n\t\t\tconst connection = new AcquiredConnection(acquired.client, eventManager)\n\t\t\tconst result = await callback(connection)\n\t\t\tthis.pool.release(acquired)\n\n\t\t\treturn result\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\tthrow e\n\t\t}\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.transaction(callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tasync end(): Promise<void> {\n\t\tawait this.pool.end()\n\t}\n\n\tpublic async clearPool(): Promise<void> {\n\t\tawait this.pool.closeIdle()\n\t}\n\n\tgetPoolStatus(): PoolStatus {\n\t\treturn this.pool.getPoolStatus()\n\t}\n}\n\nnamespace Connection {\n\texport interface Queryable {\n\t\treadonly eventManager: EventManager\n\n\t\tquery<Row extends Record<string, any>>(\n\t\t\tsql: string,\n\t\t\tparameters?: readonly any[],\n\t\t\tmeta?: Record<string, any>,\n\t\t): Promise<Connection.Result<Row>>\n\t}\n\n\texport interface Transactional {\n\t\ttransaction<Result>(\n\t\t\ttrx: (connection: TransactionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport type ConnectionType =\n\t\t& Connection.ConnectionLike\n\t\t& Connection.ClientFactory\n\t\t& Connection.PoolStatusProvider\n\n\texport interface ConnectionLike<T = {}> extends Transactional, Queryable {\n\t\tscope<Result>(\n\t\t\tcallback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,\n\t\t\toptions?: { eventManager?: EventManager },\n\t\t): Promise<Result>\n\t}\n\n\texport interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {\n\t\ton(event: 'notification', listener: (message: Notification) => void): () => void\n\t\ton(event: 'end', listener: () => void): () => void\n\t\ton(event: 'error', listener: (error: any) => void): () => void\n\t}\n\n\texport interface ClientFactory {\n\t\tcreateClient(schema: string, queryMeta: Record<string, any>): Client\n\t}\n\n\texport interface PoolStatusProvider {\n\t\tgetPoolStatus(): PoolStatus | undefined\n\t}\n\n\texport interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {\n\t\treadonly isClosed: boolean\n\n\t\trollback(): Promise<void>\n\n\t\tcommit(): Promise<void>\n\t}\n\n\texport interface Query {\n\t\treadonly sql: string\n\t\treadonly parameters: any[]\n\t\treadonly meta: Record<string, any>\n\t}\n\n\texport interface Result<Row extends Record<string, any> = Record<string, any>> {\n\t\treadonly command?: string\n\t\treadonly rowCount: number | null\n\t\treadonly rows: Row[]\n\t\treadonly timing?: {\n\t\t\tselfDuration: number\n\t\t\t/** @deprecated both selfDuration and totalDuration now contains same number */\n\t\t\ttotalDuration: number\n\t\t}\n\t}\n\n\texport const REPEATABLE_READ = 'SET TRANSACTION ISOLATION LEVEL RE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,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,MAAM,MAAqB;AAC1B,UAAM,KAAK,KAAK,IAAA;AAAA,EACjB;AAAA,EAEA,MAAa,YAA2B;AACvC,UAAM,KAAK,KAAK,UAAA;AAAA,EACjB;AAAA,EAEA,gBAA4B;AAC3B,WAAO,KAAK,KAAK,cAAA;AAAA,EAClB;AACD;AAAA,CAEA,CAAUA,gBAAV;AAqEcA,cAAA,kBAAkB;AAAA,GArEtB,eAAA,aAAA,CAAA,EAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"EventManager.cjs","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection'\n\nclass EventManager {\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t) {}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;;;AAEA,MAAM,aAAa;AAAA,EAOlB,YACiB,SAA8B,MAC7C;AADe,SAAA,SAAA;AAPjB,kBAAA,MAAiB,aAAY;AAAA,MAC5B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,MACjC,CAAC,aAAa,MAAM,QAAQ,GAAG,CAAA;AAAA,MAC/B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,IAAC,CACnC;AAAA,EAIG;AAAA,EAEH,GAAmD,OAAc,IAA6C;AAC3G,SAAK,UAAU,KAAK,EAA0C,KAAK,EAAE;AAAA,EACxE;AAAA,EAEA,KAAuC,UAAiB,QAA6D;AAClH,SAAK,UAAU,KAAK,EAA0C,QAAQ,CAAC,OAA0C,GAAG,GAAI,MAAqB,CAAC;AAChJ,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,KAAK,OAAO,GAAG,MAAM;AAAA,IAClC;AAAA,EACD;AAAA,EAEA,eACC,OACA,IACO;AACP,SAAK,UAAU,KAAK,IAAK,KAAK,UAAU,KAAK,EAA0C,OAAO,CAAA,OAAM,OAAO,EAAE;AAAA,EAC9G;AACD;AAAA,CAEA,CAAUA,kBAAV;AACQ,GAAA,CAAKC,WAAL;AACNA,WAAA,YAAA,IAAa;AACbA,WAAA,UAAA,IAAW;AACXA,WAAA,YAAA,IAAa;AAAA,EAAA,GAHFD,cAAA,UAAAA,cAAA,QAAA,CAAA,EAAA;AAAA,GADH,iBAAA,eAAA,CAAA,EAAA;;"}
1
+ {"version":3,"file":"EventManager.cjs","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection.js'\n\nclass EventManager {\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t) {}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;;;AAEA,MAAM,aAAa;AAAA,EAOlB,YACiB,SAA8B,MAC7C;AADe,SAAA,SAAA;AAPjB,kBAAA,MAAiB,aAAY;AAAA,MAC5B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,MACjC,CAAC,aAAa,MAAM,QAAQ,GAAG,CAAA;AAAA,MAC/B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,IAAC,CACnC;AAAA,EAIG;AAAA,EAEH,GAAmD,OAAc,IAA6C;AAC3G,SAAK,UAAU,KAAK,EAA0C,KAAK,EAAE;AAAA,EACxE;AAAA,EAEA,KAAuC,UAAiB,QAA6D;AAClH,SAAK,UAAU,KAAK,EAA0C,QAAQ,CAAC,OAA0C,GAAG,GAAI,MAAqB,CAAC;AAChJ,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,KAAK,OAAO,GAAG,MAAM;AAAA,IAClC;AAAA,EACD;AAAA,EAEA,eACC,OACA,IACO;AACP,SAAK,UAAU,KAAK,IAAK,KAAK,UAAU,KAAK,EAA0C,OAAO,CAAA,OAAM,OAAO,EAAE;AAAA,EAC9G;AACD;AAAA,CAEA,CAAUA,kBAAV;AACQ,GAAA,CAAKC,WAAL;AACNA,WAAA,YAAA,IAAa;AACbA,WAAA,UAAA,IAAW;AACXA,WAAA,YAAA,IAAa;AAAA,EAAA,GAHFD,cAAA,UAAAA,cAAA,QAAA,CAAA,EAAA;AAAA,GADH,iBAAA,eAAA,CAAA,EAAA;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"EventManager.js","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection'\n\nclass EventManager {\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t) {}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;AAEA,MAAM,aAAa;AAAA,EAOlB,YACiB,SAA8B,MAC7C;AADe,SAAA,SAAA;AAPjB,kBAAA,MAAiB,aAAY;AAAA,MAC5B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,MACjC,CAAC,aAAa,MAAM,QAAQ,GAAG,CAAA;AAAA,MAC/B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,IAAC,CACnC;AAAA,EAIG;AAAA,EAEH,GAAmD,OAAc,IAA6C;AAC3G,SAAK,UAAU,KAAK,EAA0C,KAAK,EAAE;AAAA,EACxE;AAAA,EAEA,KAAuC,UAAiB,QAA6D;AAClH,SAAK,UAAU,KAAK,EAA0C,QAAQ,CAAC,OAA0C,GAAG,GAAI,MAAqB,CAAC;AAChJ,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,KAAK,OAAO,GAAG,MAAM;AAAA,IAClC;AAAA,EACD;AAAA,EAEA,eACC,OACA,IACO;AACP,SAAK,UAAU,KAAK,IAAK,KAAK,UAAU,KAAK,EAA0C,OAAO,CAAA,OAAM,OAAO,EAAE;AAAA,EAC9G;AACD;AAAA,CAEA,CAAUA,kBAAV;AACQ,GAAA,CAAKC,WAAL;AACNA,WAAA,YAAA,IAAa;AACbA,WAAA,UAAA,IAAW;AACXA,WAAA,YAAA,IAAa;AAAA,EAAA,GAHFD,cAAA,UAAAA,cAAA,QAAA,CAAA,EAAA;AAAA,GADH,iBAAA,eAAA,CAAA,EAAA;"}
1
+ {"version":3,"file":"EventManager.js","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection.js'\n\nclass EventManager {\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t) {}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;AAEA,MAAM,aAAa;AAAA,EAOlB,YACiB,SAA8B,MAC7C;AADe,SAAA,SAAA;AAPjB,kBAAA,MAAiB,aAAY;AAAA,MAC5B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,MACjC,CAAC,aAAa,MAAM,QAAQ,GAAG,CAAA;AAAA,MAC/B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,IAAC,CACnC;AAAA,EAIG;AAAA,EAEH,GAAmD,OAAc,IAA6C;AAC3G,SAAK,UAAU,KAAK,EAA0C,KAAK,EAAE;AAAA,EACxE;AAAA,EAEA,KAAuC,UAAiB,QAA6D;AAClH,SAAK,UAAU,KAAK,EAA0C,QAAQ,CAAC,OAA0C,GAAG,GAAI,MAAqB,CAAC;AAChJ,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,KAAK,OAAO,GAAG,MAAM;AAAA,IAClC;AAAA,EACD;AAAA,EAEA,eACC,OACA,IACO;AACP,SAAK,UAAU,KAAK,IAAK,KAAK,UAAU,KAAK,EAA0C,OAAO,CAAA,OAAM,OAAO,EAAE;AAAA,EAC9G;AACD;AAAA,CAEA,CAAUA,kBAAV;AACQ,GAAA,CAAKC,WAAL;AACNA,WAAA,YAAA,IAAa;AACbA,WAAA,UAAA,IAAW;AACXA,WAAA,YAAA,IAAa;AAAA,EAAA,GAHFD,cAAA,UAAAA,cAAA,QAAA,CAAA,EAAA;AAAA,GADH,iBAAA,eAAA,CAAA,EAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Pool.cjs","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions'\nimport { ClientErrorCodes } from './errorCodes'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors'\nimport { PgClientFactory } from '../utils'\nimport { PgClient } from './PgClient'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":["ImplementationException","ClientError","ClientErrorCodes","DatabaseError"],"mappings":";;;;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAA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Q,YAAY;AACzB,UAAI;AACH,cAAM,WAAW,OAAO,IAAA;AAAA,MACzB,SAAS,GAAQ;AAChB,aAAK,WAAW,SAAS,IAAIA,OAAAA,YAAY,GAAG,gBAAgB,CAAC;AAAA,MAC9D;AAAA,IACD;AACA,UAAM,QAAQ,KAAK;AAAA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkBE,OAAAA,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;;;;;;"}
1
+ {"version":3,"file":"Pool.cjs","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors.js'\nimport { PgClientFactory } from '../utils/index.js'\nimport { PgClient } from './PgClient.js'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":["ImplementationException","ClientError","ClientErrorCodes","DatabaseError"],"mappings":";;;;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV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C;AAAA,IACrD;AACA,eAAW,WAAW;AACtB,UAAM,QAAQ,YAAY;AACzB,UAAI;AACH,cAAM,WAAW,OAAO,IAAA;AAAA,MACzB,SAAS,GAAQ;AAChB,aAAK,WAAW,SAAS,IAAIA,OAAAA,YAAY,GAAG,gBAAgB,CAAC;AAAA,MAC9D;AAAA,IACD;AACA,UAAM,QAAQ,KAAK;AAAA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkBE,OAAAA,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Pool.js","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions'\nimport { ClientErrorCodes } from './errorCodes'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors'\nimport { PgClientFactory } from '../utils'\nimport { PgClient } from './PgClient'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":[],"mappings":";;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,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QAAQ,YAAY;AACzB,UAAI;AACH,cAAM,WAAW,OAAO,IAAA;AAAA,MACzB,SAAS,GAAQ;AAChB,aAAK,WAAW,SAAS,IAAI,YAAY,GAAG,gBAAgB,CAAC;AAAA,MAC9D;AAAA,IACD;AACA,UAAM,QAAQ,KAAK;AAAA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkB,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;"}
1
+ {"version":3,"file":"Pool.js","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors.js'\nimport { PgClientFactory } from '../utils/index.js'\nimport { PgClient } from './PgClient.js'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":[],"mappings":";;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAAA,MAAQ,SA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,SAAS,GAAQ;AAChB,aAAK,WAAW,SAAS,IAAI,YAAY,GAAG,gBAAgB,CAAC;AAAA,MAC9D;AAAA,IACD;AACA,UAAM,QAAQ,KAAK;AAAA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkB,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;"}
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const EventManager = require("./EventManager.cjs");
4
+ const Client = require("./Client.cjs");
5
+ const Semaphore = require("../utils/Semaphore.cjs");
6
+ var __defProp = Object.defineProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
9
+ class ScopeLimitedConnection {
10
+ constructor(inner, maxConnections, eventManager = inner.eventManager) {
11
+ this.inner = inner;
12
+ this.eventManager = eventManager;
13
+ __publicField(this, "semaphore");
14
+ this.semaphore = new Semaphore.Semaphore(maxConnections);
15
+ }
16
+ createClient(schema, queryMeta) {
17
+ return new Client.Client(this, schema, queryMeta, new EventManager.EventManager(this.eventManager));
18
+ }
19
+ async scope(callback, options = {}) {
20
+ return await this.semaphore.execute(() => this.inner.scope(callback, options));
21
+ }
22
+ async transaction(callback, options = {}) {
23
+ return await this.scope(async (connection) => {
24
+ return await connection.transaction(callback);
25
+ }, options);
26
+ }
27
+ async query(sql, parameters = [], meta = {}) {
28
+ return await this.scope(async (connection) => {
29
+ return await connection.query(sql, parameters, meta);
30
+ });
31
+ }
32
+ getPoolStatus() {
33
+ return this.inner.getPoolStatus();
34
+ }
35
+ }
36
+ exports.ScopeLimitedConnection = ScopeLimitedConnection;
37
+ //# sourceMappingURL=ScopeLimitedConnection.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ScopeLimitedConnection.cjs","sources":["../../../../../packages/database/src/client/ScopeLimitedConnection.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { EventManager } from './EventManager.js'\nimport { Client } from './Client.js'\nimport { PoolStatus } from './Pool.js'\nimport { Semaphore } from '../utils/Semaphore.js'\n\n/**\n * Wraps a {@link Connection} and limits the number of pool connections that may be\n * acquired concurrently through it.\n *\n * Every top-level {@link Connection.scope} call (and therefore every {@link query} and\n * {@link transaction}) acquires exactly one pool connection. By routing those calls\n * through a {@link Semaphore} we cap how many connections a single owner of this\n * instance (typically a single HTTP request) can hold at once, preventing one request\n * from starving the shared pool under high concurrency.\n *\n * Nested scopes/transactions reuse the already-acquired connection (they go through\n * `AcquiredConnection`, not back to the underlying `Connection`), so they are not\n * counted again and cannot deadlock against the limit.\n */\nexport class ScopeLimitedConnection implements Connection.ConnectionType {\n\tprivate readonly semaphore: Semaphore\n\n\tconstructor(\n\t\tprivate readonly inner: Connection.ConnectionType,\n\t\tmaxConnections: number,\n\t\tpublic readonly eventManager: EventManager = inner.eventManager,\n\t) {\n\t\tthis.semaphore = new Semaphore(maxConnections)\n\t}\n\n\tcreateClient(schema: string, queryMeta: Record<string, any>): Client {\n\t\treturn new Client(this, schema, queryMeta, new EventManager(this.eventManager))\n\t}\n\n\tasync scope<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.semaphore.execute(() => this.inner.scope(callback, options))\n\t}\n\n\tasync transaction<Result>(\n\t\tcallback: (connection: Connection.TransactionLike) => Promise<Result> | Result,\n\t\toptions: { eventManager?: EventManager } = {},\n\t): Promise<Result> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.transaction(callback)\n\t\t}, options)\n\t}\n\n\tasync query<Row extends Record<string, any>>(\n\t\tsql: string,\n\t\tparameters: any[] = [],\n\t\tmeta: Record<string, any> = {},\n\t): Promise<Connection.Result<Row>> {\n\t\treturn await this.scope(async connection => {\n\t\t\treturn await connection.query(sql, parameters, meta)\n\t\t})\n\t}\n\n\tgetPoolStatus(): PoolStatus | undefined {\n\t\treturn this.inner.getPoolStatus()\n\t}\n}\n"],"names":["Semaphore","Client","EventManager"],"mappings":";;;;;;;;AAoBO,MAAM,uBAA4D;AAAA,EAGxE,YACkB,OACjB,gBACgB,eAA6B,MAAM,cAClD;AAHgB,SAAA,QAAA;AAED,SAAA,eAAA;AALjB,kBAAA,MAAiB,WAAA;AAOhB,SAAK,YAAY,IAAIA,UAAAA,UAAU,cAAc;AAAA,EAC9C;AAAA,EAEA,aAAa,QAAgB,WAAwC;AACpE,WAAO,IAAIC,OAAAA,OAAO,MAAM,QAAQ,WAAW,IAAIC,aAAAA,aAAa,KAAK,YAAY,CAAC;AAAA,EAC/E;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,UAAU,QAAQ,MAAM,KAAK,MAAM,MAAM,UAAU,OAAO,CAAC;AAAA,EAC9E;AAAA,EAEA,MAAM,YACL,UACA,UAA2C,IACzB;AAClB,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,YAAY,QAAQ;AAAA,IAC7C,GAAG,OAAO;AAAA,EACX;AAAA,EAEA,MAAM,MACL,KACA,aAAoB,CAAA,GACpB,OAA4B,CAAA,GACM;AAClC,WAAO,MAAM,KAAK,MAAM,OAAM,eAAc;AAC3C,aAAO,MAAM,WAAW,MAAM,KAAK,YAAY,IAAI;AAAA,IACpD,CAAC;AAAA,EACF;AAAA,EAEA,gBAAwC;AACvC,WAAO,KAAK,MAAM,cAAA;AAAA,EACnB;AACD;;"}
@@ -0,0 +1,37 @@
1
+ import { EventManager } from "./EventManager.js";
2
+ import { Client } from "./Client.js";
3
+ import { Semaphore } from "../utils/Semaphore.js";
4
+ var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
7
+ class ScopeLimitedConnection {
8
+ constructor(inner, maxConnections, eventManager = inner.eventManager) {
9
+ this.inner = inner;
10
+ this.eventManager = eventManager;
11
+ __publicField(this, "semaphore");
12
+ this.semaphore = new Semaphore(maxConnections);
13
+ }
14
+ createClient(schema, queryMeta) {
15
+ return new Client(this, schema, queryMeta, new EventManager(this.eventManager));
16
+ }
17
+ async scope(callback, options = {}) {
18
+ return await this.semaphore.execute(() => this.inner.scope(callback, options));
19
+ }
20
+ async transaction(callback, options = {}) {
21
+ return await this.scope(async (connection) => {
22
+ return await connection.transaction(callback);
23
+ }, options);
24
+ }
25
+ async query(sql, parameters = [], meta = {}) {
26
+ return await this.scope(async (connection) => {
27
+ return await connection.query(sql, parameters, meta);
28
+ });
29
+ }
30
+ getPoolStatus() {
31
+ return this.inner.getPoolStatus();
32
+ }
33
+ }
34
+ export {
35
+ ScopeLimitedConnection
36
+ };
37
+ //# sourceMappingURL=ScopeLimitedConnection.js.map