@contember/database 2.2.0-alpha.2 → 2.2.0-alpha.21

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 (189) hide show
  1. package/CLAUDE.md +23 -1
  2. package/dist/development/index.cjs +6 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +7 -1
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
  7. package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  8. package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
  9. package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
  10. package/dist/development/src/builders/WindowFunction.cjs +1 -1
  11. package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
  12. package/dist/development/src/builders/WindowFunction.js +1 -1
  13. package/dist/development/src/builders/WindowFunction.js.map +1 -1
  14. package/dist/development/src/client/AcquiredConnection.cjs +110 -32
  15. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  16. package/dist/development/src/client/AcquiredConnection.js +112 -34
  17. package/dist/development/src/client/AcquiredConnection.js.map +1 -1
  18. package/dist/development/src/client/Client.cjs +9 -1
  19. package/dist/development/src/client/Client.cjs.map +1 -1
  20. package/dist/development/src/client/Client.js +9 -1
  21. package/dist/development/src/client/Client.js.map +1 -1
  22. package/dist/development/src/client/Connection.cjs +48 -5
  23. package/dist/development/src/client/Connection.cjs.map +1 -1
  24. package/dist/development/src/client/Connection.js +48 -5
  25. package/dist/development/src/client/Connection.js.map +1 -1
  26. package/dist/development/src/client/EventManager.cjs +6 -2
  27. package/dist/development/src/client/EventManager.cjs.map +1 -1
  28. package/dist/development/src/client/EventManager.js +6 -2
  29. package/dist/development/src/client/EventManager.js.map +1 -1
  30. package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
  31. package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
  32. package/dist/development/src/client/RequestMemoryBudget.js +237 -0
  33. package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
  34. package/dist/development/src/client/Transaction.cjs +20 -8
  35. package/dist/development/src/client/Transaction.cjs.map +1 -1
  36. package/dist/development/src/client/Transaction.js +21 -9
  37. package/dist/development/src/client/Transaction.js.map +1 -1
  38. package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
  39. package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
  40. package/dist/development/src/client/cancelRunningStatement.js +32 -0
  41. package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
  42. package/dist/development/src/client/errors.cjs +12 -1
  43. package/dist/development/src/client/errors.cjs.map +1 -1
  44. package/dist/development/src/client/errors.js +12 -1
  45. package/dist/development/src/client/errors.js.map +1 -1
  46. package/dist/development/src/utils/pgClientFactory.cjs +4 -1
  47. package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
  48. package/dist/development/src/utils/pgClientFactory.js +4 -1
  49. package/dist/development/src/utils/pgClientFactory.js.map +1 -1
  50. package/dist/production/index.cjs +6 -0
  51. package/dist/production/index.cjs.map +1 -1
  52. package/dist/production/index.js +7 -1
  53. package/dist/production/index.js.map +1 -1
  54. package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
  55. package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
  56. package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
  57. package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
  58. package/dist/production/src/builders/WindowFunction.cjs +1 -1
  59. package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
  60. package/dist/production/src/builders/WindowFunction.js +1 -1
  61. package/dist/production/src/builders/WindowFunction.js.map +1 -1
  62. package/dist/production/src/client/AcquiredConnection.cjs +110 -32
  63. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  64. package/dist/production/src/client/AcquiredConnection.js +112 -34
  65. package/dist/production/src/client/AcquiredConnection.js.map +1 -1
  66. package/dist/production/src/client/Client.cjs +9 -1
  67. package/dist/production/src/client/Client.cjs.map +1 -1
  68. package/dist/production/src/client/Client.js +9 -1
  69. package/dist/production/src/client/Client.js.map +1 -1
  70. package/dist/production/src/client/Connection.cjs +48 -5
  71. package/dist/production/src/client/Connection.cjs.map +1 -1
  72. package/dist/production/src/client/Connection.js +48 -5
  73. package/dist/production/src/client/Connection.js.map +1 -1
  74. package/dist/production/src/client/EventManager.cjs +6 -2
  75. package/dist/production/src/client/EventManager.cjs.map +1 -1
  76. package/dist/production/src/client/EventManager.js +6 -2
  77. package/dist/production/src/client/EventManager.js.map +1 -1
  78. package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
  79. package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
  80. package/dist/production/src/client/RequestMemoryBudget.js +237 -0
  81. package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
  82. package/dist/production/src/client/Transaction.cjs +20 -8
  83. package/dist/production/src/client/Transaction.cjs.map +1 -1
  84. package/dist/production/src/client/Transaction.js +21 -9
  85. package/dist/production/src/client/Transaction.js.map +1 -1
  86. package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
  87. package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
  88. package/dist/production/src/client/cancelRunningStatement.js +32 -0
  89. package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
  90. package/dist/production/src/client/errors.cjs +12 -1
  91. package/dist/production/src/client/errors.cjs.map +1 -1
  92. package/dist/production/src/client/errors.js +12 -1
  93. package/dist/production/src/client/errors.js.map +1 -1
  94. package/dist/production/src/utils/pgClientFactory.cjs +4 -1
  95. package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
  96. package/dist/production/src/utils/pgClientFactory.js +4 -1
  97. package/dist/production/src/utils/pgClientFactory.js.map +1 -1
  98. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
  99. package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
  100. package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
  101. package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
  102. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +12 -3
  103. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
  104. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
  105. package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
  106. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
  107. package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
  108. package/dist/tests/src/tags.d.ts.map +1 -1
  109. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  110. package/dist/types/Literal.d.ts.map +1 -1
  111. package/dist/types/builders/CaseStatement.d.ts.map +1 -1
  112. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
  113. package/dist/types/builders/Compiler.d.ts.map +1 -1
  114. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
  115. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
  116. package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
  117. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
  118. package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
  119. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
  120. package/dist/types/builders/WindowFunction.d.ts +2 -1
  121. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  122. package/dist/types/builders/internal/Returning.d.ts.map +1 -1
  123. package/dist/types/builders/internal/Where.d.ts.map +1 -1
  124. package/dist/types/builders/internal/With.d.ts.map +1 -1
  125. package/dist/types/client/AcquiredConnection.d.ts +6 -1
  126. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  127. package/dist/types/client/Client.d.ts +8 -0
  128. package/dist/types/client/Client.d.ts.map +1 -1
  129. package/dist/types/client/Connection.d.ts +11 -2
  130. package/dist/types/client/Connection.d.ts.map +1 -1
  131. package/dist/types/client/EventManager.d.ts +5 -1
  132. package/dist/types/client/EventManager.d.ts.map +1 -1
  133. package/dist/types/client/PgClient.d.ts +13 -2
  134. package/dist/types/client/PgClient.d.ts.map +1 -1
  135. package/dist/types/client/Pool.d.ts.map +1 -1
  136. package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
  137. package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
  138. package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -1
  139. package/dist/types/client/Transaction.d.ts +3 -3
  140. package/dist/types/client/Transaction.d.ts.map +1 -1
  141. package/dist/types/client/cancelRunningStatement.d.ts +7 -0
  142. package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
  143. package/dist/types/client/errors.d.ts +5 -0
  144. package/dist/types/client/errors.d.ts.map +1 -1
  145. package/dist/types/index.d.ts +1 -0
  146. package/dist/types/index.d.ts.map +1 -1
  147. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
  148. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
  149. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
  150. package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
  151. package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
  152. package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
  153. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
  154. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
  155. package/dist/types/tsconfig.tsbuildinfo +1 -1
  156. package/dist/types/types.d.ts +15 -0
  157. package/dist/types/types.d.ts.map +1 -1
  158. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
  159. package/dist/types/utils/Mutex.d.ts.map +1 -1
  160. package/dist/types/utils/Semaphore.d.ts.map +1 -1
  161. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  162. package/dist/types/utils/listen.d.ts.map +1 -1
  163. package/dist/types/utils/pgClientFactory.d.ts +1 -2
  164. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  165. package/dist/types/utils/retryTransaction.d.ts.map +1 -1
  166. package/dist/types/utils/sql.d.ts.map +1 -1
  167. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  168. package/package.json +4 -3
  169. package/src/builders/LimitByGroupWrapper.ts +1 -1
  170. package/src/builders/WindowFunction.ts +3 -2
  171. package/src/client/AcquiredConnection.ts +131 -33
  172. package/src/client/Client.ts +11 -1
  173. package/src/client/Connection.ts +66 -3
  174. package/src/client/EventManager.ts +11 -1
  175. package/src/client/PgClient.ts +18 -2
  176. package/src/client/RequestMemoryBudget.ts +260 -0
  177. package/src/client/Transaction.ts +21 -8
  178. package/src/client/cancelRunningStatement.ts +36 -0
  179. package/src/client/errors.ts +15 -3
  180. package/src/index.ts +1 -0
  181. package/src/types.ts +15 -0
  182. package/src/utils/pgClientFactory.ts +5 -4
  183. package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
  184. package/tests/cases/unit/acquiredConnection.test.ts +209 -0
  185. package/tests/cases/unit/connection.test.ts +77 -1
  186. package/tests/cases/unit/createConnectionMockAlt.ts +35 -4
  187. package/tests/cases/unit/queryBuilder.test.ts +22 -1
  188. package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
  189. package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
