@contember/database 2.2.0-alpha.2 → 2.2.0-alpha.20
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.
- package/CLAUDE.md +23 -1
- package/dist/development/index.cjs +6 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +7 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/development/src/builders/WindowFunction.cjs +1 -1
- package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/development/src/builders/WindowFunction.js +1 -1
- package/dist/development/src/builders/WindowFunction.js.map +1 -1
- package/dist/development/src/client/AcquiredConnection.cjs +110 -32
- package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/development/src/client/AcquiredConnection.js +112 -34
- package/dist/development/src/client/AcquiredConnection.js.map +1 -1
- package/dist/development/src/client/Client.cjs +9 -1
- package/dist/development/src/client/Client.cjs.map +1 -1
- package/dist/development/src/client/Client.js +9 -1
- package/dist/development/src/client/Client.js.map +1 -1
- package/dist/development/src/client/Connection.cjs +48 -5
- package/dist/development/src/client/Connection.cjs.map +1 -1
- package/dist/development/src/client/Connection.js +48 -5
- package/dist/development/src/client/Connection.js.map +1 -1
- package/dist/development/src/client/EventManager.cjs +6 -2
- package/dist/development/src/client/EventManager.cjs.map +1 -1
- package/dist/development/src/client/EventManager.js +6 -2
- package/dist/development/src/client/EventManager.js.map +1 -1
- package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/development/src/client/RequestMemoryBudget.js +237 -0
- package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/development/src/client/Transaction.cjs +20 -8
- package/dist/development/src/client/Transaction.cjs.map +1 -1
- package/dist/development/src/client/Transaction.js +21 -9
- package/dist/development/src/client/Transaction.js.map +1 -1
- package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/development/src/client/cancelRunningStatement.js +32 -0
- package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/development/src/client/errors.cjs +12 -1
- package/dist/development/src/client/errors.cjs.map +1 -1
- package/dist/development/src/client/errors.js +12 -1
- package/dist/development/src/client/errors.js.map +1 -1
- package/dist/development/src/utils/pgClientFactory.cjs +4 -1
- package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/development/src/utils/pgClientFactory.js +4 -1
- package/dist/development/src/utils/pgClientFactory.js.map +1 -1
- package/dist/production/index.cjs +6 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +7 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/production/src/builders/WindowFunction.cjs +1 -1
- package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/production/src/builders/WindowFunction.js +1 -1
- package/dist/production/src/builders/WindowFunction.js.map +1 -1
- package/dist/production/src/client/AcquiredConnection.cjs +110 -32
- package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/production/src/client/AcquiredConnection.js +112 -34
- package/dist/production/src/client/AcquiredConnection.js.map +1 -1
- package/dist/production/src/client/Client.cjs +9 -1
- package/dist/production/src/client/Client.cjs.map +1 -1
- package/dist/production/src/client/Client.js +9 -1
- package/dist/production/src/client/Client.js.map +1 -1
- package/dist/production/src/client/Connection.cjs +48 -5
- package/dist/production/src/client/Connection.cjs.map +1 -1
- package/dist/production/src/client/Connection.js +48 -5
- package/dist/production/src/client/Connection.js.map +1 -1
- package/dist/production/src/client/EventManager.cjs +6 -2
- package/dist/production/src/client/EventManager.cjs.map +1 -1
- package/dist/production/src/client/EventManager.js +6 -2
- package/dist/production/src/client/EventManager.js.map +1 -1
- package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/production/src/client/RequestMemoryBudget.js +237 -0
- package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/production/src/client/Transaction.cjs +20 -8
- package/dist/production/src/client/Transaction.cjs.map +1 -1
- package/dist/production/src/client/Transaction.js +21 -9
- package/dist/production/src/client/Transaction.js.map +1 -1
- package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/production/src/client/cancelRunningStatement.js +32 -0
- package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/production/src/client/errors.cjs +12 -1
- package/dist/production/src/client/errors.cjs.map +1 -1
- package/dist/production/src/client/errors.js +12 -1
- package/dist/production/src/client/errors.js.map +1 -1
- package/dist/production/src/utils/pgClientFactory.cjs +4 -1
- package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/production/src/utils/pgClientFactory.js +4 -1
- package/dist/production/src/utils/pgClientFactory.js.map +1 -1
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +12 -3
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts +2 -0
- package/dist/tests/cases/unit/staleConnectionRetry.test.d.ts.map +1 -0
- package/dist/tests/src/tags.d.ts.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/Literal.d.ts.map +1 -1
- package/dist/types/builders/CaseStatement.d.ts.map +1 -1
- package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
- package/dist/types/builders/Compiler.d.ts.map +1 -1
- package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
- package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
- package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
- package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/types/builders/WindowFunction.d.ts +2 -1
- package/dist/types/builders/WindowFunction.d.ts.map +1 -1
- package/dist/types/builders/internal/Returning.d.ts.map +1 -1
- package/dist/types/builders/internal/Where.d.ts.map +1 -1
- package/dist/types/builders/internal/With.d.ts.map +1 -1
- package/dist/types/client/AcquiredConnection.d.ts +6 -1
- package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
- package/dist/types/client/Client.d.ts +8 -0
- package/dist/types/client/Client.d.ts.map +1 -1
- package/dist/types/client/Connection.d.ts +11 -2
- package/dist/types/client/Connection.d.ts.map +1 -1
- package/dist/types/client/EventManager.d.ts +5 -1
- package/dist/types/client/EventManager.d.ts.map +1 -1
- package/dist/types/client/PgClient.d.ts +13 -2
- package/dist/types/client/PgClient.d.ts.map +1 -1
- package/dist/types/client/Pool.d.ts.map +1 -1
- package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
- package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
- package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -1
- package/dist/types/client/Transaction.d.ts +3 -3
- package/dist/types/client/Transaction.d.ts.map +1 -1
- package/dist/types/client/cancelRunningStatement.d.ts +7 -0
- package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
- package/dist/types/client/errors.d.ts +5 -0
- package/dist/types/client/errors.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
- package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
- package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/types.d.ts +15 -0
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
- package/dist/types/utils/Mutex.d.ts.map +1 -1
- package/dist/types/utils/Semaphore.d.ts.map +1 -1
- package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
- package/dist/types/utils/listen.d.ts.map +1 -1
- package/dist/types/utils/pgClientFactory.d.ts +1 -2
- package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
- package/dist/types/utils/retryTransaction.d.ts.map +1 -1
- package/dist/types/utils/sql.d.ts.map +1 -1
- package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
- package/package.json +4 -3
- package/src/builders/LimitByGroupWrapper.ts +1 -1
- package/src/builders/WindowFunction.ts +3 -2
- package/src/client/AcquiredConnection.ts +131 -33
- package/src/client/Client.ts +11 -1
- package/src/client/Connection.ts +66 -3
- package/src/client/EventManager.ts +11 -1
- package/src/client/PgClient.ts +18 -2
- package/src/client/RequestMemoryBudget.ts +260 -0
- package/src/client/Transaction.ts +21 -8
- package/src/client/cancelRunningStatement.ts +36 -0
- package/src/client/errors.ts +15 -3
- package/src/index.ts +1 -0
- package/src/types.ts +15 -0
- package/src/utils/pgClientFactory.ts +5 -4
- package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
- package/tests/cases/unit/acquiredConnection.test.ts +209 -0
- package/tests/cases/unit/connection.test.ts +77 -1
- package/tests/cases/unit/createConnectionMockAlt.ts +35 -4
- package/tests/cases/unit/queryBuilder.test.ts +22 -1
- package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
- package/tests/cases/unit/staleConnectionRetry.test.ts +86 -0
|
@@ -2,6 +2,7 @@ import { QueryBuilder } from './QueryBuilder.js'
|
|
|
2
2
|
import { Literal } from '../Literal.js'
|
|
3
3
|
import { columnExpressionToLiteral } from './utils.js'
|
|
4
4
|
import { formatColumnIdentifier } from '../utils/index.js'
|
|
5
|
+
import type { SelectBuilder } from './SelectBuilder.js'
|
|
5
6
|
|
|
6
7
|
class WindowFunction<HasFunction extends boolean> implements QueryBuilder.Orderable<WindowFunction<HasFunction>> {
|
|
7
8
|
private constructor(
|
|
@@ -30,12 +31,12 @@ class WindowFunction<HasFunction extends boolean> implements QueryBuilder.Ordera
|
|
|
30
31
|
|
|
31
32
|
orderBy(
|
|
32
33
|
expression: QueryBuilder.ColumnIdentifier | Literal,
|
|
33
|
-
direction:
|
|
34
|
+
direction: SelectBuilder.OrderByDirection = 'asc',
|
|
34
35
|
): WindowFunction<HasFunction> {
|
|
35
36
|
const raw = expression instanceof Literal ? expression : new Literal(formatColumnIdentifier(expression))
|
|
36
37
|
return new WindowFunction(this.windowFunction, this.partitionByExpr, [
|
|
37
38
|
...this.orderByColumns,
|
|
38
|
-
raw.appendString(direction
|
|
39
|
+
raw.appendString(` ${direction}`),
|
|
39
40
|
])
|
|
40
41
|
}
|
|
41
42
|
|
|
@@ -1,19 +1,23 @@
|
|
|
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 {
|
|
7
|
+
CheckViolationError,
|
|
7
8
|
ForeignKeyViolationError,
|
|
8
9
|
InvalidDataError,
|
|
9
10
|
NotNullViolationError,
|
|
10
11
|
QueryError,
|
|
11
12
|
SerializationFailureError,
|
|
13
|
+
TerminatedConnectionError,
|
|
12
14
|
TransactionAbortedError,
|
|
13
15
|
UniqueViolationError,
|
|
14
16
|
} from './errors.js'
|
|
15
17
|
import { PgClient } from './PgClient.js'
|
|
16
|
-
import {
|
|
18
|
+
import { cancelRunningStatement } from './cancelRunningStatement.js'
|
|
19
|
+
import { Notification, Query, QueryResult, QueryResultRow } from 'pg'
|
|
20
|
+
import { RequestMemoryBudget, RequestMemoryBudgetExceededError } from './RequestMemoryBudget.js'
|
|
17
21
|
|
|
18
22
|
export class AcquiredConnection implements Connection.AcquiredConnectionLike {
|
|
19
23
|
private mutex = new Mutex()
|
|
@@ -21,6 +25,7 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
|
|
|
21
25
|
constructor(
|
|
22
26
|
private readonly pgClient: PgClient,
|
|
23
27
|
public readonly eventManager: EventManager,
|
|
28
|
+
private readonly physicalConnection = { terminated: false },
|
|
24
29
|
) {
|
|
25
30
|
}
|
|
26
31
|
|
|
@@ -29,7 +34,7 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
|
|
|
29
34
|
options: { eventManager?: EventManager } = {},
|
|
30
35
|
): Promise<Result> {
|
|
31
36
|
return await this.mutex.execute(async () => {
|
|
32
|
-
return await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager))
|
|
37
|
+
return await callback(new AcquiredConnection(this.pgClient, options.eventManager ?? this.eventManager, this.physicalConnection))
|
|
33
38
|
})
|
|
34
39
|
}
|
|
35
40
|
|
|
@@ -49,51 +54,144 @@ export class AcquiredConnection implements Connection.AcquiredConnectionLike {
|
|
|
49
54
|
parameters: any[] = [],
|
|
50
55
|
meta: Record<string, any> = {},
|
|
51
56
|
): Promise<Connection.Result<Row>> {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
57
|
+
// A refusal before queryStart fires no event, so cleanup on a terminated connection stays out of query error metrics.
|
|
58
|
+
this.refuseExhaustedOrTerminated()
|
|
59
|
+
|
|
60
|
+
const query: Connection.Query = { sql, parameters, meta }
|
|
55
61
|
|
|
56
|
-
|
|
62
|
+
try {
|
|
63
|
+
this.eventManager.fire(EventManager.Event.queryStart, query)
|
|
64
|
+
|
|
65
|
+
const result = await this.mutex.execute(async (): Promise<Connection.Result<Row>> => {
|
|
66
|
+
// A query queued behind the one that exhausted the budget reports the budget, not the terminated connection.
|
|
67
|
+
this.refuseExhaustedOrTerminated()
|
|
68
|
+
const memoryBudget = this.eventManager.memoryBudget
|
|
57
69
|
const startHrTime = process.hrtime.bigint()
|
|
58
70
|
|
|
59
|
-
|
|
71
|
+
const pgResult = memoryBudget && this.eventManager.chargesMemoryBudget
|
|
72
|
+
? await this.queryWithMemoryBudget<Row>(prepareSql(sql), parameters, memoryBudget)
|
|
73
|
+
: await this.pgClient.query(prepareSql(sql), parameters)
|
|
60
74
|
|
|
61
75
|
const endHrTime = process.hrtime.bigint()
|
|
62
76
|
const durationUs = Math.floor(Number(endHrTime - startHrTime) / 1000)
|
|
63
|
-
|
|
64
|
-
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
...pgResult,
|
|
65
80
|
timing: {
|
|
66
81
|
selfDuration: durationUs,
|
|
67
82
|
totalDuration: durationUs,
|
|
68
83
|
},
|
|
69
84
|
}
|
|
85
|
+
})
|
|
70
86
|
|
|
71
|
-
|
|
87
|
+
this.eventManager.fire(EventManager.Event.queryEnd, query, result)
|
|
72
88
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
89
|
+
return result
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (!(error instanceof Error)) {
|
|
92
|
+
throw error
|
|
93
|
+
}
|
|
94
|
+
this.eventManager.fire(EventManager.Event.queryError, query, error)
|
|
95
|
+
|
|
96
|
+
// neither a mutex deadlock nor a budget refusal is a postgres failure, keep them untranslated
|
|
97
|
+
if (error instanceof MutexDeadlockError || error instanceof RequestMemoryBudgetExceededError || error instanceof TerminatedConnectionError) {
|
|
98
|
+
throw error
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
switch ((error as any).code) {
|
|
102
|
+
case ClientErrorCodes.NOT_NULL_VIOLATION:
|
|
103
|
+
throw new NotNullViolationError(sql, parameters, error)
|
|
104
|
+
case ClientErrorCodes.FOREIGN_KEY_VIOLATION:
|
|
105
|
+
throw new ForeignKeyViolationError(sql, parameters, error)
|
|
106
|
+
case ClientErrorCodes.UNIQUE_VIOLATION:
|
|
107
|
+
throw new UniqueViolationError(sql, parameters, error)
|
|
108
|
+
case ClientErrorCodes.CHECK_VIOLATION:
|
|
109
|
+
throw new CheckViolationError(sql, parameters, error)
|
|
110
|
+
// both abort the transaction and succeed on a retry, so `retryTransaction` handles them alike
|
|
111
|
+
case ClientErrorCodes.T_R_SERIALIZATION_FAILURE:
|
|
112
|
+
case ClientErrorCodes.T_R_DEADLOCK_DETECTED:
|
|
113
|
+
throw new SerializationFailureError(sql, parameters, error)
|
|
114
|
+
case ClientErrorCodes.INVALID_TEXT_REPRESENTATION:
|
|
115
|
+
case ClientErrorCodes.INVALID_DATETIME_FORMAT:
|
|
116
|
+
case ClientErrorCodes.DATETIME_FIELD_OVERFLOW:
|
|
117
|
+
throw new InvalidDataError(sql, parameters, error)
|
|
118
|
+
case ClientErrorCodes.IN_FAILED_SQL_TRANSACTION:
|
|
119
|
+
throw new TransactionAbortedError(sql, parameters, error)
|
|
120
|
+
default:
|
|
121
|
+
throw new QueryError(sql, parameters, error)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private refuseExhaustedOrTerminated(): void {
|
|
127
|
+
// The budget goes first: a connection the budget terminated reports the budget to every query still bound to it.
|
|
128
|
+
this.eventManager.memoryBudget?.check()
|
|
129
|
+
if (this.physicalConnection.terminated) {
|
|
130
|
+
throw new TerminatedConnectionError()
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private async queryWithMemoryBudget<Row extends QueryResultRow>(
|
|
135
|
+
sql: string,
|
|
136
|
+
parameters: unknown[],
|
|
137
|
+
budget: RequestMemoryBudget,
|
|
138
|
+
): Promise<Connection.Result<Row>> {
|
|
139
|
+
return await new Promise<Connection.Result<Row>>((resolve, reject) => {
|
|
140
|
+
let rows: Row[] | undefined
|
|
141
|
+
let failure: Error | undefined
|
|
142
|
+
let cleanup = () => {}
|
|
143
|
+
const stop = (error: Error) => {
|
|
144
|
+
failure = error
|
|
145
|
+
if (rows) {
|
|
146
|
+
rows.length = 0
|
|
77
147
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
148
|
+
cleanup()
|
|
149
|
+
// A budget failure invalidates this connection; the enclosing pool scope disposes it.
|
|
150
|
+
this.physicalConnection.terminated = true
|
|
151
|
+
// Ending the socket alone leaves a statement still waiting for its first row running on the server.
|
|
152
|
+
// Cancelling is best effort and must not mask the budget error.
|
|
153
|
+
void cancelRunningStatement(this.pgClient).catch(() => {})
|
|
154
|
+
void this.pgClient.end().catch(reject)
|
|
155
|
+
reject(error)
|
|
156
|
+
}
|
|
157
|
+
const config = {
|
|
158
|
+
text: sql,
|
|
159
|
+
values: parameters,
|
|
160
|
+
callback: (error: Error | null, result?: QueryResult<Row>) => {
|
|
161
|
+
cleanup()
|
|
162
|
+
if (failure || error) {
|
|
163
|
+
reject(failure || error)
|
|
164
|
+
} else if (result) {
|
|
165
|
+
resolve(result)
|
|
166
|
+
} else {
|
|
167
|
+
reject(new Error('PostgreSQL query completed without a result'))
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
const query = new Query<Row>(config)
|
|
172
|
+
// A sibling query of the request may exhaust the budget while this one still waits for its first row.
|
|
173
|
+
cleanup = budget.onExceeded(stop)
|
|
174
|
+
query.on('row', (row, result) => {
|
|
175
|
+
rows = result?.rows
|
|
176
|
+
if (failure) {
|
|
177
|
+
if (rows) {
|
|
178
|
+
rows.length = 0
|
|
179
|
+
}
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
budget.addDatabaseRow(row)
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (!failure) {
|
|
186
|
+
stop(error instanceof Error ? error : new Error('Failed to account for database row', { cause: error }))
|
|
187
|
+
}
|
|
96
188
|
}
|
|
189
|
+
})
|
|
190
|
+
try {
|
|
191
|
+
this.pgClient.query(query)
|
|
192
|
+
} catch (error) {
|
|
193
|
+
cleanup()
|
|
194
|
+
reject(error)
|
|
97
195
|
}
|
|
98
196
|
})
|
|
99
197
|
}
|
package/src/client/Client.ts
CHANGED
|
@@ -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 },
|
package/src/client/Connection.ts
CHANGED
|
@@ -6,19 +6,23 @@ import { DatabaseConfig } from '../types.js'
|
|
|
6
6
|
import { AcquiredConnection } from './AcquiredConnection.js'
|
|
7
7
|
import { ScopeLimitedConnection } from './ScopeLimitedConnection.js'
|
|
8
8
|
import { Notification } from 'pg'
|
|
9
|
+
import { DatabaseError } from './errors.js'
|
|
10
|
+
import { ClientErrorCodes } from './errorCodes.js'
|
|
9
11
|
|
|
10
12
|
class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
|
|
11
13
|
constructor(
|
|
12
14
|
private readonly pool: Pool,
|
|
13
15
|
public readonly eventManager: EventManager = new EventManager(null),
|
|
16
|
+
private readonly options: Connection.Options = {},
|
|
14
17
|
) {
|
|
15
18
|
}
|
|
16
19
|
|
|
17
20
|
public static create(
|
|
18
21
|
{ pool = {}, ...config }: DatabaseConfig & { pool?: Omit<PoolConfig, 'logError'> },
|
|
19
22
|
logError: (error: Error) => void,
|
|
23
|
+
options: Connection.Options = {},
|
|
20
24
|
): Connection {
|
|
21
|
-
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }))
|
|
25
|
+
return new Connection(new Pool(createPgClientFactory(config), { ...pool, logError }), new EventManager(null), options)
|
|
22
26
|
}
|
|
23
27
|
|
|
24
28
|
public static createSingle(
|
|
@@ -47,17 +51,57 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
47
51
|
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
48
52
|
options: { eventManager?: EventManager } = {},
|
|
49
53
|
): Promise<Result> {
|
|
50
|
-
const acquired = await this.pool.acquire()
|
|
51
54
|
const eventManager = new EventManager(options.eventManager ?? this.eventManager)
|
|
55
|
+
eventManager.memoryBudget?.check()
|
|
56
|
+
// Each retry disposes the stale connection it got, so the loop ends once the idle connections are used up.
|
|
57
|
+
while (true) {
|
|
58
|
+
const attempt = await this.scopeOnce(callback, eventManager)
|
|
59
|
+
if (!attempt.stale) {
|
|
60
|
+
return attempt.result
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private async scopeOnce<Result>(
|
|
66
|
+
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
67
|
+
eventManager: EventManager,
|
|
68
|
+
): Promise<{ stale: false; result: Result } | { stale: true }> {
|
|
69
|
+
const acquired = await this.pool.acquire()
|
|
70
|
+
// A budget exhausted while waiting for the pool must not cost a healthy connection.
|
|
71
|
+
try {
|
|
72
|
+
eventManager.memoryBudget?.check()
|
|
73
|
+
} catch (e) {
|
|
74
|
+
this.pool.release(acquired)
|
|
75
|
+
throw e
|
|
76
|
+
}
|
|
77
|
+
const reused = acquired.uses > 1
|
|
78
|
+
// pg emits `error` only for a connection lost unexpectedly, not for its own end(), e.g. after an exhausted budget.
|
|
79
|
+
let lost = false
|
|
80
|
+
let answered = false
|
|
81
|
+
const onError = () => {
|
|
82
|
+
lost = true
|
|
83
|
+
}
|
|
84
|
+
const onAnswer = () => {
|
|
85
|
+
answered = true
|
|
86
|
+
}
|
|
87
|
+
acquired.client.on('error', onError)
|
|
88
|
+
eventManager.on(EventManager.Event.queryEnd, onAnswer)
|
|
52
89
|
try {
|
|
53
90
|
const connection = new AcquiredConnection(acquired.client, eventManager)
|
|
54
91
|
const result = await callback(connection)
|
|
55
92
|
this.pool.release(acquired)
|
|
56
93
|
|
|
57
|
-
return result
|
|
94
|
+
return { stale: false, result }
|
|
58
95
|
} catch (e) {
|
|
59
96
|
this.pool.dispose(acquired)
|
|
97
|
+
// The server closed a pooled connection before answering anything, e.g. a pooler or replica restart.
|
|
98
|
+
if (this.options.retryStaleConnection && reused && !answered && (lost || isConnectionLoss(e))) {
|
|
99
|
+
return { stale: true }
|
|
100
|
+
}
|
|
60
101
|
throw e
|
|
102
|
+
} finally {
|
|
103
|
+
acquired.client.off('error', onError)
|
|
104
|
+
eventManager.removeListener(EventManager.Event.queryEnd, onAnswer)
|
|
61
105
|
}
|
|
62
106
|
}
|
|
63
107
|
|
|
@@ -93,7 +137,26 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
93
137
|
}
|
|
94
138
|
}
|
|
95
139
|
|
|
140
|
+
const connectionLossCodes = new Set<string>([
|
|
141
|
+
ClientErrorCodes.CONNECTION_EXCEPTION,
|
|
142
|
+
ClientErrorCodes.CONNECTION_DOES_NOT_EXIST,
|
|
143
|
+
ClientErrorCodes.CONNECTION_FAILURE,
|
|
144
|
+
ClientErrorCodes.ADMIN_SHUTDOWN,
|
|
145
|
+
ClientErrorCodes.CRASH_SHUTDOWN,
|
|
146
|
+
])
|
|
147
|
+
|
|
148
|
+
const isConnectionLoss = (error: unknown): boolean =>
|
|
149
|
+
error instanceof DatabaseError && error.code !== undefined && connectionLossCodes.has(error.code)
|
|
150
|
+
|
|
96
151
|
namespace Connection {
|
|
152
|
+
export interface Options {
|
|
153
|
+
/**
|
|
154
|
+
* Runs a scope again on another connection when a connection taken from the pool turns out to be closed by
|
|
155
|
+
* the server before it answered anything. Only for connections whose scopes may run twice, such as a read replica.
|
|
156
|
+
*/
|
|
157
|
+
retryStaleConnection?: boolean
|
|
158
|
+
}
|
|
159
|
+
|
|
97
160
|
export interface Queryable {
|
|
98
161
|
readonly eventManager: EventManager
|
|
99
162
|
|
|
@@ -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)
|
package/src/client/PgClient.ts
CHANGED
|
@@ -1,7 +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 {
|
|
4
|
-
|
|
12
|
+
readonly host: string
|
|
13
|
+
readonly port: number
|
|
14
|
+
readonly processID: number | null
|
|
15
|
+
readonly secretKey: number | null
|
|
16
|
+
|
|
17
|
+
// pg resolves with the client, and newer @types/pg types it so; callers only await it.
|
|
18
|
+
connect(): Promise<unknown>
|
|
19
|
+
|
|
20
|
+
query<T extends Submittable>(query: T): T
|
|
5
21
|
|
|
6
22
|
query<R extends QueryResultRow = any, I extends any[] = any[]>(
|
|
7
23
|
queryTextOrConfig: string | QueryConfig<I>,
|