@contember/database 1.1.1 → 1.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 (123) hide show
  1. package/dist/src/builders/DeleteBuilder.d.ts +1 -1
  2. package/dist/src/builders/DeleteBuilder.d.ts.map +1 -1
  3. package/dist/src/builders/DeleteBuilder.js.map +1 -1
  4. package/dist/src/builders/InsertBuilder.d.ts +1 -1
  5. package/dist/src/builders/InsertBuilder.d.ts.map +1 -1
  6. package/dist/src/builders/InsertBuilder.js.map +1 -1
  7. package/dist/src/builders/UpdateBuilder.d.ts +1 -1
  8. package/dist/src/builders/UpdateBuilder.d.ts.map +1 -1
  9. package/dist/src/builders/UpdateBuilder.js.map +1 -1
  10. package/dist/src/client/AcquiredConnection.d.ts +17 -0
  11. package/dist/src/client/AcquiredConnection.d.ts.map +1 -0
  12. package/dist/src/client/AcquiredConnection.js +78 -0
  13. package/dist/src/client/AcquiredConnection.js.map +1 -0
  14. package/dist/src/client/Client.d.ts +3 -1
  15. package/dist/src/client/Client.d.ts.map +1 -1
  16. package/dist/src/client/Client.js +9 -5
  17. package/dist/src/client/Client.js.map +1 -1
  18. package/dist/src/client/Connection.d.ts +26 -30
  19. package/dist/src/client/Connection.d.ts.map +1 -1
  20. package/dist/src/client/Connection.js +31 -38
  21. package/dist/src/client/Connection.js.map +1 -1
  22. package/dist/src/client/PgClient.d.ts +9 -0
  23. package/dist/src/client/PgClient.d.ts.map +1 -0
  24. package/dist/src/client/PgClient.js +3 -0
  25. package/dist/src/client/PgClient.js.map +1 -0
  26. package/dist/src/client/Pool.d.ts +126 -0
  27. package/dist/src/client/Pool.d.ts.map +1 -0
  28. package/dist/src/client/Pool.js +380 -0
  29. package/dist/src/client/Pool.js.map +1 -0
  30. package/dist/src/client/Transaction.d.ts +20 -11
  31. package/dist/src/client/Transaction.d.ts.map +1 -1
  32. package/dist/src/client/Transaction.js +80 -55
  33. package/dist/src/client/Transaction.js.map +1 -1
  34. package/dist/src/client/errors.d.ts +1 -1
  35. package/dist/src/client/errors.d.ts.map +1 -1
  36. package/dist/src/client/errors.js +7 -5
  37. package/dist/src/client/errors.js.map +1 -1
  38. package/dist/src/client/index.d.ts +1 -1
  39. package/dist/src/client/index.d.ts.map +1 -1
  40. package/dist/src/client/index.js +1 -1
  41. package/dist/src/client/index.js.map +1 -1
  42. package/dist/src/index.d.ts +1 -1
  43. package/dist/src/index.d.ts.map +1 -1
  44. package/dist/src/index.js +3 -1
  45. package/dist/src/index.js.map +1 -1
  46. package/dist/src/tsconfig.tsbuildinfo +1 -1
  47. package/dist/src/types.d.ts +4 -1
  48. package/dist/src/types.d.ts.map +1 -1
  49. package/dist/src/utils/Mutex.d.ts +11 -0
  50. package/dist/src/utils/Mutex.d.ts.map +1 -0
  51. package/dist/src/utils/Mutex.js +49 -0
  52. package/dist/src/utils/Mutex.js.map +1 -0
  53. package/dist/src/utils/asyncIterableTransaction.d.ts +7 -0
  54. package/dist/src/utils/asyncIterableTransaction.d.ts.map +1 -0
  55. package/dist/src/utils/asyncIterableTransaction.js +32 -0
  56. package/dist/src/utils/asyncIterableTransaction.js.map +1 -0
  57. package/dist/src/utils/createDatabaseIfNotExists.d.ts +2 -2
  58. package/dist/src/utils/createDatabaseIfNotExists.d.ts.map +1 -1
  59. package/dist/src/utils/createDatabaseIfNotExists.js +2 -2
  60. package/dist/src/utils/createDatabaseIfNotExists.js.map +1 -1
  61. package/dist/src/utils/index.d.ts +3 -0
  62. package/dist/src/utils/index.d.ts.map +1 -1
  63. package/dist/src/utils/index.js +3 -0
  64. package/dist/src/utils/index.js.map +1 -1
  65. package/dist/src/utils/pgClientFactory.d.ts +6 -0
  66. package/dist/src/utils/pgClientFactory.d.ts.map +1 -0
  67. package/dist/src/utils/pgClientFactory.js +12 -0
  68. package/dist/src/utils/pgClientFactory.js.map +1 -0
  69. package/dist/src/utils/sql.d.ts +1 -1
  70. package/dist/src/utils/sql.d.ts.map +1 -1
  71. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts +1 -1
  72. package/dist/src/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
  73. package/dist/src/utils/withDatabaseAdvisoryLock.js +1 -1
  74. package/dist/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
  75. package/dist/tests/cases/unit/connection.test.d.ts +2 -0
  76. package/dist/tests/cases/unit/connection.test.d.ts.map +1 -0
  77. package/dist/tests/cases/unit/connection.test.js +128 -0
  78. package/dist/tests/cases/unit/connection.test.js.map +1 -0
  79. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -0
  80. package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -0
  81. package/dist/tests/cases/unit/createConnectionMockAlt.js +47 -0
  82. package/dist/tests/cases/unit/createConnectionMockAlt.js.map +1 -0
  83. package/dist/tests/cases/unit/eventManager.test.js +91 -17
  84. package/dist/tests/cases/unit/eventManager.test.js.map +1 -1
  85. package/dist/tests/cases/unit/pool.test.d.ts +2 -0
  86. package/dist/tests/cases/unit/pool.test.d.ts.map +1 -0
  87. package/dist/tests/cases/unit/pool.test.js +323 -0
  88. package/dist/tests/cases/unit/pool.test.js.map +1 -0
  89. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  90. package/package.json +4 -4
  91. package/src/builders/DeleteBuilder.ts +1 -1
  92. package/src/builders/InsertBuilder.ts +1 -1
  93. package/src/builders/UpdateBuilder.ts +1 -1
  94. package/src/client/AcquiredConnection.ts +104 -0
  95. package/src/client/Client.ts +34 -18
  96. package/src/client/Connection.ts +57 -63
  97. package/src/client/PgClient.ts +13 -0
  98. package/src/client/Pool.ts +465 -0
  99. package/src/client/Transaction.ts +101 -69
  100. package/src/client/errors.ts +10 -6
  101. package/src/client/index.ts +1 -1
  102. package/src/index.ts +2 -0
  103. package/src/types.ts +4 -1
  104. package/src/utils/Mutex.ts +49 -0
  105. package/src/utils/asyncIterableTransaction.ts +33 -0
  106. package/src/utils/createDatabaseIfNotExists.ts +4 -4
  107. package/src/utils/index.ts +3 -0
  108. package/src/utils/pgClientFactory.ts +11 -0
  109. package/src/utils/withDatabaseAdvisoryLock.ts +4 -4
  110. package/tests/cases/unit/connection.test.ts +154 -0
  111. package/tests/cases/unit/createConnectionMockAlt.ts +44 -0
  112. package/tests/cases/unit/eventManager.test.ts +101 -19
  113. package/tests/cases/unit/pool.test.ts +349 -0
  114. package/dist/src/client/SingleConnection.d.ts +0 -20
  115. package/dist/src/client/SingleConnection.d.ts.map +0 -1
  116. package/dist/src/client/SingleConnection.js +0 -67
  117. package/dist/src/client/SingleConnection.js.map +0 -1
  118. package/dist/src/client/execution.d.ts +0 -8
  119. package/dist/src/client/execution.d.ts.map +0 -1
  120. package/dist/src/client/execution.js +0 -74
  121. package/dist/src/client/execution.js.map +0 -1
  122. package/src/client/SingleConnection.ts +0 -82
  123. package/src/client/execution.ts +0 -93
