@contember/database 2.2.0-alpha.1 → 2.2.0-alpha.10

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 (184) hide show
  1. package/CLAUDE.md +19 -0
  2. package/dist/development/index.cjs +5 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +6 -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 +105 -32
  15. package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
  16. package/dist/development/src/client/AcquiredConnection.js +107 -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 +8 -1
  23. package/dist/development/src/client/Connection.cjs.map +1 -1
  24. package/dist/development/src/client/Connection.js +8 -1
  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 +6 -0
  43. package/dist/development/src/client/errors.cjs.map +1 -1
  44. package/dist/development/src/client/errors.js +6 -0
  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 +5 -0
  51. package/dist/production/index.cjs.map +1 -1
  52. package/dist/production/index.js +6 -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 +105 -32
  63. package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
  64. package/dist/production/src/client/AcquiredConnection.js +107 -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 +8 -1
  71. package/dist/production/src/client/Connection.cjs.map +1 -1
  72. package/dist/production/src/client/Connection.js +8 -1
  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 +6 -0
  91. package/dist/production/src/client/errors.cjs.map +1 -1
  92. package/dist/production/src/client/errors.js +6 -0
  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 +6 -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/src/tags.d.ts.map +1 -1
  107. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  108. package/dist/types/Literal.d.ts.map +1 -1
  109. package/dist/types/builders/CaseStatement.d.ts.map +1 -1
  110. package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
  111. package/dist/types/builders/Compiler.d.ts.map +1 -1
  112. package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
  113. package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
  114. package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
  115. package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
  116. package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
  117. package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
  118. package/dist/types/builders/WindowFunction.d.ts +2 -1
  119. package/dist/types/builders/WindowFunction.d.ts.map +1 -1
  120. package/dist/types/builders/internal/Returning.d.ts.map +1 -1
  121. package/dist/types/builders/internal/Where.d.ts.map +1 -1
  122. package/dist/types/builders/internal/With.d.ts.map +1 -1
  123. package/dist/types/client/AcquiredConnection.d.ts +6 -1
  124. package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
  125. package/dist/types/client/Client.d.ts +8 -0
  126. package/dist/types/client/Client.d.ts.map +1 -1
  127. package/dist/types/client/Connection.d.ts.map +1 -1
  128. package/dist/types/client/EventManager.d.ts +5 -1
  129. package/dist/types/client/EventManager.d.ts.map +1 -1
  130. package/dist/types/client/PgClient.d.ts +12 -1
  131. package/dist/types/client/PgClient.d.ts.map +1 -1
  132. package/dist/types/client/Pool.d.ts.map +1 -1
  133. package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
  134. package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
  135. package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -1
  136. package/dist/types/client/Transaction.d.ts +3 -3
  137. package/dist/types/client/Transaction.d.ts.map +1 -1
  138. package/dist/types/client/cancelRunningStatement.d.ts +7 -0
  139. package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
  140. package/dist/types/client/errors.d.ts +3 -0
  141. package/dist/types/client/errors.d.ts.map +1 -1
  142. package/dist/types/index.d.ts +1 -0
  143. package/dist/types/index.d.ts.map +1 -1
  144. package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
  145. package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
  146. package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
  147. package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
  148. package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
  149. package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
  150. package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
  151. package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
  152. package/dist/types/tsconfig.tsbuildinfo +1 -1
  153. package/dist/types/types.d.ts +15 -0
  154. package/dist/types/types.d.ts.map +1 -1
  155. package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
  156. package/dist/types/utils/Mutex.d.ts.map +1 -1
  157. package/dist/types/utils/Semaphore.d.ts.map +1 -1
  158. package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  159. package/dist/types/utils/listen.d.ts.map +1 -1
  160. package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
  161. package/dist/types/utils/retryTransaction.d.ts.map +1 -1
  162. package/dist/types/utils/sql.d.ts.map +1 -1
  163. package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  164. package/package.json +3 -3
  165. package/src/builders/LimitByGroupWrapper.ts +1 -1
  166. package/src/builders/WindowFunction.ts +3 -2
  167. package/src/client/AcquiredConnection.ts +125 -33
  168. package/src/client/Client.ts +11 -1
  169. package/src/client/Connection.ts +9 -1
  170. package/src/client/EventManager.ts +11 -1
  171. package/src/client/PgClient.ts +16 -1
  172. package/src/client/RequestMemoryBudget.ts +260 -0
  173. package/src/client/Transaction.ts +21 -8
  174. package/src/client/cancelRunningStatement.ts +36 -0
  175. package/src/client/errors.ts +6 -0
  176. package/src/index.ts +1 -0
  177. package/src/types.ts +15 -0
  178. package/src/utils/pgClientFactory.ts +4 -1
  179. package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
  180. package/tests/cases/unit/acquiredConnection.test.ts +154 -0
  181. package/tests/cases/unit/connection.test.ts +32 -0
  182. package/tests/cases/unit/createConnectionMockAlt.ts +17 -3
  183. package/tests/cases/unit/queryBuilder.test.ts +22 -1
  184. package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