@@ -20,9 +20,16 @@ class Client {
20
20
  this.eventManager = eventManager;
21
21
  }
22
22
  forSchema(schema) {
23
- const eventManager = new EventManager(this.eventManager.parent);
23
+ const eventManager = new EventManager(this.eventManager.parent, this.eventManager.memoryBudget, this.eventManager.chargesMemoryBudget);
24
24
  return new Client(this.connection, schema, this.queryMeta, eventManager);
25
25
  }
26
+ /**
27
+ * Binds the request memory budget: every query of the returned client is refused once the budget is exhausted.
28
+ * With `chargeRows`, the rows the client fetches are also accounted against the budget.
29
+ */
30
+ withMemoryBudget(memoryBudget, { chargeRows = true } = {}) {
31
+ return new Client(this.connection, this.schema, this.queryMeta, new EventManager(this.eventManager, memoryBudget, chargeRows));
32
+ }
26
33
  async scope(callback) {
27
34
  return await this.connection.scope(
28
35
  (connection) => callback(
@@ -65,6 +72,7 @@ class Client {
65
72
  return DeleteBuilder.create();
66
73
  }
67
74
  async query(sql, parameters = [], meta = {}) {
75
+ this.eventManager.memoryBudget?.check();
68
76
  return this.connection.scope(
69
77
  (connection) => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),
70
78
  { eventManager: this.eventManager }
@@ -1 +1 @@
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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A,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'\nimport { RequestMemoryBudget } from './RequestMemoryBudget.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, this.eventManager.memoryBudget, this.eventManager.chargesMemoryBudget)\n\t\treturn new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)\n\t}\n\n\t/**\n\t * Binds the request memory budget: every query of the returned client is refused once the budget is exhausted.\n\t * With `chargeRows`, the rows the client fetches are also accounted against the budget.\n\t */\n\tpublic withMemoryBudget(memoryBudget: RequestMemoryBudget, { chargeRows = true }: { chargeRows?: boolean } = {}): Client<ConnectionType> {\n\t\treturn new Client(this.connection, this.schema, this.queryMeta, new EventManager(this.eventManager, memoryBudget, chargeRows))\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\tthis.eventManager.memoryBudget?.check()\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":";;;;;;;;;;;;;;AAQA,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,QAAQ,KAAK,aAAa,cAAc,KAAK,aAAa,mBAAmB;AACrI,WAAO,IAAI,OAAuB,KAAK,YAAY,QAAQ,KAAK,WAAW,YAAY;AAAA,EACxF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,iBAAiB,cAAmC,EAAE,aAAa,KAAA,IAAmC,CAAA,GAA4B;AACxI,WAAO,IAAI,OAAO,KAAK,YAAY,KAAK,QAAQ,KAAK,WAAW,IAAI,aAAa,KAAK,cAAc,cAAc,UAAU,CAAC;AAAA,EAC9H;AAAA,EAEA,MAAM,MAAS,UAA+G;AAC7H,WAAO,MAAM,KAAK,WAAW;AAAA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A,QACR;AAAA,MAAA,CACA;AAAA,IAAA;AAEF,WAAO;AAAA,EACR;AACD;"}
@@ -4,18 +4,21 @@ 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 errorCodes = require("./errorCodes.cjs");
8
+ const errors = require("./errors.cjs");
7
9
  const ScopeLimitedConnection = require("./ScopeLimitedConnection.cjs");
8
10
  require("node:timers");
9
11
  require("../utils/Mutex.cjs");
10
12
  const pgClientFactory = require("../utils/pgClientFactory.cjs");
11
13
  const AcquiredConnection = require("./AcquiredConnection.cjs");
12
14
  class Connection {
13
- constructor(pool, eventManager = new EventManager.EventManager(null)) {
15
+ constructor(pool, eventManager = new EventManager.EventManager(null), options = {}) {
14
16
  this.pool = pool;
15
17
  this.eventManager = eventManager;
18
+ this.options = options;
16
19
  }
17
- static create({ pool = {}, ...config }, logError) {
18
- return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { ...pool, logError }));
20
+ static create({ pool = {}, ...config }, logError, options = {}) {
21
+ return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { ...pool, logError }), new EventManager.EventManager(null), options);
19
22
  }
20
23
  static createSingle(config, logError) {
21
24
  return new Connection(new Pool.Pool(pgClientFactory.createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }));
@@ -34,16 +37,48 @@ class Connection {
34
37
  return new ScopeLimitedConnection.ScopeLimitedConnection(this, maxConnections);
35
38
  }
36
39
  async scope(callback, options = {}) {
37
- const acquired = await this.pool.acquire();
38
40
  const eventManager = new EventManager.EventManager(options.eventManager ?? this.eventManager);
41
+ eventManager.memoryBudget?.check();
42
+ while (true) {
43
+ const attempt = await this.scopeOnce(callback, eventManager);
44
+ if (!attempt.stale) {
45
+ return attempt.result;
46
+ }
47
+ }
48
+ }
49
+ async scopeOnce(callback, eventManager) {
50
+ const acquired = await this.pool.acquire();
51
+ try {
52
+ eventManager.memoryBudget?.check();
53
+ } catch (e) {
54
+ this.pool.release(acquired);
55
+ throw e;
56
+ }
57
+ const reused = acquired.uses > 1;
58
+ let lost = false;
59
+ let answered = false;
60
+ const onError = () => {
61
+ lost = true;
62
+ };
63
+ const onAnswer = () => {
64
+ answered = true;
65
+ };
66
+ acquired.client.on("error", onError);
67
+ eventManager.on(EventManager.EventManager.Event.queryEnd, onAnswer);
39
68
  try {
40
69
  const connection = new AcquiredConnection.AcquiredConnection(acquired.client, eventManager);
41
70
  const result = await callback(connection);
42
71
  this.pool.release(acquired);
43
- return result;
72
+ return { stale: false, result };
44
73
  } catch (e) {
45
74
  this.pool.dispose(acquired);
75
+ if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
76
+ return { stale: true };
77
+ }
46
78
  throw e;
79
+ } finally {
80
+ acquired.client.off("error", onError);
81
+ eventManager.removeListener(EventManager.EventManager.Event.queryEnd, onAnswer);
47
82
  }
48
83
  }