@@ -0,0 +1,126 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import EventEmitter from 'events';
4
+ import { DatabaseError } from './errors';
5
+ import { PgClientFactory } from '../utils';
6
+ import { PgClient } from './PgClient';
7
+ export declare type PoolLogger = (message: string, status: PoolStatus) => void;
8
+ export declare type PoolConfig = Partial<PoolConfigInternal>;
9
+ interface PoolConfigInternal {
10
+ /** maximum number of connections in a pool */
11
+ maxConnections: number;
12
+ /** maximum number of connections concurrently establishing*/
13
+ maxConnecting: number;
14
+ /** maximum number of idle connections. when reached, will be disposed immediately */
15
+ maxIdle: number;
16
+ /** interval between retries of recoverable errors */
17
+ reconnectIntervalMs: number;
18
+ /** timeout to dispose idle connections */
19
+ idleTimeoutMs: number;
20
+ /** timeout of pending item waiting for a connection. also used for retries of recoverable errors */
21
+ acquireTimeoutMs: number;
22
+ /** how many times can a single connection be acquired */
23
+ maxUses?: number;
24
+ /** max age of connection. when reached, connection will be disposed after returning to a pool */
25
+ maxAgeMs?: number;
26
+ /** internal logging, mainly for debugging and testing */
27
+ log?: PoolLogger;
28
+ }
29
+ export declare type PoolStats = {
30
+ [K in keyof typeof poolStatsDescription]: number;
31
+ };
32
+ export interface PoolStatus {
33
+ /** maximum number of connections in a pool */
34
+ max: number;
35
+ /** number of items waiting for a connections */
36
+ pending: number;
37
+ /** number of active (acquired) connections */
38
+ active: number;
39
+ /** number of available idle connections */
40
+ idle: number;
41
+ /** number of currently establishing connections */
42
+ connecting: number;
43
+ stats: PoolStats;
44
+ }
45
+ export declare const poolStatsDescription: {
46
+ connection_established_count: string;
47
+ connection_recoverable_error_count: string;
48
+ connection_error_count: string;
49
+ connection_disposed_idle_timeout_count: string;
50
+ connection_disposed_idle_max_count: string;
51
+ connection_disposed_old_count: string;
52
+ connection_disposed_manual_count: string;
53
+ connection_released_count: string;
54
+ connection_reused_immediately_count: string;
55
+ connection_reused_later_count: string;
56
+ connection_established_idle_count: string;
57
+ item_queued_count: string;
58
+ item_timeout_count: string;
59
+ item_rejected_count: string;
60
+ item_resolved_new_ms_count: string;
61
+ item_resolved_new_ms_sum: string;
62
+ item_resolved_released_ms_count: string;
63
+ item_resolved_released_ms_sum: string;
64
+ };
65
+ declare class PoolConnection {
66
+ readonly client: PgClient;
67
+ disposed: boolean;
68
+ uses: number;
69
+ createdAt: number;
70
+ timerId: NodeJS.Timeout | undefined;
71
+ constructor(client: PgClient);
72
+ }
73
+ interface Pool {
74
+ on(event: 'error', listener: (err: Error) => void): this;
75
+ on(event: 'recoverableError', listener: (err: Error) => void): this;
76
+ }
77
+ declare class Pool extends EventEmitter {
78
+ private clientFactory;
79
+ /**
80
+ * pool was closed by calling end().
81
+ * All connection was disposed and it is not possible to acquire new one
82
+ */
83
+ private ended;
84
+ /**
85
+ * current count of connection attempts
86
+ * also includes timeout between recoverable retries
87
+ */
88
+ private connectingCount;
89
+ /**
90
+ * available idle connections
91
+ */
92
+ private idle;
93
+ /**
94
+ * currently acquired connections
95
+ */
96
+ private active;
97
+ /**
98
+ * items waiting for released or newly established connection
99
+ */
100
+ private queue;
101
+ private poolConfig;
102
+ private poolStats;
103
+ private lastRecoverableError;
104
+ constructor(clientFactory: PgClientFactory, poolConfig: PoolConfig);
105
+ acquire(): Promise<PoolConnection>;
106
+ release(poolConnection: PoolConnection): void;
107
+ dispose(poolConnection: PoolConnection): void;
108
+ end(): Promise<void>;
109
+ closeIdle(): Promise<void>;
110
+ getPoolStatus(): PoolStatus;
111
+ private maybeCreateNew;
112
+ private createPendingItem;
113
+ private handleAvailableConnection;
114
+ private disposeConnection;
115
+ private log;
116
+ }
117
+ export { Pool };
118
+ export declare class PoolError extends DatabaseError {
119
+ }
120
+ export declare class AcquireTimeoutError extends PoolError {
121
+ constructor(previous: any);
122
+ }
123
+ export declare class PoolClosedError extends PoolError {
124
+ constructor();
125
+ }
126
+ //# sourceMappingURL=Pool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Pool.d.ts","sourceRoot":"","sources":["../../../src/client/Pool.ts"],"names":[],"mappings":";;AAEA,OAAO,YAAY,MAAM,QAAQ,CAAA;AACjC,OAAO,EAAe,aAAa,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAErC,oBAAY,UAAU,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,KAAK,IAAI,CAAA;AAEtE,oBAAY,UAAU,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAEpD,UAAU,kBAAkB;IAC3B,8CAA8C;IAC9C,cAAc,EAAE,MAAM,CAAA;IACtB,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAA;IACrB,qFAAqF;IACrF,OAAO,EAAE,MAAM,CAAA;IACf,qDAAqD;IACrD,mBAAmB,EAAE,MAAM,CAAA;IAC3B,0CAA0C;IAC1C,aAAa,EAAE,MAAM,CAAA;IACrB,oGAAoG;IACpG,gBAAgB,EAAE,MAAM,CAAA;IACxB,yDAAyD;IACzD,OAAO,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;IAE1C;;OAEG;IACH,OAAO,CAAC,KAAK,CAAoB;IAEjC,OAAO,CAAC,UAAU,CAAoB;IAEtC,OAAO,CAAC,SAAS,CAmBhB;IAED,OAAO,CAAC,oBAAoB,CAGf;gBAGJ,aAAa,EAAE,eAAe,EACtC,UAAU,EAAE,UAAU;IAchB,OAAO,IAAI,OAAO,CAAC,cAAc,CAAC;IAsBlC,OAAO,CAAC,cAAc,EAAE,cAAc,GAAG,IAAI;IAuB7C,OAAO,CAAC,cAAc,EAAE,cAAc,GAAG,IAAI;IAiBvC,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;IAWpB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAQhC,aAAa,IAAI,UAAU;YAYpB,cAAc;IAkF5B,OAAO,CAAC,iBAAiB;IA2CzB,OAAO,CAAC,yBAAyB;YAuCnB,iBAAiB;IAY/B,OAAO,CAAC,GAAG;CAKX;AAED,OAAO,EAAE,IAAI,EAAE,CAAA;AAEf,qBAAa,SAAU,SAAQ,aAAa;CAC3C;AAED,qBAAa,mBAAoB,SAAQ,SAAS;gBACrC,QAAQ,EAAE,GAAG;CAGzB;AAED,qBAAa,eAAgB,SAAQ,SAAS;;CAI7C"}
@@ -0,0 +1,380 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PoolClosedError = exports.AcquireTimeoutError = exports.PoolError = exports.Pool = exports.poolStatsDescription = void 0;
7
+ const exceptions_1 = require("../exceptions");
8
+ const errorCodes_1 = require("./errorCodes");
9
+ const events_1 = __importDefault(require("events"));
10
+ const errors_1 = require("./errors");
11
+ exports.poolStatsDescription = {
12
+ connection_established_count: 'Total number of established connections.',
13
+ connection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',
14
+ connection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',
15
+ connection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',
16
+ connection_disposed_idle_max_count: 'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',
17
+ connection_disposed_old_count: 'Number of connections, that was too old after it was released.',
18
+ connection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',
19
+ connection_released_count: 'Number of connection returned to the pool.',
20
+ connection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',
21
+ connection_reused_later_count: 'Number of idle connections, that was reused later.',
22
+ connection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',
23
+ item_queued_count: 'Number of queued items requesting a connection.',
24
+ item_timeout_count: 'Number of items waiting for connection, which timed out.',
25
+ item_rejected_count: 'Number of items rejected with an error.',
26
+ item_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',
27
+ item_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',
28
+ item_resolved_released_ms_count: 'Number of queued items resolved with released connection.',
29
+ item_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',
30
+ };
31
+ class PoolConnection {
32
+ constructor(client) {
33
+ this.client = client;
34
+ this.disposed = false;
35
+ this.uses = 0;
36
+ this.createdAt = Date.now();
37
+ }
38
+ }
39
+ class PendingItem {
40
+ constructor(resolve, reject) {
41
+ this.resolve = resolve;
42
+ this.reject = reject;
43
+ this.createdAt = Date.now();
44
+ }
45
+ }
46
+ class Pool extends events_1.default {
47
+ constructor(clientFactory, poolConfig) {
48
+ var _a, _b;
49
+ super();
50
+ this.clientFactory = clientFactory;
51
+ /**
52
+ * pool was closed by calling end().
53
+ * All connection was disposed and it is not possible to acquire new one
54
+ */
55
+ this.ended = false;
56
+ /**
57
+ * current count of connection attempts
58
+ * also includes timeout between recoverable retries
59
+ */
60
+ this.connectingCount = 0;
61
+ /**
62
+ * available idle connections
63
+ */
64
+ this.idle = [];
65
+ /**
66
+ * currently acquired connections
67
+ */
68
+ this.active = new Set();
69
+ /**
70
+ * items waiting for released or newly established connection
71
+ */
72
+ this.queue = [];
73
+ this.poolStats = {
74
+ connection_established_count: 0,
75
+ connection_recoverable_error_count: 0,
76
+ connection_error_count: 0,
77
+ connection_disposed_idle_timeout_count: 0,
78
+ connection_disposed_idle_max_count: 0,
79
+ connection_disposed_old_count: 0,
80
+ connection_disposed_manual_count: 0,
81
+ connection_released_count: 0,
82
+ connection_reused_immediately_count: 0,
83
+ connection_reused_later_count: 0,
84
+ connection_established_idle_count: 0,
85
+ item_queued_count: 0,
86
+ item_timeout_count: 0,
87
+ item_rejected_count: 0,
88
+ item_resolved_new_ms_count: 0,
89
+ item_resolved_new_ms_sum: 0,
90
+ item_resolved_released_ms_count: 0,
91
+ item_resolved_released_ms_sum: 0,
92
+ };
93
+ this.poolConfig = {
94
+ maxConnections: 10,
95
+ maxConnecting: Math.ceil(((_a = poolConfig.maxConnections) !== null && _a !== void 0 ? _a : 10) / 2),
96
+ maxIdle: Math.ceil(((_b = poolConfig.maxConnections) !== null && _b !== void 0 ? _b : 10) / 2),
97
+ idleTimeoutMs: 10000,
98
+ acquireTimeoutMs: 10000,
99
+ reconnectIntervalMs: 100,
100
+ ...poolConfig,
101
+ };
102
+ }
103
+ acquire() {
104
+ if (this.ended) {
105
+ throw new PoolClosedError();
106
+ }
107
+ const poolConnection = this.idle.pop();
108
+ if (poolConnection !== undefined) {
109
+ if (poolConnection.timerId) {
110
+ clearTimeout(poolConnection.timerId);
111
+ }
112
+ poolConnection.uses++;
113
+ this.active.add(poolConnection);
114
+ this.poolStats.connection_reused_later_count++;
115
+ this.log('Item fulfilled with an idle connection.');
116
+ return Promise.resolve(poolConnection);
117
+ }
118
+ const pendingItem = this.createPendingItem();
119
+ this.maybeCreateNew();
120
+ return pendingItem;
121
+ }
122
+ release(poolConnection) {
123
+ if (this.ended) {
124
+ return;
125
+ }
126
+ this.log('Releasing a connection.');
127
+ if (!this.active.delete(poolConnection)) {
128
+ throw new exceptions_1.ImplementationException('Connection does not belong to this pool.');
129
+ }
130
+ if ((this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)
131
+ || (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())) {
132
+ setImmediate(async () => {
133
+ await this.disposeConnection(poolConnection);
134
+ this.poolStats.connection_disposed_old_count++;
135
+ this.log('Connection has reached max age or usage and was disposed.');
136
+ });
137
+ this.maybeCreateNew();
138
+ return;
139
+ }
140
+ this.handleAvailableConnection(poolConnection);
141
+ }
142
+ dispose(poolConnection) {
143
+ if (this.ended) {
144
+ return;
145
+ }
146
+ this.poolStats.connection_disposed_manual_count++;
147
+ this.log('Releasing and disposing a connection.');
148
+ if (!this.active.delete(poolConnection)) {
149
+ throw new exceptions_1.ImplementationException('Connection does not belong to this pool.');
150
+ }
151
+ setImmediate(async () => {
152
+ await this.disposeConnection(poolConnection);
153
+ this.log('Connection errored and was disposed.');
154
+ });
155
+ this.maybeCreateNew();
156
+ }
157
+ async end() {
158
+ this.ended = true;
159
+ this.queue.forEach(it => it.reject(new PoolClosedError()));
160
+ this.queue = [];
161
+ const allConnections = [...this.idle, ...Array.from(this.active)];
162
+ await Promise.allSettled(allConnections.map(it => this.disposeConnection(it)));
163
+ this.idle = [];
164
+ this.active.clear();
165
+ }
166
+ async closeIdle() {
167
+ this.log('Disposing all idle connection on request.');
168
+ const idle = this.idle;
169
+ this.idle = [];
170
+ await Promise.allSettled(idle.map(it => this.disposeConnection(it)));
171
+ }
172
+ getPoolStatus() {
173
+ return {
174
+ max: this.poolConfig.maxConnections,
175
+ active: this.active.size,
176
+ idle: this.idle.length,
177
+ pending: this.queue.length,
178
+ connecting: this.connectingCount,
179
+ stats: this.poolStats,
180
+ };
181
+ }
182
+ async maybeCreateNew(attempt = 1) {
183
+ if (this.ended) {
184
+ return;
185
+ }
186
+ if (this.queue.length === 0) {
187
+ this.log('Not connecting, queue is empty.');
188
+ return;
189
+ }
190
+ const connectingCount = this.connectingCount;
191
+ if (connectingCount >= this.queue.length) {
192
+ this.log('Not connecting, already establishing connection for all queued items.');
193
+ return;
194
+ }
195
+ const idleCount = this.idle.length;
196
+ if ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {
197
+ this.log('Not connecting, max connections reached.');
198
+ return;
199
+ }
200
+ if (connectingCount >= this.poolConfig.maxConnecting) {
201
+ this.log('Not connecting, maximum concurrent connection attempts in progress.');
202
+ return;
203
+ }
204
+ this.log('Creating a new connection');
205
+ const client = this.clientFactory();
206
+ this.connectingCount++;
207
+ const poolConnection = new PoolConnection(client);
208
+ client.on('error', e => {
209
+ this.log('Client error on idle connection has occurred: ' + e.message);
210
+ this.emit('error', e);
211
+ });
212
+ try {
213
+ await client.connect();
214
+ this.poolStats.connection_established_count++;
215
+ this.log('Connection established');
216
+ this.connectingCount--;
217
+ if (this.ended) {
218
+ await this.disposeConnection(poolConnection);
219
+ return;
220
+ }
221
+ }
222
+ catch (e) {
223
+ this.log('Connection error occurred: ' + e.message);
224
+ try {
225
+ await client.end();
226
+ }
227
+ catch (_a) {
228
+ }
229
+ if (e.code === errorCodes_1.ClientErrorCodes.TOO_MANY_CONNECTIONS || e.code === errorCodes_1.ClientErrorCodes.CANNOT_CONNECT_NOW) {
230
+ this.lastRecoverableError = { error: e, time: Date.now() };
231
+ if (this.poolConfig.reconnectIntervalMs * attempt >= this.poolConfig.acquireTimeoutMs) {
232
+ this.poolStats.connection_error_count++;
233
+ this.log('Recoverable error, max retries reached.');
234
+ this.emit('error', e);
235
+ this.connectingCount--;
236
+ }
237
+ else {
238
+ this.poolStats.connection_recoverable_error_count++;
239
+ this.log('Recoverable error, retrying in a moment.');
240
+ this.emit('recoverableError', e);
241
+ setTimeout(() => {
242
+ this.connectingCount--;
243
+ this.log('Retrying');
244
+ this.maybeCreateNew(attempt + 1);
245
+ }, this.poolConfig.reconnectIntervalMs);
246
+ }
247
+ }
248
+ else {
249
+ this.poolStats.connection_error_count++;
250
+ this.connectingCount--;
251
+ if (this.active.size === 0 && this.queue.length > 0) {
252
+ const pendingItem = this.queue.shift();
253
+ if (!pendingItem)
254
+ throw new Error();
255
+ this.log('Connecting failed, rejecting pending item');
256
+ pendingItem.reject(new errors_1.ClientError(e));
257
+ this.poolStats.item_rejected_count++;
258
+ }
259
+ else {
260
+ this.log('Connecting failed, emitting error');
261
+ this.emit('error', e);
262
+ }
263
+ }
264
+ return;
265
+ }
266
+ this.handleAvailableConnection(poolConnection);
267
+ this.maybeCreateNew();
268
+ }
269
+ createPendingItem() {
270
+ return new Promise((resolve, reject) => {
271
+ const timeout = setTimeout(() => {
272
+ const acquireTimeoutError = new AcquireTimeoutError(this.lastRecoverableError && this.lastRecoverableError.time > item.createdAt
273
+ ? this.lastRecoverableError.error
274
+ : undefined);
275
+ item.reject(acquireTimeoutError);
276
+ const index = this.queue.indexOf(item);
277
+ if (index > -1) {
278
+ this.queue.splice(index, 1);
279
+ }
280
+ this.poolStats.item_timeout_count++;
281
+ this.log('Queued item timed out');
282
+ }, this.poolConfig.acquireTimeoutMs);
283
+ const item = new PendingItem(it => {
284
+ const duration = Date.now() - item.createdAt;
285
+ const isNew = it.uses === 0;
286
+ this.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`);
287
+ if (isNew) {
288
+ this.poolStats.item_resolved_new_ms_count++;
289
+ this.poolStats.item_resolved_new_ms_sum += duration;
290
+ }
291
+ else {
292
+ this.poolStats.item_resolved_released_ms_count++;
293
+ this.poolStats.item_resolved_released_ms_sum += duration;
294
+ }
295
+ clearTimeout(timeout);
296
+ resolve(it);
297
+ }, it => {
298
+ clearTimeout(timeout);
299
+ reject(it);
300
+ });
301
+ this.poolStats.item_queued_count++;
302
+ this.queue.push(item);
303
+ this.log(`Item added to a queue.`);
304
+ });
305
+ }
306
+ handleAvailableConnection(poolConnection) {
307
+ const item = this.queue.shift();
308
+ const isNew = poolConnection.uses === 0;
309
+ if (!isNew) {
310
+ this.poolStats.connection_released_count++;
311
+ }
312
+ if (item) {
313
+ this.active.add(poolConnection);
314
+ item.resolve(poolConnection);
315
+ if (!isNew) {
316
+ this.poolStats.connection_reused_immediately_count++;
317
+ }
318
+ poolConnection.uses++;
319
+ return;
320
+ }
321
+ if (isNew) {
322
+ this.poolStats.connection_established_idle_count++;
323
+ }
324
+ if (this.idle.length >= this.poolConfig.maxIdle) {
325
+ setImmediate(async () => {
326
+ await this.disposeConnection(poolConnection);
327
+ this.poolStats.connection_disposed_idle_max_count++;
328
+ this.log('Too many idle connections, connection disposed.');
329
+ });
330
+ }
331
+ else {
332
+ poolConnection.timerId = setTimeout(async () => {
333
+ const index = this.idle.indexOf(poolConnection);
334
+ if (index > -1) {
335
+ this.idle.splice(index, 1);
336
+ await this.disposeConnection(poolConnection);
337
+ this.poolStats.connection_disposed_idle_timeout_count++;
338
+ this.log('Idle connection disposed after timeout.');
339
+ }
340
+ }, this.poolConfig.idleTimeoutMs);
341
+ this.idle.push(poolConnection);
342
+ this.log('Connection is idle and available.');
343
+ }
344
+ }
345
+ async disposeConnection(connection) {
346
+ try {
347
+ if (connection.disposed) {
348
+ throw new PoolError('Connection is already disposed');
349
+ }
350
+ connection.disposed = true;
351
+ await connection.client.end();
352
+ }
353
+ catch (e) {
354
+ this.on('error', e);
355
+ }
356
+ }
357
+ log(message) {
358
+ if (!this.poolConfig.log)
359
+ return;
360
+ const poolStatus = this.getPoolStatus();
361
+ this.poolConfig.log(message, poolStatus);
362
+ }
363
+ }
364
+ exports.Pool = Pool;
365
+ class PoolError extends errors_1.DatabaseError {
366
+ }
367
+ exports.PoolError = PoolError;
368
+ class AcquireTimeoutError extends PoolError {
369
+ constructor(previous) {
370
+ super('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous);
371
+ }
372
+ }
373
+ exports.AcquireTimeoutError = AcquireTimeoutError;
374
+ class PoolClosedError extends PoolError {
375
+ constructor() {
376
+ super('Pool is already closed');
377
+ }
378
+ }
379
+ exports.PoolClosedError = Pool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AA;YAC9B,IAAI,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAA;SAC7C;IACF,CAAC;IAEO,KAAK,CAAC,iBAAiB,CAAC,UAA0B;QACzD,IAAI;YACH,IAAI,UAAU,CAAC,QAAQ,EAAE;gBACxB,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAA;aACrD;YACD,UAAU,CAAC,QAAQ,GAAG,IAAI,CAAA;YAC1B,MAAM,UAAU,CAAC,MAAM,CAAC,GAAG,EAAE,CAAA;SAC7B;QAAC,OAAO,CAAM,EAAE;YAChB,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;SACnB;IACF,CAAC;IAEO,GAAG,CAAC,OAAe;QAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG;YAAE,OAAM;QAChC,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,CAAA;QACvC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;IACzC,CAAC;CACD;AAEQ,oBAAI;AAEb,MAAa,SAAU,SAAQ,sBAAa;CAC3C;AADD,8BACC;AAED,MAAa,mBAAoB,SAAQ,SAAS;IACjD,YAAY,QAAa;QACxB,KAAK,CAAC,gCAAgC,GAAG,CAAC,QAAQ,IAAI,SAAS,IAAI,QAAQ,CAAC,CAAC,CAAC,iBAAiB,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAA;IACnI,CAAC;CACD;AAJD,kDAIC;AAED,MAAa,eAAgB,SAAQ,SAAS;IAC7C;QACC,KAAK,CAAC,wBAAwB,CAAC,CAAA;IAChC,CAAC;CACD;AAJD,0CAIC"}
@@ -1,23 +1,32 @@
1
1
  import { Connection } from './Connection';
2
2
  import { EventManager } from './EventManager';
3
- import { ClientBase } from 'pg';
4
3
  export declare class Transaction implements Connection.TransactionLike {
5
- private readonly pgClient;
6
- readonly eventManager: EventManager;
7
- private readonly config;
8
- private _isClosed;
9
- private queryContext;
10
- private savepointCounter;
4
+ private readonly connection;
5
+ private readonly savepointManager;
6
+ private readonly state;
11
7
  get isClosed(): boolean;
12
- constructor(pgClient: ClientBase, eventManager: EventManager, config: Connection.QueryConfig);
8
+ constructor(connection: Connection.ConnectionLike, savepointManager?: SavepointState, state?: TransactionLikeState);
9
+ get eventManager(): EventManager;
10
+ scope<Result>(callback: (connection: Connection.TransactionLike) => Promise<Result> | Result, { eventManager }?: {
11
+ eventManager?: EventManager;
12
+ }): Promise<Result>;
13
13
  transaction<Result>(callback: (connection: Connection.TransactionLike) => Promise<Result> | Result, options?: {
14
14
  eventManager?: EventManager;
15
15
  }): Promise<Result>;
16
- query<Row extends Record<string, any>>(sql: string, parameters?: any[], meta?: Record<string, any>, config?: Connection.QueryConfig): Promise<Connection.Result<Row>>;
16
+ query<Row extends Record<string, any>>(sql: string, parameters?: any[], meta?: Record<string, any>): Promise<Connection.Result<Row>>;
17
17
  rollback(): Promise<void>;
18
- rollbackUnclosed(): Promise<void>;
19
18
  commit(): Promise<void>;
20
- commitUnclosed(): Promise<void>;
21
19
  private close;
22
20
  }
21
+ declare class TransactionLikeState {
22
+ private _isClosed;
23
+ get isClosed(): boolean;
24
+ close(): void;
25
+ }
26
+ declare class SavepointState {
27
+ counter: number;
28
+ execute<Result>(connection: Connection.ConnectionLike, callback: (connection: Connection.TransactionLike) => Promise<Result> | Result): Promise<Result>;
29
+ }
30
+ export declare const executeTransaction: <Result>(transaction: Connection.TransactionLike, callback: (connection: Connection.TransactionLike) => Result | Promise<Result>) => Promise<Result>;
31
+ export {};
23
32
  //# sourceMappingURL=Transaction.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Transaction.d.ts","sourceRoot":"","sources":["../../../src/client/Transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,C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