@@ -1,6 +1,6 @@
1
1
  import { Connection } from './Connection.js'
2
2
  import { EventManager } from './EventManager.js'
3
- import { Mutex } from '../utils/index.js'
3
+ import { Mutex, MutexDeadlockError } from '../utils/index.js'
4
4
  import { executeTransaction, Transaction } from './Transaction.js'
5
5
  import { ClientErrorCodes } from './errorCodes.js'
6
6
  import {
@@ -9,11 +9,14 @@ import {
9
9
  NotNullViolationError,
10
10
  QueryError,
11
11
  SerializationFailureError,
12
+ TerminatedConnectionError,
12
13
  TransactionAbortedError,
13
14
  UniqueViolationError,
14
15
  } from './errors.js'
15
16
  import { PgClient } from './PgClient.js'
16
- import { Notification } from 'pg'
17
+ import { cancelRunningStatement } from './cancelRunningStatement.js'
18
+ import { Notification, Query, QueryResult, QueryResultRow } from 'pg'
19
+ import { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'
17
20
 
18
21
  export class AcquiredConnection implements Connection.AcquiredConnectionLike {
19
22
  private mutex = new Mutex()
@@ -21,6 +24,7 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
21
24
  constructor(
22
25
  private readonly pgClient: PgClient,
23
26
  public readonly eventManager: EventManager,
27
+ private readonly physicalConnection = { terminated: false },
24
28
  ) {
25
29
  }
26
30
 
@@ -29,7 +33,7 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
29
33
  options: { eventManager?: EventManager } = {},
30
34
  ): Promise<Result> {
31
35
  return await this.mutex.execute(async () => {
32
- return await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager))
36
+ return await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))
33
37
  })
34
38
  }
35
39
 
@@ -49,51 +53,139 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
49
53
  parameters: any[] = [],
50
54
  meta: Record<string, any> = {},