49
84
  async transaction(callback, options = {}) {
@@ -66,6 +101,14 @@ class Connection {
66
101
  return this.pool.getPoolStatus();
67
102
  }
68
103
  }
104
+ const connectionLossCodes = /* @__PURE__ */ new Set([
105
+ errorCodes.ClientErrorCodes.CONNECTION_EXCEPTION,
106
+ errorCodes.ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
107
+ errorCodes.ClientErrorCodes.CONNECTION_FAILURE,
108
+ errorCodes.ClientErrorCodes.ADMIN_SHUTDOWN,
109
+ errorCodes.ClientErrorCodes.CRASH_SHUTDOWN
110
+ ]);
111
+ const isConnectionLoss = (error) => error instanceof errors.DatabaseError && error.code !== void 0 && connectionLossCodes.has(error.code);
69
112
  ((Connection2) => {
70
113
  Connection2.REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
71
114
  })(Connection || (Connection = {}));
@@ -1 +1 @@
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,GAAG,EAAE,gBAAgB,GA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,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'\nimport { DatabaseError } from './errors.js'\nimport { ClientErrorCodes } from './errorCodes.js'\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\tprivate readonly options: Connection.Options = {},\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\toptions: Connection.Options = {},\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)\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 eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\t// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.\n\t\twhile (true) {\n\t\t\tconst attempt = await this.scopeOnce(callback, eventManager)\n\t\t\tif (!attempt.stale) {\n\t\t\t\treturn attempt.result\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async scopeOnce<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\teventManager: EventManager,\n\t): Promise<{ stale: false; result: Result } | { stale: true }> {\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\tconst reused = acquired.uses > 1\n\t\t// pg emits `error` only for a connection lost unexpectedly, not for its own end(), e.g. after an exhausted budget.\n\t\tlet lost = false\n\t\tlet answered = false\n\t\tconst onError = () => {\n\t\t\tlost = true\n\t\t}\n\t\tconst onAnswer = () => {\n\t\t\tanswered = true\n\t\t}\n\t\tacquired.client.on('error', onError)\n\t\teventManager.on(EventManager.Event.queryEnd, onAnswer)\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 { stale: false, result }\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\t// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.\n\t\t\tif (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {\n\t\t\t\treturn { stale: true }\n\t\t\t}\n\t\t\tthrow e\n\t\t} finally {\n\t\t\tacquired.client.off('error', onError)\n\t\t\teventManager.removeListener(EventManager.Event.queryEnd, onAnswer)\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\nconst connectionLossCodes = new Set<string>([\n\tClientErrorCodes.CONNECTION_EXCEPTION,\n\tClientErrorCodes.CONNECTION_DOES_NOT_EXIST,\n\tClientErrorCodes.CONNECTION_FAILURE,\n\tClientErrorCodes.ADMIN_SHUTDOWN,\n\tClientErrorCodes.CRASH_SHUTDOWN,\n])\n\nconst isConnectionLoss = (error: unknown): boolean =>\n\terror instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)\n\nnamespace Connection {\n\texport interface Options {\n\t\t/**\n\t\t * Runs a scope again on another connection when a connection taken from the pool turns out to be closed by\n\t\t * the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.\n\t\t */\n\t\tretryStaleConnection?: boolean\n\t}\n\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","Acqu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,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;AAEA,MAAM,0CAA0B,IAAY;AAAA,EAC3CM,WAAAA,iBAAiB;AAAA,EACjBA,WAAAA,iBAAiB;AAAA,EACjBA,WAAAA,iBAAiB;AAAA,EACjBA,WAAAA,iBAAiB;AAAA,EACjBA,4BAAiB;AAClB,CAAC;AAED,MAAM,mBAAmB,CAAC,UACzB,iBAAiBC,OAAAA,iBAAiB,MAAM,SAAS,UAAa,oBAAoB,IAAI,MAAM,IAAI;AAAA,CAEjG,CAAUC,gBAAV;AA6EcA,cAAA,kBAAkB;AAAA,GA7EtB,eAAA,aAAA,CAAA,EAAA;;"}
@@ -2,18 +2,21 @@ 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 { ClientErrorCodes } from "./errorCodes.js";
6
+ import { DatabaseError } from "./errors.js";
5
7
  import { ScopeLimitedConnection } from "./ScopeLimitedConnection.js";
