@contember/database 1.2.1 → 1.3.0-alpha.13
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/dist/src/builders/Compiler.d.ts.map +1 -1
- package/dist/src/builders/Compiler.js +8 -16
- package/dist/src/builders/Compiler.js.map +1 -1
- package/dist/src/builders/InsertBuilder.d.ts +2 -2
- package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/src/builders/InsertBuilder.js +7 -4
- package/dist/src/builders/InsertBuilder.js.map +1 -1
- package/dist/src/builders/LockType.d.ts +8 -4
- package/dist/src/builders/LockType.d.ts.map +1 -1
- package/dist/src/builders/LockType.js +10 -5
- package/dist/src/builders/LockType.js.map +1 -1
- package/dist/src/builders/QueryBuilder.d.ts +4 -2
- package/dist/src/builders/QueryBuilder.d.ts.map +1 -1
- package/dist/src/builders/SelectBuilder.d.ts +6 -3
- package/dist/src/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/src/builders/SelectBuilder.js +2 -2
- package/dist/src/builders/SelectBuilder.js.map +1 -1
- package/dist/src/builders/UpdateBuilder.d.ts +3 -1
- package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/src/builders/UpdateBuilder.js +4 -0
- package/dist/src/builders/UpdateBuilder.js.map +1 -1
- package/dist/src/builders/internal/Where.js +1 -1
- package/dist/src/builders/internal/Where.js.map +1 -1
- package/dist/src/builders/utils.d.ts.map +1 -1
- package/dist/src/builders/utils.js +6 -9
- package/dist/src/builders/utils.js.map +1 -1
- package/dist/src/client/AcquiredConnection.d.ts +4 -2
- package/dist/src/client/AcquiredConnection.d.ts.map +1 -1
- package/dist/src/client/AcquiredConnection.js +4 -0
- package/dist/src/client/AcquiredConnection.js.map +1 -1
- package/dist/src/client/Client.d.ts +1 -1
- package/dist/src/client/Client.d.ts.map +1 -1
- package/dist/src/client/Client.js.map +1 -1
- package/dist/src/client/Connection.d.ts +9 -5
- package/dist/src/client/Connection.d.ts.map +1 -1
- package/dist/src/client/Connection.js.map +1 -1
- package/dist/src/client/PgClient.d.ts +6 -4
- package/dist/src/client/PgClient.d.ts.map +1 -1
- package/dist/src/client/Pool.d.ts +1 -0
- package/dist/src/client/Pool.d.ts.map +1 -1
- package/dist/src/client/Pool.js +23 -21
- package/dist/src/client/Pool.js.map +1 -1
- package/dist/src/client/Transaction.d.ts +8 -2
- package/dist/src/client/Transaction.d.ts.map +1 -1
- package/dist/src/client/Transaction.js +2 -0
- package/dist/src/client/Transaction.js.map +1 -1
- package/dist/src/client/errors.d.ts +1 -0
- package/dist/src/client/errors.d.ts.map +1 -1
- package/dist/src/client/errors.js +1 -0
- package/dist/src/client/errors.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +3 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/types.d.ts +2 -2
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/utils/ConstraintHelper.d.ts +1 -0
- package/dist/src/utils/ConstraintHelper.d.ts.map +1 -1
- package/dist/src/utils/ConstraintHelper.js +3 -0
- package/dist/src/utils/ConstraintHelper.js.map +1 -1
- package/dist/src/utils/index.d.ts +1 -0
- package/dist/src/utils/index.d.ts.map +1 -1
- package/dist/src/utils/index.js +1 -0
- package/dist/src/utils/index.js.map +1 -1
- package/dist/src/utils/listen.d.ts +32 -0
- package/dist/src/utils/listen.d.ts.map +1 -0
- package/dist/src/utils/listen.js +126 -0
- package/dist/src/utils/listen.js.map +1 -0
- package/dist/tests/cases/unit/pool.test.js +12 -12
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +8 -4
- package/src/builders/Compiler.ts +13 -17
- package/src/builders/InsertBuilder.ts +8 -5
- package/src/builders/LockType.ts +9 -4
- package/src/builders/QueryBuilder.ts +2 -1
- package/src/builders/SelectBuilder.ts +4 -4
- package/src/builders/UpdateBuilder.ts +4 -1
- package/src/builders/internal/Where.ts +1 -1
- package/src/builders/utils.ts +6 -9
- package/src/client/AcquiredConnection.ts +8 -2
- package/src/client/Client.ts +3 -3
- package/src/client/Connection.ts +9 -5
- package/src/client/PgClient.ts +8 -3
- package/src/client/Pool.ts +34 -20
- package/src/client/Transaction.ts +9 -3
- package/src/client/errors.ts +2 -0
- package/src/index.ts +2 -0
- package/src/tsconfig.json +1 -3
- package/src/types.ts +2 -2
- package/src/utils/ConstraintHelper.ts +4 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/listen.ts +140 -0
- package/tests/cases/unit/pool.test.ts +12 -12
|
@@ -13,8 +13,9 @@ import {
|
|
|
13
13
|
UniqueViolationError,
|
|
14
14
|
} from './errors'
|
|
15
15
|
import { PgClient } from './PgClient'
|
|
16
|
+
import { Notification } from 'pg'
|
|
16
17
|
|
|
17
|
-
export class AcquiredConnection implements Connection.
|
|
18
|
+
export class AcquiredConnection implements Connection.AcquiredConnectionLike {
|
|
18
19
|
private mutex = new Mutex()
|
|
19
20
|
|
|
20
21
|
constructor(
|
|
@@ -24,7 +25,7 @@ export class AcquiredConnection implements Connection.ConnectionLike {
|
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
async scope<Result>(
|
|
27
|
-
callback: (connection: Connection.
|
|
28
|
+
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
28
29
|
options: { eventManager?: EventManager } = {},
|
|
29
30
|
): Promise<Result> {
|
|
30
31
|
return await this.mutex.execute(async () => {
|
|
@@ -96,6 +97,11 @@ export class AcquiredConnection implements Connection.ConnectionLike {
|
|
|
96
97
|
}
|
|
97
98
|
})
|
|
98
99
|
}
|
|
100
|
+
|
|
101
|
+
on(event: 'end' | 'notification' | 'error', cb: (() => void) | ((notification: Notification) => void) | ((error: any) => void)) {
|
|
102
|
+
this.pgClient.on(event as any, cb)
|
|
103
|
+
return () => this.pgClient.off(event as any, cb)
|
|
104
|
+
}
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
function prepareSql(sql: string) {
|
package/src/client/Client.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { DatabaseQueryable } from '../queryable'
|
|
|
3
3
|
import { Connection } from './Connection'
|
|
4
4
|
import { EventManager } from './EventManager'
|
|
5
5
|
import { QueryHandler } from '@contember/queryable'
|
|
6
|
-
import { withDatabaseAdvisoryLock } from '../utils'
|
|
6
|
+
import { withDatabaseAdvisoryLock, wrapIdentifier } from '../utils'
|
|
7
7
|
|
|
8
8
|
class Client<ConnectionType extends Connection.ConnectionLike = Connection.ConnectionLike> implements Connection.Queryable {
|
|
9
9
|
constructor(
|
|
@@ -19,11 +19,11 @@ class Client<ConnectionType extends Connection.ConnectionLike = Connection.Conne
|
|
|
19
19
|
return new Client<ConnectionType>(this.connection, schema, this.queryMeta, eventManager)
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
async scope<T>(callback: (wrapper: Client<Connection.
|
|
22
|
+
async scope<T>(callback: (wrapper: Client<ConnectionType & Connection.AcquiredConnectionLike>) => Promise<T> | T): Promise<T> {
|
|
23
23
|
return await this.connection.scope(
|
|
24
24
|
connection => callback(
|
|
25
25
|
new Client(
|
|
26
|
-
connection,
|
|
26
|
+
connection as ConnectionType & Connection.AcquiredConnectionLike,
|
|
27
27
|
this.schema,
|
|
28
28
|
this.queryMeta,
|
|
29
29
|
new EventManager(connection.eventManager),
|
package/src/client/Connection.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { Pool, PoolConfig, PoolStatus } from './Pool'
|
|
|
4
4
|
import { createPgClientFactory } from '../utils'
|
|
5
5
|
import { DatabaseConfig } from '../types'
|
|
6
6
|
import { AcquiredConnection } from './AcquiredConnection'
|
|
7
|
+
import { Notification } from 'pg'
|
|
7
8
|
|
|
8
9
|
class Connection implements Connection.ConnectionLike, Connection.ClientFactory, Connection.PoolStatusProvider {
|
|
9
10
|
constructor(
|
|
@@ -31,7 +32,7 @@ class Connection implements Connection.ConnectionLike, Connection.ClientFactory,
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
async scope<Result>(
|
|
34
|
-
callback: (connection: Connection.
|
|
35
|
+
callback: (connection: Connection.AcquiredConnectionLike) => Promise<Result> | Result,
|
|
35
36
|
options: { eventManager?: EventManager } = {},
|
|
36
37
|
): Promise<Result> {
|
|
37
38
|
const acquired = await this.pool.acquire()
|
|
@@ -103,14 +104,17 @@ namespace Connection {
|
|
|
103
104
|
& Connection.ClientFactory
|
|
104
105
|
& Connection.PoolStatusProvider
|
|
105
106
|
|
|
106
|
-
export interface
|
|
107
|
+
export interface ConnectionLike<T = {}> extends Transactional, Queryable {
|
|
107
108
|
scope<Result>(
|
|
108
|
-
callback: (connection:
|
|
109
|
+
callback: (connection: T & AcquiredConnectionLike) => Promise<Result> | Result,
|
|
109
110
|
options?: { eventManager?: EventManager },
|
|
110
111
|
): Promise<Result>
|
|
111
112
|
}
|
|
112
113
|
|
|
113
|
-
export interface
|
|
114
|
+
export interface AcquiredConnectionLike<T = {}> extends ConnectionLike<T> {
|
|
115
|
+
on(event: 'notification', listener: (message: Notification) => void): () => void
|
|
116
|
+
on(event: 'end', listener: () => void): () => void
|
|
117
|
+
on(event: 'error', listener: (error: any) => void): () => void
|
|
114
118
|
}
|
|
115
119
|
|
|
116
120
|
export interface ClientFactory {
|
|
@@ -121,7 +125,7 @@ namespace Connection {
|
|
|
121
125
|
getPoolStatus(): PoolStatus | undefined
|
|
122
126
|
}
|
|
123
127
|
|
|
124
|
-
export interface TransactionLike extends
|
|
128
|
+
export interface TransactionLike extends AcquiredConnectionLike<TransactionLike> {
|
|
125
129
|
readonly isClosed: boolean
|
|
126
130
|
|
|
127
131
|
rollback(): Promise<void>
|
package/src/client/PgClient.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { QueryConfig, QueryResult, QueryResultRow } from 'pg'
|
|
2
|
-
import EventEmitter from 'node:events'
|
|
1
|
+
import { Notification, QueryConfig, QueryResult, QueryResultRow } from 'pg'
|
|
3
2
|
|
|
4
|
-
export interface PgClient
|
|
3
|
+
export interface PgClient {
|
|
5
4
|
connect(): Promise<void>
|
|
6
5
|
|
|
7
6
|
query<R extends QueryResultRow = any, I extends any[] = any[]>(
|
|
@@ -10,4 +9,10 @@ export interface PgClient extends EventEmitter {
|
|
|
10
9
|
): Promise<QueryResult<R>>
|
|
11
10
|
|
|
12
11
|
end(): Promise<void>
|
|
12
|
+
|
|
13
|
+
on(event: 'notification', listener: (message: Notification) => void): this
|
|
14
|
+
on(event: 'error', listener: (err: Error) => void): this
|
|
15
|
+
on(event: 'end', listener: () => void): this
|
|
16
|
+
|
|
17
|
+
off(eventName: string | symbol, listener: (...args: any[]) => void): this
|
|
13
18
|
}
|
package/src/client/Pool.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ImplementationException } from '../exceptions'
|
|
2
2
|
import { ClientErrorCodes } from './errorCodes'
|
|
3
|
-
import EventEmitter from 'node:events'
|
|
3
|
+
import { EventEmitter } from 'node:events'
|
|
4
4
|
import { ClientError, DatabaseError } from './errors'
|
|
5
5
|
import { PgClientFactory } from '../utils'
|
|
6
6
|
import { PgClient } from './PgClient'
|
|
@@ -52,7 +52,8 @@ export interface PoolStatus {
|
|
|
52
52
|
stats: PoolStats
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
export const poolStatsDescription =
|
|
55
|
+
export const poolStatsDescription = {
|
|
56
|
+
connection_started_count: 'Total number of connection attempts when started.',
|
|
56
57
|
connection_established_count: 'Total number of established connections.',
|
|
57
58
|
connection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',
|
|
58
59
|
connection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',
|
|
@@ -135,6 +136,7 @@ class Pool {
|
|
|
135
136
|
private poolConfig: PoolConfigInternal
|
|
136
137
|
|
|
137
138
|
private poolStats: PoolStats = {
|
|
139
|
+
connection_started_count: 0,
|
|
138
140
|
connection_established_count: 0,
|
|
139
141
|
connection_recoverable_error_count: 0,
|
|
140
142
|
connection_error_count: 0,
|
|
@@ -303,6 +305,7 @@ class Pool {
|
|
|
303
305
|
this.log('Creating a new connection')
|
|
304
306
|
const client = this.clientFactory()
|
|
305
307
|
const poolConnection = new PoolConnection(client)
|
|
308
|
+
|
|
306
309
|
client.on('error', e => {
|
|
307
310
|
this.log('Client error on idle connection has occurred: ' + e.message)
|
|
308
311
|
this.poolConfig.logError(new ClientError(e, 'runtime error'))
|
|
@@ -313,24 +316,30 @@ class Pool {
|
|
|
313
316
|
this.disposeConnection(poolConnection)
|
|
314
317
|
}
|
|
315
318
|
})
|
|
319
|
+
|
|
316
320
|
try {
|
|
317
321
|
this.connectingCount++
|
|
318
322
|
this.remainingRateLimit--
|
|
323
|
+
this.poolStats.connection_started_count++
|
|
324
|
+
|
|
319
325
|
await client.connect()
|
|
326
|
+
|
|
320
327
|
this.poolStats.connection_established_count++
|
|
321
|
-
this.log('Connection established')
|
|
322
328
|
this.connectingCount--
|
|
329
|
+
|
|
330
|
+
this.log('Connection established')
|
|
331
|
+
|
|
323
332
|
if (this.ended) {
|
|
324
|
-
|
|
325
|
-
return
|
|
333
|
+
return this.disposeConnection(poolConnection)
|
|
326
334
|
}
|
|
335
|
+
|
|
336
|
+
this.handleAvailableConnection(poolConnection)
|
|
337
|
+
this.maybeCreateNew()
|
|
338
|
+
|
|
327
339
|
} catch (e: any) {
|
|
328
340
|
this.log('Connection error occurred: ' + e.message)
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
} catch (e2: unknown) {
|
|
332
|
-
this.poolConfig.logError(new ClientError(e2, 'disposal error'))
|
|
333
|
-
}
|
|
341
|
+
this.disposeConnection(poolConnection)
|
|
342
|
+
|
|
334
343
|
if (
|
|
335
344
|
e.code === ClientErrorCodes.TOO_MANY_CONNECTIONS
|
|
336
345
|
|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting
|
|
@@ -345,6 +354,7 @@ class Pool {
|
|
|
345
354
|
this.log('Retrying')
|
|
346
355
|
this.maybeCreateNew()
|
|
347
356
|
}, this.poolConfig.reconnectIntervalMs)
|
|
357
|
+
|
|
348
358
|
} else {
|
|
349
359
|
this.poolStats.connection_error_count++
|
|
350
360
|
this.connectingCount--
|
|
@@ -360,7 +370,7 @@ class Pool {
|
|
|
360
370
|
this.poolConfig.logError(clientError)
|
|
361
371
|
}
|
|
362
372
|
}
|
|
363
|
-
|
|
373
|
+
|
|
364
374
|
} finally {
|
|
365
375
|
setTimeout(() => {
|
|
366
376
|
if (this.remainingRateLimit === 0) {
|
|
@@ -370,8 +380,6 @@ class Pool {
|
|
|
370
380
|
this.maybeCreateNew()
|
|
371
381
|
}, this.poolConfig.rateLimitPeriodMs)
|
|
372
382
|
}
|
|
373
|
-
this.handleAvailableConnection(poolConnection)
|
|
374
|
-
this.maybeCreateNew()
|
|
375
383
|
}
|
|
376
384
|
|
|
377
385
|
private createPendingItem(): Promise<PoolConnection> {
|
|
@@ -464,15 +472,21 @@ class Pool {
|
|
|
464
472
|
}
|
|
465
473
|
|
|
466
474
|
private async disposeConnection(connection: PoolConnection) {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
475
|
+
if (connection.disposed) {
|
|
476
|
+
throw new PoolError('Connection is already disposed')
|
|
477
|
+
}
|
|
478
|
+
connection.disposed = true
|
|
479
|
+
const doEnd = async () => {
|
|
480
|
+
try {
|
|
481
|
+
await connection.client.end()
|
|
482
|
+
} catch (e: any) {
|
|
483
|
+
this.poolConfig.logError(new ClientError(e, 'disposal error'))
|
|
470
484
|
}
|
|
471
|
-
connection.disposed = true
|
|
472
|
-
await connection.client.end()
|
|
473
|
-
} catch (e: any) {
|
|
474
|
-
this.poolConfig.logError(new ClientError(e, 'disposal error'))
|
|
475
485
|
}
|
|
486
|
+
await Promise.race([
|
|
487
|
+
doEnd(),
|
|
488
|
+
new Promise(resolve => setTimeout(resolve, 5_000)),
|
|
489
|
+
])
|
|
476
490
|
}
|
|
477
491
|
|
|
478
492
|
private log(message: string) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Connection } from './Connection'
|
|
2
2
|
import { EventManager } from './EventManager'
|
|
3
3
|
import { wrapIdentifier } from '../utils'
|
|
4
|
+
import { Notification } from 'pg'
|
|
4
5
|
|
|
5
6
|
export class Transaction implements Connection.TransactionLike {
|
|
6
7
|
public get isClosed(): boolean {
|
|
@@ -8,7 +9,7 @@ export class Transaction implements Connection.TransactionLike {
|
|
|
8
9
|
}
|
|
9
10
|
|
|
10
11
|
constructor(
|
|
11
|
-
private readonly connection: Connection.
|
|
12
|
+
private readonly connection: Connection.AcquiredConnectionLike,
|
|
12
13
|
private readonly savepointManager = new SavepointState(),
|
|
13
14
|
private readonly state = new TransactionLikeState(),
|
|
14
15
|
) {
|
|
@@ -61,6 +62,9 @@ export class Transaction implements Connection.TransactionLike {
|
|
|
61
62
|
await this.query(command)
|
|
62
63
|
this.state.close()
|
|
63
64
|
}
|
|
65
|
+
|
|
66
|
+
on = this.connection.on.bind(this.connection)
|
|
67
|
+
|
|
64
68
|
}
|
|
65
69
|
|
|
66
70
|
class SavePoint implements Connection.TransactionLike {
|
|
@@ -68,7 +72,7 @@ class SavePoint implements Connection.TransactionLike {
|
|
|
68
72
|
constructor(
|
|
69
73
|
public readonly savepointName: string,
|
|
70
74
|
public readonly savepointManager: SavepointState,
|
|
71
|
-
private readonly connection: Connection.
|
|
75
|
+
private readonly connection: Connection.AcquiredConnectionLike,
|
|
72
76
|
private readonly state = new TransactionLikeState(),
|
|
73
77
|
) {
|
|
74
78
|
}
|
|
@@ -125,6 +129,8 @@ class SavePoint implements Connection.TransactionLike {
|
|
|
125
129
|
await this.query(sql)
|
|
126
130
|
this.state.close()
|
|
127
131
|
}
|
|
132
|
+
|
|
133
|
+
on = this.connection.on.bind(this.connection)
|
|
128
134
|
}
|
|
129
135
|
|
|
130
136
|
class TransactionLikeState {
|
|
@@ -143,7 +149,7 @@ class SavepointState {
|
|
|
143
149
|
public counter = 1
|
|
144
150
|
|
|
145
151
|
public async execute<Result>(
|
|
146
|
-
connection: Connection.
|
|
152
|
+
connection: Connection.AcquiredConnectionLike,
|
|
147
153
|
callback: (connection: Connection.TransactionLike) => Promise<Result> | Result,
|
|
148
154
|
) {
|
|
149
155
|
const savepointName = `savepoint_${this.counter++}`
|
package/src/client/errors.ts
CHANGED
|
@@ -32,6 +32,7 @@ export class ClientError extends DatabaseError {
|
|
|
32
32
|
export class QueryError extends DatabaseError {
|
|
33
33
|
public readonly code?: string
|
|
34
34
|
public readonly constraint?: string
|
|
35
|
+
public readonly table?: string
|
|
35
36
|
public readonly originalMessage?: string
|
|
36
37
|
|
|
37
38
|
constructor(public readonly sql: string, public readonly parameters: any, public readonly previous: Error | any) {
|
|
@@ -42,6 +43,7 @@ parameters: ${parameters}`,
|
|
|
42
43
|
previous,
|
|
43
44
|
)
|
|
44
45
|
this.constraint = previous.constraint
|
|
46
|
+
this.table = previous.table
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
|
package/src/index.ts
CHANGED
package/src/tsconfig.json
CHANGED
package/src/types.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type JSONPrimitive = string | number | boolean | null | undefined
|
|
2
2
|
export type JSONValue = JSONPrimitive | JSONObject | JSONArray
|
|
3
|
-
export type JSONObject = { [
|
|
4
|
-
export type JSONArray = JSONValue[]
|
|
3
|
+
export type JSONObject = { readonly [K in string]?: JSONValue }
|
|
4
|
+
export type JSONArray = readonly JSONValue[]
|
|
5
5
|
|
|
6
6
|
export type Value =
|
|
7
7
|
| JSONValue
|
|
@@ -7,6 +7,10 @@ export class ConstraintHelper {
|
|
|
7
7
|
|
|
8
8
|
constructor(private readonly client: Client) {}
|
|
9
9
|
|
|
10
|
+
public areFkConstraintsDeferred(): boolean {
|
|
11
|
+
return this.fkConstraintsLevel > 0
|
|
12
|
+
}
|
|
13
|
+
|
|
10
14
|
public async setFkConstraintsDeferred(): Promise<void> {
|
|
11
15
|
this.fkConstraintsLevel++
|
|
12
16
|
if (this.fkConstraintsLevel > 1) {
|
package/src/utils/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './assertNever'
|
|
|
2
2
|
export * from './asyncIterableTransaction'
|
|
3
3
|
export * from './ConstraintHelper'
|
|
4
4
|
export * from './createDatabaseIfNotExists'
|
|
5
|
+
export * from './listen'
|
|
5
6
|
export * from './Mutex'
|
|
6
7
|
export * from './sql'
|
|
7
8
|
export * from './retryTransaction'
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { Client, Connection } from '../client'
|
|
2
|
+
import { wrapIdentifier } from './sql'
|
|
3
|
+
import { clearInterval } from 'node:timers'
|
|
4
|
+
|
|
5
|
+
type ListenArgs<P> = {
|
|
6
|
+
client: Client<Connection.AcquiredConnectionLike>
|
|
7
|
+
channel: string
|
|
8
|
+
abortSignal?: AbortSignal
|
|
9
|
+
healthCheckMs?: number
|
|
10
|
+
onMessage: (payload: P) => void
|
|
11
|
+
onError: (err: any) => void
|
|
12
|
+
onClose?: () => void
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export class Listener<P> {
|
|
17
|
+
constructor(
|
|
18
|
+
private readonly client: Client<Connection.AcquiredConnectionLike>,
|
|
19
|
+
private readonly channel: string,
|
|
20
|
+
private readonly onMessage: (message: P) => void,
|
|
21
|
+
private readonly options: { healthCheckMs?: number } = {},
|
|
22
|
+
) {
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async run({ onClose, onError }: {
|
|
26
|
+
onError: (e: any) => void
|
|
27
|
+
onClose?: () => void
|
|
28
|
+
},
|
|
29
|
+
): Promise<{ end: () => Promise<void> }> {
|
|
30
|
+
let aborted = false
|
|
31
|
+
let onAbortInner = async () => {}
|
|
32
|
+
const onAbort = async () => {
|
|
33
|
+
aborted = true
|
|
34
|
+
await onAbortInner()
|
|
35
|
+
}
|
|
36
|
+
let cleanups: (() => void)[] = []
|
|
37
|
+
const cleanup = () => {
|
|
38
|
+
let localCleanup = cleanups
|
|
39
|
+
cleanups = []
|
|
40
|
+
localCleanup.forEach(it => it())
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
cleanups.push(this.client.connection.on('notification', ({ channel, payload }) => {
|
|
44
|
+
if (channel !== this.channel || aborted) {
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
this.onMessage(payload as P)
|
|
48
|
+
}))
|
|
49
|
+
await this.client.query(`LISTEN ${wrapIdentifier(this.channel)}`)
|
|
50
|
+
|
|
51
|
+
;(async () => {
|
|
52
|
+
const stopListening = async () => {
|
|
53
|
+
try {
|
|
54
|
+
await this.client.query(`UNLISTEN ${wrapIdentifier(this.channel)}`)
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
if (aborted) {
|
|
61
|
+
await stopListening()
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
await new Promise<void>((resolve, reject) => {
|
|
65
|
+
onAbortInner = async () => {
|
|
66
|
+
await stopListening()
|
|
67
|
+
resolve()
|
|
68
|
+
}
|
|
69
|
+
cleanups.push(this.client.connection.on('end', reject))
|
|
70
|
+
cleanups.push(this.client.connection.on('error', reject))
|
|
71
|
+
|
|
72
|
+
const healthCheckHandle = setInterval(async () => {
|
|
73
|
+
try {
|
|
74
|
+
await this.client.query('SELECT 1')
|
|
75
|
+
} catch (e) {
|
|
76
|
+
reject(e)
|
|
77
|
+
}
|
|
78
|
+
}, this.options.healthCheckMs ?? 30_000)
|
|
79
|
+
cleanups.push(() => clearInterval(healthCheckHandle))
|
|
80
|
+
})
|
|
81
|
+
onClose?.()
|
|
82
|
+
} catch (e) {
|
|
83
|
+
onError(e)
|
|
84
|
+
} finally {
|
|
85
|
+
cleanup()
|
|
86
|
+
}
|
|
87
|
+
})()
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
end: async () => {
|
|
91
|
+
await onAbort()
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
} catch (e) {
|
|
95
|
+
cleanup()
|
|
96
|
+
throw e
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
export class AcquiringListener<P> {
|
|
103
|
+
constructor(
|
|
104
|
+
private readonly client: Client,
|
|
105
|
+
private readonly channel: string,
|
|
106
|
+
private readonly onMessage: (message: P) => void,
|
|
107
|
+
private readonly options: { healthCheckMs?: number } = {},
|
|
108
|
+
) {
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async run({ onClose, onError }: { onError: (e: any) => void;onClose?: () => void },
|
|
112
|
+
): Promise<{ end: () => Promise<void> }> {
|
|
113
|
+
return new Promise(async (resolveRunning, rejectRunning) => {
|
|
114
|
+
try {
|
|
115
|
+
await this.client.scope(async db => {
|
|
116
|
+
const listener = new Listener<P>(db, this.channel, this.onMessage, this.options)
|
|
117
|
+
await new Promise<void>(async (resolveScope, rejectScope) => {
|
|
118
|
+
try {
|
|
119
|
+
const running = await listener.run({
|
|
120
|
+
onClose: resolveScope,
|
|
121
|
+
onError: rejectScope,
|
|
122
|
+
})
|
|
123
|
+
resolveRunning({
|
|
124
|
+
end: async () => {
|
|
125
|
+
await running.end()
|
|
126
|
+
},
|
|
127
|
+
})
|
|
128
|
+
} catch (e) {
|
|
129
|
+
rejectScope(e)
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
onClose?.()
|
|
134
|
+
} catch (e) {
|
|
135
|
+
rejectRunning(e)
|
|
136
|
+
onError(e)
|
|
137
|
+
}
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -34,7 +34,7 @@ it('acquires and releases new connection from pool', async () => {
|
|
|
34
34
|
CAI P
|
|
35
35
|
000 1: Item added to a queue.
|
|
36
36
|
000 1: Creating a new connection
|
|
37
|
-
|
|
37
|
+
000 1: Connection established
|
|
38
38
|
010 0: Queued item fulfilled with new connection.
|
|
39
39
|
010 0: Not connecting, queue is empty.
|
|
40
40
|
010 0: Releasing a connection.
|
|
@@ -57,7 +57,7 @@ it('disposes connection when maxIdle is reached', async () => {
|
|
|
57
57
|
CAI P
|
|
58
58
|
000 1: Item added to a queue.
|
|
59
59
|
000 1: Creating a new connection
|
|
60
|
-
|
|
60
|
+
000 1: Connection established
|
|
61
61
|
010 0: Queued item fulfilled with new connection.
|
|
62
62
|
010 0: Not connecting, queue is empty.
|
|
63
63
|
010 0: Releasing a connection.
|
|
@@ -79,7 +79,7 @@ it('disposes connection after max uses', async () => {
|
|
|
79
79
|
CAI P
|
|
80
80
|
000 1: Item added to a queue.
|
|
81
81
|
000 1: Creating a new connection
|
|
82
|
-
|
|
82
|
+
000 1: Connection established
|
|
83
83
|
010 0: Queued item fulfilled with new connection.
|
|
84
84
|
010 0: Not connecting, queue is empty.
|
|
85
85
|
010 0: Releasing a connection.
|
|
@@ -102,7 +102,7 @@ it('disposes errored connection', async () => {
|
|
|
102
102
|
CAI P
|
|
103
103
|
000 1: Item added to a queue.
|
|
104
104
|
000 1: Creating a new connection
|
|
105
|
-
|
|
105
|
+
000 1: Connection established
|
|
106
106
|
010 0: Queued item fulfilled with new connection.
|
|
107
107
|
010 0: Not connecting, queue is empty.
|
|
108
108
|
010 0: Releasing and disposing a connection.
|
|
@@ -129,7 +129,7 @@ it('time outs when waiting for a connection', async () => {
|
|
|
129
129
|
000 1: Item added to a queue.
|
|
130
130
|
000 1: Creating a new connection
|
|
131
131
|
100 0: Queued item timed out
|
|
132
|
-
|
|
132
|
+
000 0: Connection established
|
|
133
133
|
001 0: Connection is idle and available.
|
|
134
134
|
001 0: Not connecting, queue is empty.
|
|
135
135
|
`)
|
|
@@ -171,12 +171,12 @@ it('acquires multiple new connections from pool', async () => {
|
|
|
171
171
|
CAI P
|
|
172
172
|
000 1: Item added to a queue.
|
|
173
173
|
000 1: Creating a new connection
|
|
174
|
-
|
|
174
|
+
000 1: Connection established
|
|
175
175
|
010 0: Queued item fulfilled with new connection.
|
|
176
176
|
010 0: Not connecting, queue is empty.
|
|
177
177
|
010 1: Item added to a queue.
|
|
178
178
|
010 1: Creating a new connection
|
|
179
|
-
|
|
179
|
+
010 1: Connection established
|
|
180
180
|
020 0: Queued item fulfilled with new connection.
|
|
181
181
|
020 0: Not connecting, queue is empty.
|
|
182
182
|
020 0: Releasing a connection.
|
|
@@ -201,7 +201,7 @@ it('releases idle connection', async () => {
|
|
|
201
201
|
CAI P
|
|
202
202
|
000 1: Item added to a queue.
|
|
203
203
|
000 1: Creating a new connection
|
|
204
|
-
|
|
204
|
+
000 1: Connection established
|
|
205
205
|
010 0: Queued item fulfilled with new connection.
|
|
206
206
|
010 0: Not connecting, queue is empty.
|
|
207
207
|
010 0: Releasing a connection.
|
|
@@ -229,7 +229,7 @@ it('waits for idle connection when pool is full', async () => {
|
|
|
229
229
|
CAI P
|
|
230
230
|
000 1: Item added to a queue.
|
|
231
231
|
000 1: Creating a new connection
|
|
232
|
-
|
|
232
|
+
000 1: Connection established
|
|
233
233
|
010 0: Queued item fulfilled with new connection.
|
|
234
234
|
010 0: Not connecting, queue is empty.
|
|
235
235
|
010 1: Item added to a queue.
|
|
@@ -267,7 +267,7 @@ it('tries to reconnect on recoverable error', async () => {
|
|
|
267
267
|
100 1: Recoverable error, retrying in a moment.
|
|
268
268
|
000 1: Retrying
|
|
269
269
|
000 1: Creating a new connection
|
|
270
|
-
|
|
270
|
+
000 1: Connection established
|
|
271
271
|
010 0: Queued item fulfilled with new connection.
|
|
272
272
|
010 0: Not connecting, queue is empty.
|
|
273
273
|
`)
|
|
@@ -378,7 +378,7 @@ it('rate limit', async () => {
|
|
|
378
378
|
CAI P
|
|
379
379
|
000 1: Item added to a queue.
|
|
380
380
|
000 1: Creating a new connection
|
|
381
|
-
|
|
381
|
+
000 1: Connection established
|
|
382
382
|
010 0: Queued item fulfilled with new connection.
|
|
383
383
|
010 0: Not connecting, queue is empty.
|
|
384
384
|
010 1: Item added to a queue.
|
|
@@ -392,7 +392,7 @@ it('rate limit', async () => {
|
|
|
392
392
|
000 1: Not connecting, rate limit reached.
|
|
393
393
|
000 1: Rate limit renewed.
|
|
394
394
|
000 1: Creating a new connection
|
|
395
|
-
|
|
395
|
+
000 1: Connection established
|
|
396
396
|
010 0: Queued item fulfilled with new connection.
|
|
397
397
|
010 0: Not connecting, queue is empty.
|
|
398
398
|
`)
|