51
55
  ): Promise<Connection.Result<Row>> {
52
- return await this.mutex.execute(async () => {
53
- try {
54
- this.eventManager.fire(EventManager.Event.queryStart, { sql, parameters, meta })
56
+ // A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.
57
+ this.refuseExhaustedOrTerminated()
58
+
59
+ const query: Connection.Query = { sql, parameters, meta }
55
60
 
56
- let result: Connection.Result<Row>
61
+ try {
62
+ this.eventManager.fire(EventManager.Event.queryStart, query)
63
+
64
+ const result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {
65
+ // A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.
66
+ this.refuseExhaustedOrTerminated()
67
+ const memoryBudget = this.eventManager.memoryBudget
57
68
  const startHrTime = process.hrtime.bigint()
58
69
 
59
- result = await this.pgClient.query(prepareSql(sql), parameters)
70
+ const pgResult = memoryBudget && this.eventManager.chargesMemoryBudget
71
+ ? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)
72
+ : await this.pgClient.query(prepareSql(sql), parameters)
60
73
 
61
74
  const endHrTime = process.hrtime.bigint()
62
75
  const durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)
63
- result = {
64
- ...result,
76
+
77
+ return {
78
+ ...pgResult,
65
79
  timing: {
66
80
  selfDuration: durationUs,
67
81
  totalDuration: durationUs,
68
82
  },
69
83
  }
84
+ })
70
85
 
71
- this.eventManager.fire(EventManager.Event.queryEnd, { sql, parameters, meta }, result)
86
+ this.eventManager.fire(EventManager.Event.queryEnd, query, result)
72
87
 
73
- return result
74
- } catch (error) {
75
- if (!(error instanceof Error)) {
76
- throw error
88
+ return result
89
+ } catch (error) {
90
+ if (!(error instanceof Error)) {
91
+ throw error
92
+ }
93
+ this.eventManager.fire(EventManager.Event.queryError, query, error)
94
+
95
+ // neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated
96
+ if (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {
97
+ throw error
98
+ }
99
+
100
+ switch ((error as any).code) {
101
+ case ClientErrorCodes.NOT_NULL_VIOLATION:
102
+ throw new NotNullViolationError(sql, parameters, error)
103
+ case ClientErrorCodes.FOREIGN_KEY_VIOLATION:
104
+ throw new ForeignKeyViolationError(sql, parameters, error)
105
+ case ClientErrorCodes.UNIQUE_VIOLATION:
106
+ throw new UniqueViolationError(sql, parameters, error)
107
+ case ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
108
+ throw new SerializationFailureError(sql, parameters, error)
109
+ case ClientErrorCodes.INVALID_TEXT_REPRESENTATION:
110
+ case ClientErrorCodes.DATETIME_FIELD_OVERFLOW:
111
+ throw new InvalidDataError(sql, parameters, error)
112
+ case ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:
113
+ throw new TransactionAbortedError(sql, parameters, error)
114
+ default:
115
+ throw new QueryError(sql, parameters, error)
116
+ }
117
+ }
118
+ }
119
+
120
+ private refuseExhaustedOrTerminated(): void {
121
+ // The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.
122
+ this.eventManager.memoryBudget?.check()
123
+ if (this.physicalConnection.terminated) {
124
+ throw new TerminatedConnectionError()
125
+ }
126
+ }
127
+
128
+ private async queryWithMemoryBudget<Row extends QueryResultRow>(
129
+ sql: string,
130
+ parameters: unknown[],
131
+ budget: RequestMemoryBudget,
132
+ ): Promise<Connection.Result<Row>> {
133
+ return await new Promise<Connection.Result<Row>>((resolve, reject) => {
134
+ let rows: Row[] | undefined
135
+ let failure: Error | undefined
136
+ let cleanup = () => {}
137
+ const stop = (error: Error) => {
138
+ failure = error
139
+ if (rows) {
140
+ rows.length = 0
77
141
  }
78
- this.eventManager.fire(EventManager.Event.queryError, { sql, parameters, meta }, error)
79
-
80
- switch ((error as any).code) {
81
- case ClientErrorCodes.NOT_NULL_VIOLATION:
82
- throw new NotNullViolationError(sql, parameters, error)
83
- case ClientErrorCodes.FOREIGN_KEY_VIOLATION:
84
- throw new ForeignKeyViolationError(sql, parameters, error)
85
- case ClientErrorCodes.UNIQUE_VIOLATION:
86
- throw new UniqueViolationError(sql, parameters, error)
87
- case ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
88
- throw new SerializationFailureError(sql, parameters, error)
89
- case ClientErrorCodes.INVALID_TEXT_REPRESENTATION:
90
- case ClientErrorCodes.DATETIME_FIELD_OVERFLOW:
91
- throw new InvalidDataError(sql, parameters, error)
92
- case ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:
93
- throw new TransactionAbortedError(sql, parameters, error)
94
- default:
95
- throw new QueryError(sql, parameters, error)
142
+ cleanup()
143
+ // A budget failure invalidates this connection; the enclosing pool scope disposes it.
144
+ this.physicalConnection.terminated = true
145
+ // Ending the socket alone leaves a statement still waiting for its first row running on the server.
146
+ // Cancelling is best effort and must not mask the budget error.
147
+ void cancelRunningStatement(this.pgClient).catch(() => {})
148
+ void this.pgClient.end().catch(reject)
149
+ reject(error)
150
+ }
151
+ const config = {
152
+ text: sql,
153
+ values: parameters,
154
+ callback: (error: Error | null, result?: QueryResult<Row>) => {
155
+ cleanup()
156
+ if (failure || error) {
157
+ reject(failure || error)
158
+ } else if (result) {
159
+ resolve(result)
160
+ } else {
161
+ reject(new Error('PostgreSQL query completed without a result'))
162
+ }
163
+ },
164
+ }
165
+ const query = new Query<Row>(config)
166
+ // A sibling query of the request may exhaust the budget while this one still waits for its first row.
167
+ cleanup = budget.onExceeded(stop)
168
+ query.on('row', (row, result) => {
169
+ rows = result?.rows
170
+ if (failure) {
171
+ if (rows) {
172
+ rows.length = 0
173
+ }
174
+ return
175
+ }
176
+ try {
177
+ budget.addDatabaseRow(row)
178
+ } catch (error) {
179
+ if (!failure) {
180
+ stop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))
181
+ }
96
182
  }
183
+ })
184
+ try {
185
+ this.pgClient.query(query)
186
+ } catch (error) {
187
+ cleanup()
188
+ reject(error)
97
189
  }
98
190
  })
99
191
  }
@@ -4,6 +4,7 @@ import { Connection } from './Connection.js'
4
4
  import { EventManager } from './EventManager.js'
5
5
  import { QueryHandler } from '@contember/queryable'
6
6
  import { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils/index.js'
7
+ import { RequestMemoryBudget } from './RequestMemoryBudget.js'
7
8
 
8
9
  class Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {
9
10
  constructor(
@@ -15,10 +16,18 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
15
16
  }
16
17
 
17
18
  public forSchema(schema: string): Client<ConnectionType> {
18
- const eventManager = new EventManager(this.eventManager.parent)
19
+ const eventManager = new EventManager(this.eventManager.parent, this.eventManager.memoryBudget, this.eventManager.chargesMemoryBudget)
19
20
  return new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)
20
21
  }
21
22
 
23
+ /**
24
+ * Binds the request memory budget: every query of the returned client is refused once the budget is exhausted.
25
+ * With `chargeRows`, the rows the client fetches are also accounted against the budget.
26
+ */
27
+ public withMemoryBudget(memoryBudget: RequestMemoryBudget, { chargeRows = true }: { chargeRows?: boolean } = {}): Client<ConnectionType> {
28
+ return new Client(this.connection, this.schema, this.queryMeta, new EventManager(this.eventManager, memoryBudget, chargeRows))
29
+ }
30
+
22
31
  async scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {
23
32
  return await this.connection.scope(
24
33
  connection =>
@@ -74,6 +83,7 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
74
83
  parameters: readonly any[] = [],
75
84
  meta: Record<string, any> = {},
76
85
  ): Promise<Connection.Result<Row>> {
86
+ this.eventManager.memoryBudget?.check()
77
87
  return this.connection.scope(
78
88
  connection => connection.query(sql, parameters, { ...this.queryMeta, ...meta }),
79
89
  { eventManager: this.eventManager },
@@ -47,8 +47,16 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
47
47
  callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
48
48
  options: { eventManager?: EventManager } = {},
49
49
  ): Promise<Result> {
50
- const acquired = await this.pool.acquire()
51
50
  const eventManager = new EventManager(options.eventManager ?? this.eventManager)
51
+ eventManager.memoryBudget?.check()
52
+ const acquired = await this.pool.acquire()
53
+ // A budget exhausted while waiting for the pool must not cost a healthy connection.
54
+ try {
55
+ eventManager.memoryBudget?.check()
56
+ } catch (e) {
57
+ this.pool.release(acquired)
58
+ throw e
59
+ }
52
60
  try {
53
61
  const connection = new AcquiredConnection(acquired.client, eventManager)
54
62
  const result = await callback(connection)
@@ -1,6 +1,11 @@
1
1
  import { Connection } from './Connection.js'
2
+ import { RequestMemoryBudget } from './RequestMemoryBudget.js'
2
3
 
3
4
  class EventManager {
5
+ /** Every query bound to a budget is refused once it is exhausted; only queries that also charge it account their rows. */
6
+ public readonly memoryBudget: RequestMemoryBudget | undefined
7
+ public readonly chargesMemoryBudget: boolean
8
+
4
9
  private readonly listeners = {
5
10
  [EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],
6
11
  [EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],
@@ -9,7 +14,12 @@ class EventManager {
9
14
 
10
15
  constructor(
11
16
  public readonly parent: EventManager | null = null,
12
- ) {}
17
+ memoryBudget: RequestMemoryBudget | null | undefined = parent?.memoryBudget,
18
+ chargesMemoryBudget: boolean = parent?.chargesMemoryBudget ?? false,
19
+ ) {
20
+ this.memoryBudget = memoryBudget ?? undefined
21
+ this.chargesMemoryBudget = this.memoryBudget !== undefined && chargesMemoryBudget
22
+ }
13
23
 
14
24
  on<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {
15
25
  ;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)
@@ -1,8 +1,23 @@
1
- import { Notification, QueryConfig, QueryResult, QueryResultRow } from 'pg'
1
+ import { Notification, QueryConfig, QueryResult, QueryResultRow, Submittable } from 'pg'
2
+
3
+ declare module 'pg' {
4
+ interface Client {
5
+ // Set by pg from the server's BackendKeyData message once connected; missing from @types/pg.
6
+ readonly processID: number | null
7
+ readonly secretKey: number | null
8
+ }
9
+ }
2
10
 
3
11
  export interface PgClient {
12
+ readonly host: string
13
+ readonly port: number
14
+ readonly processID: number | null
15
+ readonly secretKey: number | null
16
+
4
17
  connect(): Promise<void>
5
18
 
19
+ query<T extends Submittable>(query: T): T
20
+
6
21
  query<R extends QueryResultRow = any, I extends any[] = any[]>(
7
22
  queryTextOrConfig: string | QueryConfig<I>,
8
23
  values?: I,
@@ -0,0 +1,260 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ export interface RequestMemoryBudgetOptions {
4
+ warnBytes: number
5
+ maxBytes: number
6
+ }
7
+
8
+ const rowCompletionOverheadBytes = 256
9
+ const maximumRecursiveEstimateDepth = 64
10
+ const isBun = process.versions.bun !== undefined
11
+
12
+ export const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }: RequestMemoryBudgetOptions): string | undefined => {
13
+ if (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {
14
+ return 'warnBytes must be a positive safe integer'
15
+ }
16
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
17
+ return 'maxBytes must be a positive safe integer'
18
+ }
19
+ if (warnBytes > maxBytes) {
20
+ return 'warnBytes must not exceed maxBytes'
21
+ }
22
+ return undefined
23
+ }
24
+
25
+ export class RequestMemoryBudgetExceededError extends Error {
26
+ constructor() {
27
+ super('Request memory budget exceeded')
28
+ this.name = 'RequestMemoryBudgetExceededError'
29
+ }
30
+ }
31
+
32
+ export class RequestMemoryBudget {
33
+ private databaseBytes = 0
34
+ private hydrationBytes = 0
35
+ private peakBytes = 0
36
+ private databaseRows = 0
37
+ private largestDatabaseRowBytes = 0
38
+ private readonly databaseStrings = new StringMemoryEstimate()
39
+ private failure: RequestMemoryBudgetExceededError | undefined
40
+ // A plain set rather than an AbortSignal: every in-flight query of the request listens, and Node 20 warns above ten signal listeners.
41
+ private readonly exceededListeners = new Set<(failure: RequestMemoryBudgetExceededError) => void>()
42
+
43
+ constructor(private readonly options: RequestMemoryBudgetOptions) {
44
+ const optionsError = validateRequestMemoryBudgetOptions(options)
45
+ if (optionsError) {
46
+ throw new Error(`Invalid request memory budget: ${optionsError}`)
47
+ }
48
+ }
49
+
50
+ get exceeded(): boolean {
51
+ return this.failure !== undefined
52
+ }
53
+
54
+ check(): void {
55
+ if (this.failure) {
56
+ throw this.failure
57
+ }
58
+ }
59
+
60
+ /** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */
61
+ onExceeded(listener: (failure: RequestMemoryBudgetExceededError) => void): () => void {
62
+ if (this.failure) {
63
+ listener(this.failure)
64
+ return () => {}
65
+ }
66
+ this.exceededListeners.add(listener)
67
+ return () => this.exceededListeners.delete(listener)
68
+ }
69
+
70
+ addDatabaseRow(row: Record<string, unknown>): void {
71
+ this.check()
72
+ this.databaseRows++
73
+ let rowBytes = 40
74
+ for (const key in row) {
75
+ if (Object.prototype.hasOwnProperty.call(row, key)) {
76
+ rowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings)
77
+ }
78
+ }
79
+ this.databaseBytes += rowBytes
80
+ this.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes)
81
+ this.update()
82
+ }
83
+
84
+ addHydrationBytes(bytes: number): void {
85
+ this.check()
86
+ this.hydrationBytes += bytes
87
+ this.update()
88
+ }
89
+
90
+ snapshot() {
91
+ return {
92
+ estimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,
93
+ reservedCompletionBytes: this.getCompletionBytes(),
94
+ estimatedPeakBytes: this.peakBytes,
95
+ databaseRows: this.databaseRows,
96
+ databaseBytes: this.databaseBytes,
97
+ hydrationBytes: this.hydrationBytes,
98
+ warnBytes: this.options.warnBytes,
99
+ maxBytes: this.options.maxBytes,
100
+ warningThresholdExceeded: this.peakBytes > this.options.warnBytes,
101
+ maxBytesExceeded: this.peakBytes > this.options.maxBytes,
102
+ }
103
+ }
104
+
105
+ private getCompletionBytes(): number {
106
+ // GraphQL shares scalar strings with DB results; completion allocates structures and serialized text.
107
+ const projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2
108
+ + this.databaseStrings.serializedBytes + this.hydrationBytes
109
+ // Decoding a row and serializing the response happen in different phases.
110
+ // JSC includes pg's growing buffers in its heap account; V8 reports them as external memory.
111
+ const decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1)
112
+ return Math.max(projectedCompletionBytes, decodingBytes)
113
+ + this.databaseRows * rowCompletionOverheadBytes
114
+ }
115
+
116
+ private update(): void {
117
+ const estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes()
118
+ this.peakBytes = Math.max(this.peakBytes, estimatedBytes)
119
+ if (estimatedBytes > this.options.maxBytes) {
120
+ const failure = new RequestMemoryBudgetExceededError()
121
+ this.failure = failure
122
+ const listeners = [...this.exceededListeners]
123
+ this.exceededListeners.clear()
124
+ listeners.forEach(listener => listener(failure))
125
+ throw failure
126
+ }
127
+ }
128
+ }
129
+
130
+ function estimateValueBytes(value: unknown, strings: StringMemoryEstimate): number {
131
+ return estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0)
132
+ }
133
+
134
+ function estimateStructuredValueBytes(value: unknown, strings: StringMemoryEstimate, depth: number): number {
135
+ if (depth >= maximumRecursiveEstimateDepth) {
136
+ return estimateDeepValueBytes(value, strings)
137
+ }
138
+ if (Array.isArray(value)) {
139
+ let bytes = 32 + value.length * 8
140
+ for (let i = 0; i < value.length; i++) {
141
+ const item: unknown = value[i]
142
+ const scalarBytes = estimateScalarBytes(item, strings)
143
+ bytes += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1)
144
+ }
145
+ return bytes
146
+ }
147
+ let bytes = 32
148
+ if (value !== null && typeof value === 'object') {
149
+ for (const key in value) {
150
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
151
+ const item: unknown = Reflect.get(value, key)
152
+ const scalarBytes = estimateScalarBytes(item, strings)
153
+ strings.addPropertyName(key)
154
+ bytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1))
155
+ }
156
+ }
157
+ }
158
+ return bytes
159
+ }
160
+
161
+ function estimateDeepValueBytes(value: unknown, strings: StringMemoryEstimate): number {
162
+ const scalarBytes = estimateScalarBytes(value, strings)
163
+ if (scalarBytes !== undefined) {
164
+ return scalarBytes
165
+ }
166
+ let bytes = 0
167
+ const pending: Iterator<unknown>[] = [[value].values()]
168
+ while (pending.length > 0) {
169
+ const next = pending[pending.length - 1].next()
170
+ if (next.done) {
171
+ pending.pop()
172
+ continue
173
+ }
174
+ const current: unknown = next.value
175
+ const scalarBytes = estimateScalarBytes(current, strings)
176
+ if (scalarBytes !== undefined) {
177
+ bytes += scalarBytes
178
+ } else if (Array.isArray(current)) {
179
+ bytes += 32 + current.length * 8
180
+ pending.push(current.values())
181
+ } else if (current !== null && typeof current === 'object') {
182
+ bytes += 32
183
+ let hasNestedValues = false
184
+ for (const key in current) {
185
+ if (!Object.prototype.hasOwnProperty.call(current, key)) {
186
+ continue
187
+ }
188
+ strings.addPropertyName(key)
189
+ bytes += 16
190
+ const scalarBytes = estimateScalarBytes(Reflect.get(current, key), strings)
191
+ if (scalarBytes === undefined) {
192
+ hasNestedValues = true
193
+ } else {
194
+ bytes += scalarBytes
195
+ }
196
+ }
197
+ if (hasNestedValues) {
198
+ pending.push(nestedValues(current))
199
+ }
200
+ }
201
+ }
202
+ return bytes
203
+
204
+ function* nestedValues(object: object): Generator<unknown> {
205
+ for (const key in object) {
206
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
207
+ const value: unknown = Reflect.get(object, key)
208
+ if (value !== null && typeof value === 'object' && !(value instanceof Date) && !ArrayBuffer.isView(value)) {
209
+ yield value
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ function estimateScalarBytes(value: unknown, strings: StringMemoryEstimate): number | undefined {
217
+ if (typeof value === 'string') {
218
+ return 24 + strings.add(value)
219
+ }
220
+ if (value === null || typeof value !== 'object') {
221
+ return 8
222
+ }
223
+ if (value instanceof Date) {
224
+ return 40
225
+ }
226
+ if (ArrayBuffer.isView(value)) {
227
+ return 64 + value.byteLength
228
+ }
229
+ return undefined
230
+ }
231
+
232
+ class StringMemoryEstimate {
233
+ private codeUnits = 0
234
+ private storageBytes = 0
235
+ private nonAscii = false
236
+
237
+ get retainedBytes(): number {
238
+ return this.storageBytes
239
+ }
240
+
241
+ get serializedBytes(): number {
242
+ // One non-ASCII string can promote the entire serialized JSON string to two-byte storage.
243
+ return this.codeUnits * (this.nonAscii ? 2 : 1)
244
+ }
245
+
246
+ add(value: string): number {
247
+ // A native length comparison avoids a JavaScript character loop and RegExp.input, which can retain a request string.
248
+ const ascii = Buffer.byteLength(value) === value.length
249
+ this.nonAscii ||= !ascii
250
+ this.codeUnits += value.length
251
+ const bytes = ascii ? value.length : value.length * 2
252
+ this.storageBytes += bytes
253
+ return bytes
254
+ }
255
+
256
+ // Runtimes share property names between objects of one shape; only their serialized copies are new.
257
+ addPropertyName(key: string): void {
258
+ this.codeUnits += key.length
259
+ }
260
+ }
@@ -2,7 +2,7 @@ import { Connection } from './Connection.js'
2
2
  import { EventManager } from './EventManager.js'
3
3
  import { wrapIdentifier } from '../utils/index.js'
4
4
  import { Notification } from 'pg'
5
- import { CannotCommitError, DatabaseError } from './errors.js'
5
+ import { CannotCommitError, DatabaseError, TerminatedConnectionError } from './errors.js'
6
6
 
7
7
  export class Transaction implements Connection.TransactionLike {
8
8
  public get isClosed(): boolean {
@@ -55,7 +55,7 @@ export class Transaction implements Connection.TransactionLike {
55
55
  }
56
56
 
57
57
  async rollback(): Promise<void> {
58
- await this.close('ROLLBACK')
58
+ await this.close('ROLLBACK', new EventManager(this.eventManager, null))
59
59
  }
60
60
 
61
61
  async commit(): Promise<void> {
@@ -65,8 +65,11 @@ export class Transaction implements Connection.TransactionLike {
65
65
  }
66
66
  }
67
67
 
68
- private async close(command: string) {
69
- const result = await this.query(command)
68
+ private async close(command: string, eventManager = this.eventManager) {
69
+ if (this.isClosed) {
70
+ throw new Error('Transaction is already closed')
71
+ }
72
+ const result = await this.scope(connection => connection.query(command), { eventManager })
70
73
  this.state.close()
71
74
  return result
72
75
  }
@@ -124,15 +127,18 @@ class SavePoint implements Connection.TransactionLike {
124
127
  }
125
128
 
126
129
  async rollback(): Promise<void> {
127
- await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
130
+ await this.close(`ROLLBACK TO SAVEPOINT ${wrapIdentifier(this.savepointName)}`, new EventManager(this.eventManager, null))
128
131
  }
129
132
 
130
133
  async commit(): Promise<void> {
131
134
  await this.close(`RELEASE SAVEPOINT ${wrapIdentifier(this.savepointName)}`)
132
135
  }
133
136
 
134
- private async close(sql: string) {
135
- await this.query(sql)
137
+ private async close(sql: string, eventManager = this.eventManager) {
138
+ if (this.isClosed) {
139
+ throw new Error(`Savepoint ${this.savepointName} is already closed.`)
140
+ }
141
+ await this.scope(connection => connection.query(sql), { eventManager })
136
142
  this.state.close()
137
143
  }
138
144
  }
@@ -176,7 +182,14 @@ export const executeTransaction = async <Result>(
176
182
  return result
177
183
  } catch (e) {
178
184
  if (!transaction.isClosed) {
179
- await transaction.rollback()
185
+ try {
186
+ await transaction.rollback()
187
+ } catch (rollbackError) {
188
+ // PostgreSQL already rolled back the transaction of a terminated connection, whatever terminated it.
189
+ if (!(rollbackError instanceof TerminatedConnectionError)) {
190
+ throw rollbackError
191
+ }
192
+ }
180
193
  }
181
194
  throw e
182
195
  }
@@ -0,0 +1,36 @@
1
+ import { connect } from 'node:net'
2
+ import { PgClient } from './PgClient.js'
3
+
4
+ const CANCEL_REQUEST_CODE = 80877102
5
+ const CANCEL_REQUEST_TIMEOUT_MS = 5000
6
+
7
+ /**
8
+ * Asks the server to cancel the statement the client is running, with a protocol CancelRequest on a separate socket.
9
+ * Closing the client's own socket does not stop a statement that has not sent a row yet.
10
+ */
11
+ export const cancelRunningStatement = async ({ host, port, processID, secretKey }: PgClient): Promise<void> => {
12
+ if (processID === null || secretKey === null) {
13
+ return
14
+ }
15
+ const message = Buffer.alloc(16)
16
+ message.writeInt32BE(16, 0)
17
+ message.writeInt32BE(CANCEL_REQUEST_CODE, 4)
18
+ message.writeInt32BE(processID, 8)
19
+ message.writeInt32BE(secretKey, 12)
20
+
21
+ const socket = host.startsWith('/') ? connect(`${host}/.s.PGSQL.${port}`) : connect(port, host)
22
+ await new Promise<void>((resolve, reject) => {
23
+ socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS, () => {
24
+ socket.destroy(new Error(`PostgreSQL cancel request timed out after ${CANCEL_REQUEST_TIMEOUT_MS} ms`))
25
+ })
26
+ socket.once('error', reject)
27
+ socket.once('close', hadError => {
28
+ if (!hadError) {
29
+ resolve()
30
+ }
31
+ })
32
+ socket.once('connect', () => {
33
+ socket.end(message)
34
+ })
35
+ })
36
+ }