6
8
  import "node:timers";
7
9
  import "../utils/Mutex.js";
8
10
  import { createPgClientFactory } from "../utils/pgClientFactory.js";
9
11
  import { AcquiredConnection } from "./AcquiredConnection.js";
10
12
  class Connection {
11
- constructor(pool, eventManager = new EventManager(null)) {
13
+ constructor(pool, eventManager = new EventManager(null), options = {}) {
12
14
  this.pool = pool;
13
15
  this.eventManager = eventManager;
16
+ this.options = options;
14
17
  }
15
- static create({ pool = {}, ...config }, logError) {
16
- return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }));
18
+ static create({ pool = {}, ...config }, logError, options = {}) {
19
+ return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options);
17
20
  }
18
21
  static createSingle(config, logError) {
19
22
  return new Connection(new Pool(createPgClientFactory(config), { maxConnections: 1, maxIdle: 0, logError }));
@@ -32,16 +35,48 @@ class Connection {
32
35
  return new ScopeLimitedConnection(this, maxConnections);
33
36
  }
34
37
  async scope(callback, options = {}) {
35
- const acquired = await this.pool.acquire();
36
38
  const eventManager = new EventManager(options.eventManager ?? this.eventManager);
39
+ eventManager.memoryBudget?.check();
40
+ while (true) {
41
+ const attempt = await this.scopeOnce(callback, eventManager);
42
+ if (!attempt.stale) {
43
+ return attempt.result;
44
+ }
45
+ }
46
+ }
47
+ async scopeOnce(callback, eventManager) {
48
+ const acquired = await this.pool.acquire();
49
+ try {
50
+ eventManager.memoryBudget?.check();
51
+ } catch (e) {
52
+ this.pool.release(acquired);
53
+ throw e;
54
+ }
55
+ const reused = acquired.uses > 1;
56
+ let lost = false;
57
+ let answered = false;
58
+ const onError = () => {
59
+ lost = true;
60
+ };
61
+ const onAnswer = () => {
62
+ answered = true;
63
+ };
64
+ acquired.client.on("error", onError);
65
+ eventManager.on(EventManager.Event.queryEnd, onAnswer);
37
66
  try {
38
67
  const connection = new AcquiredConnection(acquired.client, eventManager);
39
68
  const result = await callback(connection);
40
69
  this.pool.release(acquired);
41
- return result;
70
+ return { stale: false, result };
42
71
  } catch (e) {
43
72
  this.pool.dispose(acquired);
73
+ if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
74
+ return { stale: true };
75
+ }
44
76
  throw e;
77
+ } finally {
78
+ acquired.client.off("error", onError);
79
+ eventManager.removeListener(EventManager.Event.queryEnd, onAnswer);
45
80
  }
46
81
  }
