-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpool.mjs
More file actions
327 lines (300 loc) · 8.97 KB
/
pool.mjs
File metadata and controls
327 lines (300 loc) · 8.97 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/**
* Connection pool for hyperdb-api-node.
*
* Manages a pool of reusable database connections with configurable
* min/max size, idle timeout, and automatic health checking.
*
* @module hyperdb-api-node/pool
*
* @example
* ```js
* import { ConnectionPool } from 'hyperdb-api-node/pool.mjs';
*
* const pool = new ConnectionPool(hyper.endpoint, 'data.hyper', {
* min: 2,
* max: 10,
* idleTimeoutMs: 30_000,
* });
*
* // Auto acquire/release
* const rows = await pool.query('SELECT * FROM users WHERE id = $1', [42]);
*
* // Manual acquire/release
* const conn = await pool.acquire();
* try {
* await conn.executeCommand('INSERT INTO logs VALUES (1, \'hello\')');
* } finally {
* pool.release(conn);
* }
*
* await pool.close();
* ```
*/
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { Connection, CreateMode } = require('./index.js');
/**
* A connection pool that manages reusable Hyper database connections.
*/
export class ConnectionPool {
#endpoint;
#databasePath;
#createMode;
#min;
#max;
#idleTimeoutMs;
#idle = []; // { conn, lastUsed }
#active = new Set();
#waiting = []; // { resolve, reject, timer } waiting for a connection
#closed = false;
#idleTimer = null;
#acquireTimeoutMs;
/**
* Creates a new connection pool.
*
* Connections are created lazily on first `acquire()` call.
*
* @param {string} endpoint - Hyper server endpoint (e.g., "localhost:7483").
* @param {string} databasePath - Path to the .hyper database file.
* @param {object} [options] - Pool configuration.
* @param {number} [options.min=0] - Minimum idle connections to maintain.
* @param {number} [options.max=10] - Maximum total connections.
* @param {number} [options.idleTimeoutMs=30000] - Close idle connections after this many ms.
* @param {number} [options.acquireTimeoutMs=30000] - Max ms to wait for a connection (0 = no limit).
* @param {string} [options.createMode='CreateIfNotExists'] - Database creation mode.
*/
constructor(endpoint, databasePath, options = {}) {
this.#endpoint = endpoint;
this.#databasePath = databasePath;
this.#min = options.min ?? 0;
this.#max = options.max ?? 10;
this.#idleTimeoutMs = options.idleTimeoutMs ?? 30_000;
this.#acquireTimeoutMs = options.acquireTimeoutMs ?? 30_000;
this.#createMode = options.createMode ?? CreateMode.CreateIfNotExists;
if (this.#idleTimeoutMs > 0) {
this.#idleTimer = setInterval(() => this.#evictIdle(), this.#idleTimeoutMs / 2);
this.#idleTimer.unref(); // Don't prevent process exit
}
}
/**
* Total number of connections (idle + active).
* @type {number}
*/
get size() {
return this.#idle.length + this.#active.size;
}
/**
* Number of idle (available) connections.
* @type {number}
*/
get idle() {
return this.#idle.length;
}
/**
* Number of active (in-use) connections.
* @type {number}
*/
get active() {
return this.#active.size;
}
/**
* Number of callers waiting for a connection.
* @type {number}
*/
get pending() {
return this.#waiting.length;
}
/**
* Acquires a connection from the pool.
*
* If an idle connection is available, it is returned immediately.
* If the pool is at max capacity, the call waits until a connection
* is released. Otherwise, a new connection is created.
*
* @returns {Promise<import('./index.js').Connection>} A database connection.
*/
async acquire() {
if (this.#closed) throw new Error('Pool is closed');
// Try to reuse an idle connection
while (this.#idle.length > 0) {
const { conn } = this.#idle.pop();
try {
if (conn.isAlive) {
this.#active.add(conn);
return conn;
}
} catch {
// Connection is dead, discard and try next
}
try { await conn.close(); } catch {}
}
// Create a new connection if below max
if (this.size < this.#max) {
const conn = await Connection.connect(
this.#endpoint,
this.#databasePath,
this.#createMode,
);
this.#active.add(conn);
return conn;
}
// At max capacity — wait for a release (with timeout)
return new Promise((resolve, reject) => {
const entry = { resolve, reject, timer: null };
if (this.#acquireTimeoutMs > 0) {
entry.timer = setTimeout(() => {
if (this.#closed) {
reject(new Error('Pool is closed'));
return;
}
const idx = this.#waiting.indexOf(entry);
if (idx !== -1) this.#waiting.splice(idx, 1);
reject(new Error(`Pool acquire timeout after ${this.#acquireTimeoutMs}ms`));
}, this.#acquireTimeoutMs);
}
this.#waiting.push(entry);
});
}
/**
* Returns a connection to the pool.
*
* The connection becomes available for reuse by other callers.
*
* @param {import('./index.js').Connection} conn - The connection to release.
*/
release(conn) {
if (!this.#active.has(conn)) {
if (process.env.NODE_ENV !== 'production') {
console.warn('hyperdb-api-node/pool: release() called on a connection not owned by this pool (possible double-release)');
}
return;
}
this.#active.delete(conn);
if (this.#closed) {
conn.close().catch(() => {});
return;
}
// If someone is waiting, hand the connection directly to them
if (this.#waiting.length > 0) {
const waiter = this.#waiting.shift();
if (waiter.timer) clearTimeout(waiter.timer);
this.#active.add(conn);
waiter.resolve(conn);
return;
}
// Return to idle pool
this.#idle.push({ conn, lastUsed: Date.now() });
}
/**
* Executes a callback with an auto-managed connection.
*
* The connection is automatically acquired before and released after
* the callback completes (or throws).
*
* @template T
* @param {(conn: import('./index.js').Connection) => Promise<T>} fn - Callback receiving the connection.
* @returns {Promise<T>} The callback's return value.
*
* @example
* ```js
* const rows = await pool.use(async (conn) => {
* return conn.executeQuery('SELECT * FROM users');
* });
* ```
*/
async use(fn) {
const conn = await this.acquire();
try {
return await fn(conn);
} finally {
this.release(conn);
}
}
/**
* Shorthand: execute a query using a pooled connection.
*
* @param {string} sql - SQL query.
* @returns {Promise<import('./index.js').RowData[]>} Query results.
*/
async query(sql) {
return this.use((conn) => conn.executeQuery(sql));
}
/**
* Shorthand: run a parameterized query via a server-side prepared
* statement on a pooled connection.
*
* @param {string} sql - SQL with $1, $2 placeholders.
* @param {Array} params - Parameter values (bool / number / bigint / string / null).
* @returns {Promise<import('./index.js').RowData[]>} Query results.
*/
async queryParams(sql, params) {
return this.use(async (conn) => {
const stmt = conn.prepare(sql);
try {
return await stmt.query(params);
} finally {
await stmt.close().catch(() => {});
}
});
}
/**
* Shorthand: execute a command using a pooled connection.
*
* @param {string} sql - SQL command.
* @returns {Promise<number>} Affected row count.
*/
async command(sql) {
return this.use((conn) => conn.executeCommand(sql));
}
/**
* Closes all connections and shuts down the pool.
*
* After calling this, no further operations are allowed.
*/
async close() {
this.#closed = true;
if (this.#idleTimer) {
clearInterval(this.#idleTimer);
this.#idleTimer = null;
}
// Reject waiting callers
for (const waiter of this.#waiting) {
if (waiter.timer) clearTimeout(waiter.timer);
waiter.reject(new Error('Pool is closed'));
}
this.#waiting = [];
// Close all idle connections
const closePromises = [];
for (const { conn } of this.#idle) {
closePromises.push(conn.close().catch(() => {}));
}
this.#idle = [];
// Close all active connections
for (const conn of this.#active) {
closePromises.push(conn.close().catch(() => {}));
}
this.#active.clear();
await Promise.all(closePromises);
}
/** Evicts idle connections that have been unused longer than idleTimeoutMs. */
#evictIdle() {
const now = Date.now();
const keep = [];
const evict = [];
for (const entry of this.#idle) {
if (now - entry.lastUsed > this.#idleTimeoutMs) {
evict.push(entry);
} else {
keep.push(entry);
}
}
// Only evict excess connections — always retain at least #min idle
while (evict.length > 0 && keep.length + evict.length > this.#min) {
const entry = evict.pop();
entry.conn.close().catch(() => {});
}
// Remaining stale connections that can't be evicted go back to keep
keep.push(...evict);
this.#idle = keep;
}
}