@contember/database 1.2.0-alpha.8 → 1.2.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/builders/DeleteBuilder.d.ts +1 -1
- package/dist/src/builders/DeleteBuilder.d.ts.map +1 -1
- package/dist/src/builders/DeleteBuilder.js.map +1 -1
- package/dist/src/builders/InsertBuilder.d.ts +1 -1
- package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/src/builders/InsertBuilder.js.map +1 -1
- package/dist/src/builders/LimitByGroupWrapper.d.ts.map +1 -1
- package/dist/src/builders/LimitByGroupWrapper.js +2 -1
- package/dist/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/src/builders/SelectBuilder.d.ts +1 -0
- package/dist/src/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/src/builders/SelectBuilder.js +5 -2
- package/dist/src/builders/SelectBuilder.js.map +1 -1
- package/dist/src/builders/UpdateBuilder.d.ts +1 -1
- package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/src/builders/UpdateBuilder.js.map +1 -1
- package/dist/src/client/Connection.d.ts +3 -3
- package/dist/src/client/Connection.d.ts.map +1 -1
- package/dist/src/client/Connection.js +4 -9
- package/dist/src/client/Connection.js.map +1 -1
- package/dist/src/client/EventManager.d.ts +1 -4
- package/dist/src/client/EventManager.d.ts.map +1 -1
- package/dist/src/client/EventManager.js +0 -2
- package/dist/src/client/EventManager.js.map +1 -1
- package/dist/src/client/PgClient.d.ts +1 -1
- package/dist/src/client/PgClient.d.ts.map +1 -1
- package/dist/src/client/Pool.d.ts +14 -10
- package/dist/src/client/Pool.d.ts.map +1 -1
- package/dist/src/client/Pool.js +45 -34
- package/dist/src/client/Pool.js.map +1 -1
- package/dist/src/client/errors.d.ts +3 -1
- package/dist/src/client/errors.d.ts.map +1 -1
- package/dist/src/client/errors.js +3 -2
- package/dist/src/client/errors.js.map +1 -1
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/utils/Mutex.js +2 -2
- package/dist/src/utils/Mutex.js.map +1 -1
- package/dist/src/utils/createDatabaseIfNotExists.d.ts +1 -1
- package/dist/src/utils/createDatabaseIfNotExists.d.ts.map +1 -1
- package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
- package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
- package/dist/src/utils/retryTransaction.d.ts +1 -1
- package/dist/src/utils/retryTransaction.d.ts.map +1 -1
- package/dist/src/utils/retryTransaction.js +3 -5
- package/dist/src/utils/retryTransaction.js.map +1 -1
- package/dist/tests/cases/unit/createConnectionMockAlt.js +3 -3
- package/dist/tests/cases/unit/createConnectionMockAlt.js.map +1 -1
- package/dist/tests/cases/unit/pool.test.js +61 -12
- package/dist/tests/cases/unit/pool.test.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/src/builders/DeleteBuilder.ts +1 -1
- package/src/builders/InsertBuilder.ts +1 -1
- package/src/builders/LimitByGroupWrapper.ts +2 -1
- package/src/builders/SelectBuilder.ts +7 -2
- package/src/builders/UpdateBuilder.ts +1 -1
- package/src/client/Connection.ts +5 -8
- package/src/client/EventManager.ts +0 -4
- package/src/client/PgClient.ts +1 -1
- package/src/client/Pool.ts +58 -36
- package/src/client/errors.ts +10 -2
- package/src/utils/Mutex.ts +1 -1
- package/src/utils/createDatabaseIfNotExists.ts +3 -3
- package/src/utils/retryTransaction.ts +3 -4
- package/tests/cases/unit/createConnectionMockAlt.ts +2 -2
- package/tests/cases/unit/pool.test.ts +62 -12
|
@@ -5,7 +5,6 @@ class EventManager {
|
|
|
5
5
|
[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],
|
|
6
6
|
[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],
|
|
7
7
|
[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],
|
|
8
|
-
[EventManager.Event.clientError]: [] as EventManager.ClientErrorCallback[],
|
|
9
8
|
}
|
|
10
9
|
|
|
11
10
|
constructor(
|
|
@@ -39,19 +38,16 @@ namespace EventManager {
|
|
|
39
38
|
queryStart = 'queryStart',
|
|
40
39
|
queryEnd = 'queryEnd',
|
|
41
40
|
queryError = 'queryError',
|
|
42
|
-
clientError = 'clientError',
|
|
43
41
|
}
|
|
44
42
|
|
|
45
43
|
export type QueryStartCallback = (query: Connection.Query) => void
|
|
46
44
|
export type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void
|
|
47
45
|
export type QueryErrorCallback = (query: Connection.Query, error: Error) => void
|
|
48
|
-
export type ClientErrorCallback = (error: Error) => void
|
|
49
46
|
|
|
50
47
|
export interface ListenerTypes {
|
|
51
48
|
[EventManager.Event.queryStart]: QueryStartCallback
|
|
52
49
|
[EventManager.Event.queryEnd]: QueryEndCallback
|
|
53
50
|
[EventManager.Event.queryError]: QueryErrorCallback
|
|
54
|
-
[EventManager.Event.clientError]: ClientErrorCallback
|
|
55
51
|
}
|
|
56
52
|
|
|
57
53
|
export type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }
|
package/src/client/PgClient.ts
CHANGED
package/src/client/Pool.ts
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { ImplementationException } from '../exceptions'
|
|
2
2
|
import { ClientErrorCodes } from './errorCodes'
|
|
3
|
-
import EventEmitter from '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'
|
|
7
7
|
|
|
8
8
|
export type PoolLogger = (message: string, status: PoolStatus) => void
|
|
9
9
|
|
|
10
|
-
export type PoolConfig = Partial<PoolConfigInternal>
|
|
10
|
+
export type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>
|
|
11
11
|
|
|
12
12
|
interface PoolConfigInternal {
|
|
13
13
|
/** maximum number of connections in a pool */
|
|
14
14
|
maxConnections: number
|
|
15
15
|
/** maximum number of connections concurrently establishing*/
|
|
16
16
|
maxConnecting: number
|
|
17
|
+
/** maximum connection attempts during given period */
|
|
18
|
+
rateLimitCount: number
|
|
19
|
+
/** period for rate limiting */
|
|
20
|
+
rateLimitPeriodMs: number
|
|
17
21
|
/** maximum number of idle connections. when reached, will be disposed immediately */
|
|
18
22
|
maxIdle: number
|
|
19
23
|
/** interval between retries of recoverable errors */
|
|
@@ -28,6 +32,8 @@ interface PoolConfigInternal {
|
|
|
28
32
|
maxAgeMs?: number
|
|
29
33
|
/** internal logging, mainly for debugging and testing */
|
|
30
34
|
log?: PoolLogger
|
|
35
|
+
/** logging of out-of-stack errors */
|
|
36
|
+
logError: (error: ClientError) => void
|
|
31
37
|
}
|
|
32
38
|
|
|
33
39
|
export type PoolStats = { [K in keyof typeof poolStatsDescription]: number }
|
|
@@ -92,17 +98,11 @@ class PendingItem {
|
|
|
92
98
|
}
|
|
93
99
|
}
|
|
94
100
|
|
|
95
|
-
|
|
96
|
-
on(event: 'error', listener: (err: Error) => void): this
|
|
97
|
-
|
|
98
|
-
on(event: 'recoverableError', listener: (err: Error) => void): this
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
class Pool extends EventEmitter {
|
|
101
|
+
class Pool {
|
|
102
102
|
|
|
103
103
|
/**
|
|
104
104
|
* pool was closed by calling end().
|
|
105
|
-
* All connection was disposed and it is not possible to acquire new one
|
|
105
|
+
* All connection was disposed, and it is not possible to acquire new one
|
|
106
106
|
*/
|
|
107
107
|
private ended = false
|
|
108
108
|
|
|
@@ -112,6 +112,11 @@ class Pool extends EventEmitter {
|
|
|
112
112
|
*/
|
|
113
113
|
private connectingCount = 0
|
|
114
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Remaining number of connections per floating period.
|
|
117
|
+
*/
|
|
118
|
+
private remainingRateLimit: number
|
|
119
|
+
|
|
115
120
|
/**
|
|
116
121
|
* available idle connections
|
|
117
122
|
*/
|
|
@@ -159,16 +164,20 @@ class Pool extends EventEmitter {
|
|
|
159
164
|
private clientFactory: PgClientFactory,
|
|
160
165
|
poolConfig: PoolConfig,
|
|
161
166
|
) {
|
|
162
|
-
|
|
167
|
+
const maxConnections = poolConfig.maxConnections ?? 10
|
|
168
|
+
const maxConnecting = Math.ceil(maxConnections / 2)
|
|
163
169
|
this.poolConfig = {
|
|
164
|
-
maxConnections
|
|
165
|
-
maxConnecting
|
|
166
|
-
maxIdle:
|
|
170
|
+
maxConnections,
|
|
171
|
+
maxConnecting,
|
|
172
|
+
maxIdle: maxConnections,
|
|
173
|
+
rateLimitCount: maxConnecting * 5,
|
|
174
|
+
rateLimitPeriodMs: 1000,
|
|
167
175
|
idleTimeoutMs: 10_000,
|
|
168
176
|
acquireTimeoutMs: 10_000,
|
|
169
177
|
reconnectIntervalMs: 100,
|
|
170
178
|
...poolConfig,
|
|
171
179
|
}
|
|
180
|
+
this.remainingRateLimit = this.poolConfig.rateLimitCount
|
|
172
181
|
}
|
|
173
182
|
|
|
174
183
|
public acquire(): Promise<PoolConnection> {
|
|
@@ -264,7 +273,7 @@ class Pool extends EventEmitter {
|
|
|
264
273
|
}
|
|
265
274
|
|
|
266
275
|
|
|
267
|
-
private async maybeCreateNew(
|
|
276
|
+
private async maybeCreateNew(): Promise<void> {
|
|
268
277
|
if (this.ended) {
|
|
269
278
|
return
|
|
270
279
|
}
|
|
@@ -286,15 +295,21 @@ class Pool extends EventEmitter {
|
|
|
286
295
|
this.log('Not connecting, maximum concurrent connection attempts in progress.')
|
|
287
296
|
return
|
|
288
297
|
}
|
|
298
|
+
if (this.remainingRateLimit <= 0) {
|
|
299
|
+
this.log('Not connecting, rate limit reached.')
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
|
|
289
303
|
this.log('Creating a new connection')
|
|
290
304
|
const client = this.clientFactory()
|
|
291
|
-
this.connectingCount++
|
|
292
305
|
const poolConnection = new PoolConnection(client)
|
|
293
306
|
client.on('error', e => {
|
|
294
307
|
this.log('Client error on idle connection has occurred: ' + e.message)
|
|
295
|
-
this.
|
|
308
|
+
this.poolConfig.logError(new ClientError(e, 'runtime error'))
|
|
296
309
|
})
|
|
297
310
|
try {
|
|
311
|
+
this.connectingCount++
|
|
312
|
+
this.remainingRateLimit--
|
|
298
313
|
await client.connect()
|
|
299
314
|
this.poolStats.connection_established_count++
|
|
300
315
|
this.log('Connection established')
|
|
@@ -307,40 +322,47 @@ class Pool extends EventEmitter {
|
|
|
307
322
|
this.log('Connection error occurred: ' + e.message)
|
|
308
323
|
try {
|
|
309
324
|
await client.end()
|
|
310
|
-
} catch {
|
|
325
|
+
} catch (e2: unknown) {
|
|
326
|
+
this.poolConfig.logError(new ClientError(e2, 'disposal error'))
|
|
311
327
|
}
|
|
312
|
-
if (
|
|
328
|
+
if (
|
|
329
|
+
e.code === ClientErrorCodes.TOO_MANY_CONNECTIONS
|
|
330
|
+
|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting
|
|
331
|
+
|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105
|
|
332
|
+
) {
|
|
313
333
|
this.lastRecoverableError = { error: e, time: Date.now() }
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
334
|
+
this.poolStats.connection_recoverable_error_count++
|
|
335
|
+
this.log('Recoverable error, retrying in a moment.')
|
|
336
|
+
this.poolConfig.logError(new ClientError(e, 'recoverable connection error'))
|
|
337
|
+
setTimeout(() => {
|
|
318
338
|
this.connectingCount--
|
|
319
|
-
|
|
320
|
-
this.
|
|
321
|
-
|
|
322
|
-
this.emit('recoverableError', e)
|
|
323
|
-
setTimeout(() => {
|
|
324
|
-
this.connectingCount--
|
|
325
|
-
this.log('Retrying')
|
|
326
|
-
this.maybeCreateNew(attempt + 1)
|
|
327
|
-
}, this.poolConfig.reconnectIntervalMs)
|
|
328
|
-
}
|
|
339
|
+
this.log('Retrying')
|
|
340
|
+
this.maybeCreateNew()
|
|
341
|
+
}, this.poolConfig.reconnectIntervalMs)
|
|
329
342
|
} else {
|
|
330
343
|
this.poolStats.connection_error_count++
|
|
331
344
|
this.connectingCount--
|
|
345
|
+
const clientError = new ClientError(e, 'connection error')
|
|
332
346
|
if (this.active.size === 0 && this.queue.length > 0) {
|
|
333
347
|
const pendingItem = this.queue.shift()
|
|
334
348
|
if (!pendingItem) throw new Error()
|
|
335
349
|
this.log('Connecting failed, rejecting pending item')
|
|
336
|
-
pendingItem.reject(
|
|
350
|
+
pendingItem.reject(clientError)
|
|
337
351
|
this.poolStats.item_rejected_count++
|
|
338
352
|
} else {
|
|
339
353
|
this.log('Connecting failed, emitting error')
|
|
340
|
-
this.
|
|
354
|
+
this.poolConfig.logError(clientError)
|
|
341
355
|
}
|
|
342
356
|
}
|
|
343
357
|
return
|
|
358
|
+
} finally {
|
|
359
|
+
setTimeout(() => {
|
|
360
|
+
if (this.remainingRateLimit === 0) {
|
|
361
|
+
this.log('Rate limit renewed.')
|
|
362
|
+
}
|
|
363
|
+
this.remainingRateLimit++
|
|
364
|
+
this.maybeCreateNew()
|
|
365
|
+
}, this.poolConfig.rateLimitPeriodMs)
|
|
344
366
|
}
|
|
345
367
|
this.handleAvailableConnection(poolConnection)
|
|
346
368
|
this.maybeCreateNew()
|
|
@@ -436,7 +458,7 @@ class Pool extends EventEmitter {
|
|
|
436
458
|
connection.disposed = true
|
|
437
459
|
await connection.client.end()
|
|
438
460
|
} catch (e: any) {
|
|
439
|
-
this.
|
|
461
|
+
this.poolConfig.logError(new ClientError(e, 'disposal error'))
|
|
440
462
|
}
|
|
441
463
|
}
|
|
442
464
|
|
package/src/client/errors.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ClientErrorCodes } from './errorCodes'
|
|
2
|
+
|
|
1
3
|
export class DatabaseError extends Error {
|
|
2
4
|
public readonly code?: string
|
|
3
5
|
public readonly originalMessage?: string
|
|
@@ -15,9 +17,15 @@ export class DatabaseError extends Error {
|
|
|
15
17
|
}
|
|
16
18
|
}
|
|
17
19
|
|
|
20
|
+
export type ClientErrorType =
|
|
21
|
+
| 'recoverable connection error'
|
|
22
|
+
| 'connection error'
|
|
23
|
+
| 'runtime error'
|
|
24
|
+
| 'disposal error'
|
|
25
|
+
|
|
18
26
|
export class ClientError extends DatabaseError {
|
|
19
|
-
constructor(previous: Error | any) {
|
|
20
|
-
super(`Database client
|
|
27
|
+
constructor(previous: Error | any, public readonly type: ClientErrorType) {
|
|
28
|
+
super(`Database client ${type}: ${'message' in previous ? previous.message : JSON.stringify(previous)}`, previous)
|
|
21
29
|
}
|
|
22
30
|
}
|
|
23
31
|
|
package/src/utils/Mutex.ts
CHANGED
|
@@ -2,9 +2,9 @@ import { DatabaseConfig } from '../types'
|
|
|
2
2
|
import { ClientError, ClientErrorCodes, Connection } from '../client'
|
|
3
3
|
import { wrapIdentifier } from './sql'
|
|
4
4
|
|
|
5
|
-
export const createDatabaseIfNotExists = async (db: DatabaseConfig, log: (message: string) => void) => {
|
|
5
|
+
export const createDatabaseIfNotExists = async (db: DatabaseConfig, log: (message: string | Error) => void) => {
|
|
6
6
|
try {
|
|
7
|
-
const connection = Connection.createSingle(db)
|
|
7
|
+
const connection = Connection.createSingle(db, log)
|
|
8
8
|
await connection.query('SELECT 1')
|
|
9
9
|
await connection.end()
|
|
10
10
|
return
|
|
@@ -15,7 +15,7 @@ export const createDatabaseIfNotExists = async (db: DatabaseConfig, log: (messag
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
log(`Database ${db.database} does not exist, attempting to create it...`)
|
|
18
|
-
const connection = Connection.createSingle({ ...db, database: 'postgres' })
|
|
18
|
+
const connection = Connection.createSingle({ ...db, database: 'postgres' }, log)
|
|
19
19
|
await connection.query(`CREATE DATABASE ${wrapIdentifier(db.database)}`)
|
|
20
20
|
await connection.end()
|
|
21
21
|
}
|
|
@@ -14,6 +14,7 @@ const defaultOptions: RetryOptions = {
|
|
|
14
14
|
|
|
15
15
|
export const retryTransaction = async <R>(
|
|
16
16
|
cb: () => Promise<R> | R,
|
|
17
|
+
logger: (message: string) => void,
|
|
17
18
|
options: Partial<RetryOptions> = {},
|
|
18
19
|
): Promise<R> => {
|
|
19
20
|
let attempt = 0
|
|
@@ -36,11 +37,9 @@ export const retryTransaction = async <R>(
|
|
|
36
37
|
}
|
|
37
38
|
if (attempt < maxAttempts) {
|
|
38
39
|
const timeoutMs = await timeout(attempt)
|
|
39
|
-
|
|
40
|
-
console.error(`RETRY: Serialization failure (attempt #${attempt}, retrying after ${timeoutMs}ms)`)
|
|
40
|
+
logger(`RETRY: Serialization failure (attempt #${attempt}, retrying after ${timeoutMs}ms)`)
|
|
41
41
|
} else {
|
|
42
|
-
|
|
43
|
-
console.error(`ABORT: Serialization failure (attempt #${attempt})`)
|
|
42
|
+
logger(`ABORT: Serialization failure (attempt #${attempt})`)
|
|
44
43
|
throw e
|
|
45
44
|
}
|
|
46
45
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Connection, Pool } from '../../../src'
|
|
2
2
|
import { PgClient } from '../../../src/client/PgClient'
|
|
3
|
-
import EventEmitter from 'events'
|
|
3
|
+
import EventEmitter from 'node:events'
|
|
4
4
|
import { expect } from 'vitest'
|
|
5
5
|
|
|
6
6
|
export const createConnectionMockAlt = (...queries: { sql: string; timeout?: number }[][]): [Connection, () => void] => {
|
|
@@ -34,7 +34,7 @@ export const createConnectionMockAlt = (...queries: { sql: string; timeout?: num
|
|
|
34
34
|
return connectionMocks.shift() ?? (() => {
|
|
35
35
|
throw new Error('No connection')
|
|
36
36
|
})()
|
|
37
|
-
}, {})
|
|
37
|
+
}, { logError: () => null })
|
|
38
38
|
return [
|
|
39
39
|
new Connection(pool),
|
|
40
40
|
() => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { expect, it, beforeAll } from 'vitest'
|
|
2
2
|
import { ClientErrorCodes, Pool, PoolLogger } from '../../../src'
|
|
3
3
|
import { Client as PgClient } from 'pg'
|
|
4
|
-
import EventEmitter from 'events'
|
|
4
|
+
import EventEmitter from 'node:events'
|
|
5
5
|
|
|
6
6
|
const createPoolLogger = () => {
|
|
7
7
|
const logger: PoolLogger & {messages: string; clear: () => void} = (message, pool) => {
|
|
@@ -25,6 +25,7 @@ it('acquires and releases new connection from pool', async () => {
|
|
|
25
25
|
const logger = createPoolLogger()
|
|
26
26
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
27
27
|
log: logger,
|
|
28
|
+
logError: () => null,
|
|
28
29
|
})
|
|
29
30
|
const connection = await pool.acquire()
|
|
30
31
|
await pool.release(connection)
|
|
@@ -46,6 +47,7 @@ it('disposes connection when maxIdle is reached', async () => {
|
|
|
46
47
|
const logger = createPoolLogger()
|
|
47
48
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
48
49
|
log: logger,
|
|
50
|
+
logError: () => null,
|
|
49
51
|
maxIdle: 0,
|
|
50
52
|
})
|
|
51
53
|
const connection = await pool.acquire()
|
|
@@ -67,6 +69,7 @@ it('disposes connection after max uses', async () => {
|
|
|
67
69
|
const logger = createPoolLogger()
|
|
68
70
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
69
71
|
log: logger,
|
|
72
|
+
logError: () => null,
|
|
70
73
|
maxUses: 1,
|
|
71
74
|
})
|
|
72
75
|
const connection = await pool.acquire()
|
|
@@ -89,6 +92,7 @@ it('disposes errored connection', async () => {
|
|
|
89
92
|
const logger = createPoolLogger()
|
|
90
93
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
91
94
|
log: logger,
|
|
95
|
+
logError: () => null,
|
|
92
96
|
maxIdle: 0,
|
|
93
97
|
})
|
|
94
98
|
const connection = await pool.acquire()
|
|
@@ -114,6 +118,7 @@ it('time outs when waiting for a connection', async () => {
|
|
|
114
118
|
clientMock.connections.push(createSuccessfulPromise(5))
|
|
115
119
|
const pool = new Pool(() => clientMock as unknown as PgClient, {
|
|
116
120
|
log: logger,
|
|
121
|
+
logError: () => null,
|
|
117
122
|
acquireTimeoutMs: 2,
|
|
118
123
|
})
|
|
119
124
|
await expect(pool.acquire.bind(pool)).rejects.toThrowError('Failed to acquire a connection')
|
|
@@ -135,6 +140,7 @@ it('acquires idle connection from pool', async () => {
|
|
|
135
140
|
const logger = createPoolLogger()
|
|
136
141
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
137
142
|
log: logger,
|
|
143
|
+
logError: () => null,
|
|
138
144
|
})
|
|
139
145
|
const connection = await pool.acquire()
|
|
140
146
|
await pool.release(connection)
|
|
@@ -154,6 +160,7 @@ it('acquires multiple new connections from pool', async () => {
|
|
|
154
160
|
const logger = createPoolLogger()
|
|
155
161
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
156
162
|
log: logger,
|
|
163
|
+
logError: () => null,
|
|
157
164
|
})
|
|
158
165
|
const conn1 = await pool.acquire()
|
|
159
166
|
const conn2 = await pool.acquire()
|
|
@@ -184,6 +191,7 @@ it('releases idle connection', async () => {
|
|
|
184
191
|
const logger = createPoolLogger()
|
|
185
192
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
186
193
|
log: logger,
|
|
194
|
+
logError: () => null,
|
|
187
195
|
idleTimeoutMs: 2,
|
|
188
196
|
})
|
|
189
197
|
const conn1 = await pool.acquire()
|
|
@@ -208,6 +216,7 @@ it('waits for idle connection when pool is full', async () => {
|
|
|
208
216
|
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
209
217
|
maxConnections: 1,
|
|
210
218
|
log: logger,
|
|
219
|
+
logError: () => null,
|
|
211
220
|
})
|
|
212
221
|
const conn1 = await pool.acquire()
|
|
213
222
|
setTimeout(async () => {
|
|
@@ -241,6 +250,7 @@ it('tries to reconnect on recoverable error', async () => {
|
|
|
241
250
|
})
|
|
242
251
|
const pool = new Pool(() => pgClientMock as unknown as PgClient, {
|
|
243
252
|
log: logger,
|
|
253
|
+
logError: () => null,
|
|
244
254
|
})
|
|
245
255
|
pgClientMock.connections.push(createRecoverableErrorPromise(), createRecoverableErrorPromise())
|
|
246
256
|
await pool.acquire()
|
|
@@ -272,14 +282,13 @@ it('fails to reconnect on recoverable error', async () => {
|
|
|
272
282
|
})
|
|
273
283
|
const pool = new Pool(() => pgClientMock as unknown as PgClient, {
|
|
274
284
|
log: logger,
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
pool.on('error', () => {
|
|
285
|
+
logError: () => null,
|
|
286
|
+
reconnectIntervalMs: 20,
|
|
287
|
+
acquireTimeoutMs: 30,
|
|
279
288
|
})
|
|
280
289
|
pgClientMock.connections.push(createRecoverableErrorPromise(), createRecoverableErrorPromise())
|
|
281
290
|
await expect(async () => await pool.acquire()).rejects.toThrowError('Failed to acquire a connection. Last error: too many connection')
|
|
282
|
-
await timeout(
|
|
291
|
+
await timeout(20)
|
|
283
292
|
expect(logger.messages).toMatchInlineSnapshot(`
|
|
284
293
|
CAI P
|
|
285
294
|
000 1: Item added to a queue.
|
|
@@ -289,8 +298,10 @@ it('fails to reconnect on recoverable error', async () => {
|
|
|
289
298
|
000 1: Retrying
|
|
290
299
|
000 1: Creating a new connection
|
|
291
300
|
100 1: Connection error occurred: too many connection
|
|
292
|
-
100 1: Recoverable error,
|
|
293
|
-
|
|
301
|
+
100 1: Recoverable error, retrying in a moment.
|
|
302
|
+
100 0: Queued item timed out
|
|
303
|
+
000 0: Retrying
|
|
304
|
+
000 0: Not connecting, queue is empty.
|
|
294
305
|
`)
|
|
295
306
|
})
|
|
296
307
|
|
|
@@ -301,12 +312,10 @@ it('fails to reconnect on unrecoverable error', async () => {
|
|
|
301
312
|
})
|
|
302
313
|
const pool = new Pool(() => pgClientMock as unknown as PgClient, {
|
|
303
314
|
log: logger,
|
|
304
|
-
|
|
305
|
-
pool.on('error', () => {
|
|
306
|
-
|
|
315
|
+
logError: () => null,
|
|
307
316
|
})
|
|
308
317
|
pgClientMock.connections.push(createErrorPromise())
|
|
309
|
-
await expect(async () => await pool.acquire()).rejects.toThrowError('Database client error: my err')
|
|
318
|
+
await expect(async () => await pool.acquire()).rejects.toThrowError('Database client connection error: my err')
|
|
310
319
|
await timeout()
|
|
311
320
|
expect(logger.messages).toMatchInlineSnapshot(`
|
|
312
321
|
CAI P
|
|
@@ -347,3 +356,44 @@ const PgClientMock = class extends EventEmitter {
|
|
|
347
356
|
return createSuccessfulPromise()
|
|
348
357
|
}
|
|
349
358
|
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
it('rate limit', async () => {
|
|
362
|
+
const logger = createPoolLogger()
|
|
363
|
+
const pool = new Pool(() => new PgClientMock() as unknown as PgClient, {
|
|
364
|
+
rateLimitCount: 1,
|
|
365
|
+
rateLimitPeriodMs: 50,
|
|
366
|
+
log: logger,
|
|
367
|
+
logError: () => null,
|
|
368
|
+
})
|
|
369
|
+
const conn1 = await pool.acquire()
|
|
370
|
+
setTimeout(async () => {
|
|
371
|
+
await pool.release(conn1)
|
|
372
|
+
}, 20)
|
|
373
|
+
const conn2 = await pool.acquire()
|
|
374
|
+
await pool.dispose(conn2)
|
|
375
|
+
await timeout(10)
|
|
376
|
+
const conn3 = await pool.acquire()
|
|
377
|
+
expect(logger.messages).toMatchInlineSnapshot(`
|
|
378
|
+
CAI P
|
|
379
|
+
000 1: Item added to a queue.
|
|
380
|
+
000 1: Creating a new connection
|
|
381
|
+
100 1: Connection established
|
|
382
|
+
010 0: Queued item fulfilled with new connection.
|
|
383
|
+
010 0: Not connecting, queue is empty.
|
|
384
|
+
010 1: Item added to a queue.
|
|
385
|
+
010 1: Not connecting, rate limit reached.
|
|
386
|
+
010 1: Releasing a connection.
|
|
387
|
+
010 0: Queued item fulfilled with released connection.
|
|
388
|
+
010 0: Releasing and disposing a connection.
|
|
389
|
+
000 0: Not connecting, queue is empty.
|
|
390
|
+
000 0: Connection errored and was disposed.
|
|
391
|
+
000 1: Item added to a queue.
|
|
392
|
+
000 1: Not connecting, rate limit reached.
|
|
393
|
+
000 1: Rate limit renewed.
|
|
394
|
+
000 1: Creating a new connection
|
|
395
|
+
100 1: Connection established
|
|
396
|
+
010 0: Queued item fulfilled with new connection.
|
|
397
|
+
010 0: Not connecting, queue is empty.
|
|
398
|
+
`)
|
|
399
|
+
})
|