47
82
  async transaction(callback, options = {}) {
@@ -64,6 +99,14 @@ class Connection {
64
99
  return this.pool.getPoolStatus();
65
100
  }
66
101
  }
102
+ const connectionLossCodes = /* @__PURE__ */ new Set([
103
+ ClientErrorCodes.CONNECTION_EXCEPTION,
104
+ ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
105
+ ClientErrorCodes.CONNECTION_FAILURE,
106
+ ClientErrorCodes.ADMIN_SHUTDOWN,
107
+ ClientErrorCodes.CRASH_SHUTDOWN
108
+ ]);
109
+ const isConnectionLoss = (error) => error instanceof DatabaseError && error.code !== void 0 && connectionLossCodes.has(error.code);
67
110
  ((Connection2) => {
68
111
  Connection2.REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
69
112
  })(Connection || (Connection = {}));
@@ -1 +1 @@
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 REPEATABLE READ'\n}\n\nexport { Connection }\n"],"names":["Connection"],"mappings":";;;;;;;;;AASA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAI,aAAa,IAAI,GACjE;AAFgB,SAAA,OAAA;AACD,SAAA,eAAA;AAAA,EAEjB;AAAA,EAEA,OAAc,OACb,EA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AAA,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'\nimport { DatabaseError } from './errors.js'\nimport { ClientErrorCodes } from './errorCodes.js'\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\tprivate readonly options: Connection.Options = {},\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\toptions: Connection.Options = {},\n\t): Connection {\n\t\treturn new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)\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 eventManager = new EventManager(options.eventManager ?? this.eventManager)\n\t\teventManager.memoryBudget?.check()\n\t\t// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.\n\t\twhile (true) {\n\t\t\tconst attempt = await this.scopeOnce(callback, eventManager)\n\t\t\tif (!attempt.stale) {\n\t\t\t\treturn attempt.result\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async scopeOnce<Result>(\n\t\tcallback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,\n\t\teventManager: EventManager,\n\t): Promise<{ stale: false; result: Result } | { stale: true }> {\n\t\tconst acquired = await this.pool.acquire()\n\t\t// A budget exhausted while waiting for the pool must not cost a healthy connection.\n\t\ttry {\n\t\t\teventManager.memoryBudget?.check()\n\t\t} catch (e) {\n\t\t\tthis.pool.release(acquired)\n\t\t\tthrow e\n\t\t}\n\t\tconst reused = acquired.uses > 1\n\t\t// pg emits `error` only for a connection lost unexpectedly, not for its own end(), e.g. after an exhausted budget.\n\t\tlet lost = false\n\t\tlet answered = false\n\t\tconst onError = () => {\n\t\t\tlost = true\n\t\t}\n\t\tconst onAnswer = () => {\n\t\t\tanswered = true\n\t\t}\n\t\tacquired.client.on('error', onError)\n\t\teventManager.on(EventManager.Event.queryEnd, onAnswer)\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 { stale: false, result }\n\t\t} catch (e) {\n\t\t\tthis.pool.dispose(acquired)\n\t\t\t// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.\n\t\t\tif (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {\n\t\t\t\treturn { stale: true }\n\t\t\t}\n\t\t\tthrow e\n\t\t} finally {\n\t\t\tacquired.client.off('error', onError)\n\t\t\teventManager.removeListener(EventManager.Event.queryEnd, onAnswer)\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\nconst connectionLossCodes = new Set<string>([\n\tClientErrorCodes.CONNECTION_EXCEPTION,\n\tClientErrorCodes.CONNECTION_DOES_NOT_EXIST,\n\tClientErrorCodes.CONNECTION_FAILURE,\n\tClientErrorCodes.ADMIN_SHUTDOWN,\n\tClientErrorCodes.CRASH_SHUTDOWN,\n])\n\nconst isConnectionLoss = (error: unknown): boolean =>\n\terror instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)\n\nnamespace Connection {\n\texport interface Options {\n\t\t/**\n\t\t * Runs a scope again on another connection when a connection taken from the pool turns out to be closed by\n\t\t * the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.\n\t\t */\n\t\tretryStaleConnection?: boolean\n\t}\n\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":["Connection"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAyG;AAAA,EAC9G,YACkB,MACD,eAA6B,IAAI,aAAa,IAAI,GACjD,UAA8B,IAC9C;AAHgB,SAAA,OAAA;AACD,SAAA,eAAA;AACC,SAAA,UAAA;AAAA,EAElB;AAAA,EAEA,OAAc,OACb,EAAE,OAAO,CAAA,GAAI,GAAG,UAChB,UACA,UAA8B,IACjB;AACb,WAAO,IAAI,WAAW,IAAI,KAAK,sBAAsB,MAAM,GAAG,EAAE,GAAG,MAAM,UAAU,GAAG,IAAI,aAAa,IAAI,GAAG,OAAO;AAAA,EACtH;AAAA,EAEA,OAAc,aACb,QACA,UACa;AACb,WAAO,IAAI,WAAW,IAAI,KAAK,sBAAsB,MAAM,GAAG,EAAE,gBAAgB,GAAG,SAAS,GAAG,SAAA,CAAU,CAAC;AAAA,EAC3G;AAAA,EAEO,aAAa,QAAgB,WAAwC;AAC3E,WAAO,IAAI,OAAO,MAAM,QAAQ,WAAW,IAAI,aAAa,KAAK,YAAY,CAAC;AAAA,EAC/E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,mBAAmB,gBAAmD;AAC5E,WAAO,IAAI,uBAAuB,MAAM,cAAc;AAAA,EACvD;AAAA,EAEA,MAAM,MACL,UACA,UAA2C,IACzB;AAClB,UAAM,eAAe,IAAI,aAAa,QAAQ,gBAAgB,KAAK,YAAY;AAC/E,iBAAa,cAAc,MAAA;AAE3B,WAAO,MAAM;AACZ,YAAM,UAAU,MAAM,KAAK,UAAU,UAAU,YAAY;AAC3D,UAAI,CAAC,QAAQ,OAAO;AACnB,eAAO,QAAQ;AAAA,MAChB;AAAA,IACD;AAAA,EACD;AAAA,EAEA,MAA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A,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;AAEA,MAAM,0CAA0B,IAAY;AAAA,EAC3C,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,iBAAiB;AAClB,CAAC;AAED,MAAM,mBAAmB,CAAC,UACzB,iBAAiB,iBAAiB,MAAM,SAAS,UAAa,oBAAoB,IAAI,MAAM,IAAI;AAAA,CAEjG,CAAUA,gBAAV;AA6EcA,cAAA,kBAAkB;AAAA,GA7EtB,eAAA,aAAA,CAAA,EAAA;"}
@@ -2,15 +2,19 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  var __defProp = Object.defineProperty;
4
4
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
6
  class EventManager {
7
- constructor(parent = null) {
7
+ constructor(parent = null, memoryBudget = parent?.memoryBudget, chargesMemoryBudget = parent?.chargesMemoryBudget ?? false) {
8
8
  this.parent = parent;
9
+ __publicField(this, "memoryBudget");
10
+ __publicField(this, "chargesMemoryBudget");
9
11
  __publicField(this, "listeners", {
10
12
  [EventManager.Event.queryStart]: [],
11
13
  [EventManager.Event.queryEnd]: [],
12
14
  [EventManager.Event.queryError]: []
13
15
  });
16
+ this.memoryBudget = memoryBudget ?? void 0;
17
+ this.chargesMemoryBudget = this.memoryBudget !== void 0 && chargesMemoryBudget;
14
18
  }
15
19
  on(event, cb) {
16
20
  this.listeners[event].push(cb);
@@ -1 +1 @@
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
+ {"version":3,"file":"EventManager.cjs","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { RequestMemoryBudget } from './RequestMemoryBudget.js'\n\nclass EventManager {\n\t/** Every query bound to a budget is refused once it is exhausted; only queries that also charge it account their rows. */\n\tpublic readonly memoryBudget: RequestMemoryBudget | undefined\n\tpublic readonly chargesMemoryBudget: boolean\n\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\tmemoryBudget: RequestMemoryBudget | null | undefined = parent?.memoryBudget,\n\t\tchargesMemoryBudget: boolean = parent?.chargesMemoryBudget ?? false,\n\t) {\n\t\tthis.memoryBudget = memoryBudget ?? undefined\n\t\tthis.chargesMemoryBudget = this.memoryBudget !== undefined && chargesMemoryBudget\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":";;;;;AAGA,MAAM,aAAa;AAAA,EAWlB,YACiB,SAA8B,MAC9C,eAAuD,QAAQ,cAC/D,sBAA+B,QAAQ,uBAAuB,OAC7D;AAHe,SAAA,SAAA;AAVjB,kBAAA,MAAgB,cAAA;AAChB,kBAAA,MAAgB,qBAAA;AAEhB,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;AAOC,SAAK,eAAe,gBAAgB;AACpC,SAAK,sBAAsB,KAAK,iBAAiB,UAAa;AAAA,EAC/D;AAAA,EAEA,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,14 +1,18 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "", value);
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
4
  class EventManager {
5
- constructor(parent = null) {
5
+ constructor(parent = null, memoryBudget = parent?.memoryBudget, chargesMemoryBudget = parent?.chargesMemoryBudget ?? false) {
6
6
  this.parent = parent;
7
+ __publicField(this, "memoryBudget");
8
+ __publicField(this, "chargesMemoryBudget");
7
9
  __publicField(this, "listeners", {
8
10
  [EventManager.Event.queryStart]: [],
9
11
  [EventManager.Event.queryEnd]: [],
10
12
  [EventManager.Event.queryError]: []
11
13
  });
14
+ this.memoryBudget = memoryBudget ?? void 0;
15
+ this.chargesMemoryBudget = this.memoryBudget !== void 0 && chargesMemoryBudget;
12
16
  }
13
17
  on(event, cb) {
14
18
  this.listeners[event].push(cb);
@@ -1 +1 @@
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
+ {"version":3,"file":"EventManager.js","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { RequestMemoryBudget } from './RequestMemoryBudget.js'\n\nclass EventManager {\n\t/** Every query bound to a budget is refused once it is exhausted; only queries that also charge it account their rows. */\n\tpublic readonly memoryBudget: RequestMemoryBudget | undefined\n\tpublic readonly chargesMemoryBudget: boolean\n\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\tmemoryBudget: RequestMemoryBudget | null | undefined = parent?.memoryBudget,\n\t\tchargesMemoryBudget: boolean = parent?.chargesMemoryBudget ?? false,\n\t) {\n\t\tthis.memoryBudget = memoryBudget ?? undefined\n\t\tthis.chargesMemoryBudget = this.memoryBudget !== undefined && chargesMemoryBudget\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":";;;AAGA,MAAM,aAAa;AAAA,EAWlB,YACiB,SAA8B,MAC9C,eAAuD,QAAQ,cAC/D,sBAA+B,QAAQ,uBAAuB,OAC7D;AAHe,SAAA,SAAA;AAVjB,kBAAA,MAAgB,cAAA;AAChB,kBAAA,MAAgB,qBAAA;AAEhB,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;AAOC,SAAK,eAAe,gBAAgB;AACpC,SAAK,sBAAsB,KAAK,iBAAiB,UAAa;AAAA,EAC/D;AAAA,EAEA,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;"}
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const node_buffer = require("node:buffer");
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, typeof key !== "symbol" ? key + "" : key, value);
7
+ const rowCompletionOverheadBytes = 256;
8
+ const maximumRecursiveEstimateDepth = 64;
9
+ const isBun = process.versions.bun !== void 0;
10
+ const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }) => {
11
+ if (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {
12
+ return "warnBytes must be a positive safe integer";
13
+ }
14
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
15
+ return "maxBytes must be a positive safe integer";
16
+ }
17
+ if (warnBytes > maxBytes) {
18
+ return "warnBytes must not exceed maxBytes";
19
+ }
20
+ return void 0;
21
+ };
22
+ class RequestMemoryBudgetExceededError extends Error {
23
+ constructor() {
24
+ super("Request memory budget exceeded");
25
+ this.name = "RequestMemoryBudgetExceededError";
26
+ }
27
+ }
28
+ class RequestMemoryBudget {
29
+ constructor(options) {
30
+ this.options = options;
31
+ __publicField(this, "databaseBytes", 0);
32
+ __publicField(this, "hydrationBytes", 0);
33
+ __publicField(this, "peakBytes", 0);
34
+ __publicField(this, "databaseRows", 0);
35
+ __publicField(this, "largestDatabaseRowBytes", 0);
36
+ __publicField(this, "databaseStrings", new StringMemoryEstimate());
37
+ __publicField(this, "failure");
38
+ __publicField(this, "exceededListeners", /* @__PURE__ */ new Set());
39
+ const optionsError = validateRequestMemoryBudgetOptions(options);
40
+ if (optionsError) {
41
+ throw new Error(`Invalid request memory budget: ${optionsError}`);
42
+ }
43
+ }
44
+ get exceeded() {
45
+ return this.failure !== void 0;
46
+ }
47
+ check() {
48
+ if (this.failure) {
49
+ throw this.failure;
50
+ }
51
+ }
52
+ /** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */
53
+ onExceeded(listener) {
54
+ if (this.failure) {
55
+ listener(this.failure);
56
+ return () => {
57
+ };
58
+ }
59
+ this.exceededListeners.add(listener);
60
+ return () => this.exceededListeners.delete(listener);
61
+ }
62
+ addDatabaseRow(row) {
63
+ this.check();
64
+ this.databaseRows++;
65
+ let rowBytes = 40;
66
+ for (const key in row) {
67
+ if (Object.prototype.hasOwnProperty.call(row, key)) {
68
+ rowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings);
69
+ }
70
+ }
71
+ this.databaseBytes += rowBytes;
72
+ this.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes);
73
+ this.update();
74
+ }
75
+ addHydrationBytes(bytes) {
76
+ this.check();
77
+ this.hydrationBytes += bytes;
78
+ this.update();
79
+ }
80
+ snapshot() {
81
+ return {
82
+ estimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,
83
+ reservedCompletionBytes: this.getCompletionBytes(),
84
+ estimatedPeakBytes: this.peakBytes,
85
+ databaseRows: this.databaseRows,
86
+ databaseBytes: this.databaseBytes,
87
+ hydrationBytes: this.hydrationBytes,
88
+ warnBytes: this.options.warnBytes,
89
+ maxBytes: this.options.maxBytes,
90
+ warningThresholdExceeded: this.peakBytes > this.options.warnBytes,
91
+ maxBytesExceeded: this.peakBytes > this.options.maxBytes
92
+ };
93
+ }
94
+ getCompletionBytes() {
95
+ const projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2 + this.databaseStrings.serializedBytes + this.hydrationBytes;
96
+ const decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1);
97
+ return Math.max(projectedCompletionBytes, decodingBytes) + this.databaseRows * rowCompletionOverheadBytes;
98
+ }
99
+ update() {
100
+ const estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes();
101
+ this.peakBytes = Math.max(this.peakBytes, estimatedBytes);
102
+ if (estimatedBytes > this.options.maxBytes) {
103
+ const failure = new RequestMemoryBudgetExceededError();
104
+ this.failure = failure;
105
+ const listeners = [...this.exceededListeners];
106
+ this.exceededListeners.clear();
107
+ listeners.forEach((listener) => listener(failure));
108
+ throw failure;
109
+ }
110
+ }
111
+ }
112
+ function estimateValueBytes(value, strings) {
113
+ return estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0);
114
+ }
115
+ function estimateStructuredValueBytes(value, strings, depth) {
116
+ if (depth >= maximumRecursiveEstimateDepth) {
117
+ return estimateDeepValueBytes(value, strings);
118
+ }
119
+ if (Array.isArray(value)) {
120
+ let bytes2 = 32 + value.length * 8;
121
+ for (let i = 0; i < value.length; i++) {
122
+ const item = value[i];
123
+ const scalarBytes = estimateScalarBytes(item, strings);
124
+ bytes2 += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1);
125
+ }
126
+ return bytes2;
127
+ }
128
+ let bytes = 32;
129
+ if (value !== null && typeof value === "object") {
130
+ for (const key in value) {
131
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
132
+ const item = Reflect.get(value, key);
133
+ const scalarBytes = estimateScalarBytes(item, strings);
134
+ strings.addPropertyName(key);
135
+ bytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1));
136
+ }
137
+ }
138
+ }
139
+ return bytes;
140
+ }
141
+ function estimateDeepValueBytes(value, strings) {
142
+ const scalarBytes = estimateScalarBytes(value, strings);
143
+ if (scalarBytes !== void 0) {
144
+ return scalarBytes;
145
+ }
146
+ let bytes = 0;
147
+ const pending = [[value].values()];
148
+ while (pending.length > 0) {
149
+ const next = pending[pending.length - 1].next();
150
+ if (next.done) {
151
+ pending.pop();
152
+ continue;
153
+ }
154
+ const current = next.value;
155
+ const scalarBytes2 = estimateScalarBytes(current, strings);
156
+ if (scalarBytes2 !== void 0) {
157
+ bytes += scalarBytes2;
158
+ } else if (Array.isArray(current)) {
159
+ bytes += 32 + current.length * 8;
160
+ pending.push(current.values());
161
+ } else if (current !== null && typeof current === "object") {
162
+ bytes += 32;
163
+ let hasNestedValues = false;
164
+ for (const key in current) {
165
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
166
+ continue;
167
+ }
168
+ strings.addPropertyName(key);
169
+ bytes += 16;
170
+ const scalarBytes3 = estimateScalarBytes(Reflect.get(current, key), strings);
171
+ if (scalarBytes3 === void 0) {
172
+ hasNestedValues = true;
173
+ } else {
174
+ bytes += scalarBytes3;
175
+ }
176
+ }
177
+ if (hasNestedValues) {
178
+ pending.push(nestedValues(current));
179
+ }
180
+ }
181
+ }
182
+ return bytes;
183
+ function* nestedValues(object) {
184
+ for (const key in object) {
185
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
186
+ const value2 = Reflect.get(object, key);
187
+ if (value2 !== null && typeof value2 === "object" && !(value2 instanceof Date) && !ArrayBuffer.isView(value2)) {
188
+ yield value2;
189
+ }
190
+ }
191
+ }
192
+ }
193
+ }
194
+ function estimateScalarBytes(value, strings) {
195
+ if (typeof value === "string") {
196
+ return 24 + strings.add(value);
197
+ }
198
+ if (value === null || typeof value !== "object") {
199
+ return 8;
200
+ }
201
+ if (value instanceof Date) {
202
+ return 40;
203
+ }
204
+ if (ArrayBuffer.isView(value)) {
205
+ return 64 + value.byteLength;
206
+ }
207
+ return void 0;
208
+ }
209
+ class StringMemoryEstimate {
210
+ constructor() {
211
+ __publicField(this, "codeUnits", 0);
212
+ __publicField(this, "storageBytes", 0);
213
+ __publicField(this, "nonAscii", false);
214
+ }
215
+ get retainedBytes() {
216
+ return this.storageBytes;
217
+ }
218
+ get serializedBytes() {
219
+ return this.codeUnits * (this.nonAscii ? 2 : 1);
220
+ }
221
+ add(value) {
222
+ const ascii = node_buffer.Buffer.byteLength(value) === value.length;
223
+ this.nonAscii || (this.nonAscii = !ascii);
224
+ this.codeUnits += value.length;
225
+ const bytes = ascii ? value.length : value.length * 2;
226
+ this.storageBytes += bytes;
227
+ return bytes;
228
+ }
229
+ // Runtimes share property names between objects of one shape; only their serialized copies are new.
230
+ addPropertyName(key) {
231
+ this.codeUnits += key.length;
232
+ }
233
+ }
234
+ exports.RequestMemoryBudget = RequestMemoryBudget;
235
+ exports.RequestMemoryBudgetExceededError = RequestMemoryBudgetExceededError;
236
+ exports.validateRequestMemoryBudgetOptions = validateRequestMemoryBudgetOptions;
237
+ //# sourceMappingURL=RequestMemoryBudget.cjs.map