-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
replication-pool.ts
239 lines (189 loc) · 6.59 KB
/
replication-pool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { pojo, shallowClonePojo } from '@sequelize/utils';
import { Pool, TimeoutError } from 'sequelize-pool';
import type { Class } from 'type-fest';
import { logger } from '../utils/logger.js';
const debug = logger.debugContext('pool');
export type ConnectionType = 'read' | 'write';
export interface ReplicationPoolOptions {
/**
* Maximum number of connections in pool. Default is 5
*/
max: number;
/**
* Minimum number of connections in pool. Default is 0
*/
min: number;
/**
* The maximum time, in milliseconds, that a connection can be idle before being released
*/
idle: number;
/**
* The maximum time, in milliseconds, that pool will try to get connection before throwing error
*/
acquire: number;
/**
* The time interval, in milliseconds, after which sequelize-pool will remove idle connections.
*/
evict: number;
/**
* The number of times to use a connection before closing and replacing it. Default is Infinity
*/
maxUses: number;
}
export interface AcquireConnectionOptions {
/**
* Set which replica to use. Available options are `read` and `write`
*/
type?: 'read' | 'write';
/**
* Force master or write replica to get connection from
*/
useMaster?: boolean;
}
interface ReplicationPoolConfig<Connection extends object, ConnectionOptions extends object> {
readConfig: readonly ConnectionOptions[] | null;
writeConfig: ConnectionOptions;
pool: ReplicationPoolOptions;
// TODO: move this option to sequelize-pool so it applies to sub-pools as well
timeoutErrorClass?: Class<Error>;
connect(options: ConnectionOptions): Promise<Connection>;
disconnect(connection: Connection): Promise<void>;
validate(connection: Connection): boolean;
beforeAcquire?(options: AcquireConnectionOptions): Promise<void>;
afterAcquire?(connection: Connection, options: AcquireConnectionOptions): Promise<void>;
}
const owningPools = new WeakMap<object, 'read' | 'write'>();
export class ReplicationPool<Connection extends object, ConnectionOptions extends object> {
/**
* Replication read pool. Will only be used if the 'read' replication option has been provided,
* otherwise the {@link write} will be used instead.
*/
readonly read: Pool<Connection> | null;
readonly write: Pool<Connection>;
readonly #timeoutErrorClass: Class<TimeoutError> | undefined;
readonly #beforeAcquire: ((options: AcquireConnectionOptions) => Promise<void>) | undefined;
readonly #afterAcquire:
| ((connection: Connection, options: AcquireConnectionOptions) => Promise<void>)
| undefined;
constructor(config: ReplicationPoolConfig<Connection, ConnectionOptions>) {
const {
connect,
disconnect,
validate,
beforeAcquire,
afterAcquire,
timeoutErrorClass,
readConfig,
writeConfig,
} = config;
this.#beforeAcquire = beforeAcquire;
this.#afterAcquire = afterAcquire;
this.#timeoutErrorClass = timeoutErrorClass;
if (!readConfig || readConfig.length === 0) {
// no replication, the write pool will always be used instead
this.read = null;
} else {
let reads = 0;
this.read = new Pool({
name: 'sequelize:read',
create: async () => {
// round robin config
const nextRead = reads++ % readConfig.length;
const connection = await connect(readConfig[nextRead]);
owningPools.set(connection, 'read');
return connection;
},
destroy: disconnect,
validate,
max: config.pool.max,
min: config.pool.min,
acquireTimeoutMillis: config.pool.acquire,
idleTimeoutMillis: config.pool.idle,
reapIntervalMillis: config.pool.evict,
maxUses: config.pool.maxUses,
});
}
this.write = new Pool({
name: 'sequelize:write',
create: async () => {
const connection = await connect(writeConfig);
owningPools.set(connection, 'write');
return connection;
},
destroy: disconnect,
validate,
max: config.pool.max,
min: config.pool.min,
acquireTimeoutMillis: config.pool.acquire,
idleTimeoutMillis: config.pool.idle,
reapIntervalMillis: config.pool.evict,
maxUses: config.pool.maxUses,
});
if (!this.read) {
debug(`pool created with max/min: ${config.pool.max}/${config.pool.min}, no replication`);
} else {
debug(`pool created with max/min: ${config.pool.max}/${config.pool.min}, with replication`);
}
}
async acquire(options?: AcquireConnectionOptions | undefined) {
options = options ? shallowClonePojo(options) : pojo();
await this.#beforeAcquire?.(options);
Object.freeze(options);
const { useMaster = false, type = 'write' } = options;
if (type !== 'read' && type !== 'write') {
throw new Error(`Expected queryType to be either read or write. Received ${type}`);
}
const pool = this.read != null && type === 'read' && !useMaster ? this.read : this.write;
let connection;
try {
connection = await pool.acquire();
} catch (error) {
if (this.#timeoutErrorClass && error instanceof TimeoutError) {
throw new this.#timeoutErrorClass(error.message, { cause: error });
}
throw error;
}
await this.#afterAcquire?.(connection, options);
return connection;
}
release(client: Connection): void {
const connectionType = owningPools.get(client);
if (!connectionType) {
throw new Error('Unable to determine to which pool the connection belongs');
}
this.getPool(connectionType).release(client);
}
async destroy(client: Connection): Promise<void> {
const connectionType = owningPools.get(client);
if (!connectionType) {
throw new Error('Unable to determine to which pool the connection belongs');
}
await this.getPool(connectionType).destroy(client);
debug('connection destroy');
}
async destroyAllNow() {
await Promise.all([this.read?.destroyAllNow(), this.write.destroyAllNow()]);
debug('all connections destroyed');
}
async drain() {
await Promise.all([this.write.drain(), this.read?.drain()]);
}
getPool(poolType: ConnectionType): Pool<Connection> {
if (poolType === 'read' && this.read != null) {
return this.read;
}
return this.write;
}
get size(): number {
return (this.read?.size ?? 0) + this.write.size;
}
get available(): number {
return (this.read?.available ?? 0) + this.write.available;
}
get using(): number {
return (this.read?.using ?? 0) + this.write.using;
}
get waiting(): number {
return (this.read?.waiting ?? 0) + this.write.waiting;
}
}