@elizaos/plugin-sql 1.0.0-beta.45 → 1.0.0-beta.47
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/chunk-EYE2J2N6.js +346 -0
- package/dist/{chunk-K7ZVMPCJ.js.map → chunk-EYE2J2N6.js.map} +1 -1
- package/dist/index.js +2483 -10
- package/dist/index.js.map +1 -1
- package/dist/migrate.js +54 -1
- package/dist/migrate.js.map +1 -1
- package/package.json +16 -7
- package/dist/chunk-K7ZVMPCJ.js +0 -2
- package/dist/index.d.ts +0 -30
- package/dist/migrate.d.ts +0 -2
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// src/pglite/manager.ts
|
|
5
|
+
import { dirname as pathDirname, resolve as pathResolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
8
|
+
import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
|
|
9
|
+
import { vector } from "@electric-sql/pglite/vector";
|
|
10
|
+
import { logger } from "@elizaos/core";
|
|
11
|
+
import { drizzle } from "drizzle-orm/pglite";
|
|
12
|
+
import { migrate } from "drizzle-orm/pglite/migrator";
|
|
13
|
+
var PGliteClientManager = class {
|
|
14
|
+
static {
|
|
15
|
+
__name(this, "PGliteClientManager");
|
|
16
|
+
}
|
|
17
|
+
client;
|
|
18
|
+
shuttingDown = false;
|
|
19
|
+
shutdownTimeout = 500;
|
|
20
|
+
/**
|
|
21
|
+
* Constructor for creating a new instance of PGlite with the provided options.
|
|
22
|
+
* Initializes the PGlite client with additional extensions.
|
|
23
|
+
* @param {PGliteOptions} options - The options to configure the PGlite client.
|
|
24
|
+
*/
|
|
25
|
+
constructor(options) {
|
|
26
|
+
this.client = new PGlite({
|
|
27
|
+
...options,
|
|
28
|
+
extensions: {
|
|
29
|
+
vector,
|
|
30
|
+
fuzzystrmatch
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
this.setupShutdownHandlers();
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Retrieves the PostgreSQL lite connection.
|
|
37
|
+
*
|
|
38
|
+
* @returns {PGlite} The PostgreSQL lite connection.
|
|
39
|
+
* @throws {Error} If the client manager is currently shutting down.
|
|
40
|
+
*/
|
|
41
|
+
getConnection() {
|
|
42
|
+
if (this.shuttingDown) {
|
|
43
|
+
throw new Error("Client manager is shutting down");
|
|
44
|
+
}
|
|
45
|
+
return this.client;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Initiates a graceful shutdown of the PGlite client.
|
|
49
|
+
* Checks if the client is already in the process of shutting down.
|
|
50
|
+
* Logs the start of shutdown process and sets shuttingDown flag to true.
|
|
51
|
+
* Sets a timeout for the shutdown process and forces closure of database connection if timeout is reached.
|
|
52
|
+
* Handles the shutdown process, closes the client connection, clears the timeout, and logs the completion of shutdown.
|
|
53
|
+
* Logs any errors that occur during the shutdown process.
|
|
54
|
+
*/
|
|
55
|
+
async gracefulShutdown() {
|
|
56
|
+
if (this.shuttingDown) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
this.shuttingDown = true;
|
|
60
|
+
logger.info("Starting graceful shutdown of PGlite client...");
|
|
61
|
+
const timeout = setTimeout(() => {
|
|
62
|
+
logger.warn("Shutdown timeout reached, forcing database connection closure...");
|
|
63
|
+
this.client.close().finally(() => {
|
|
64
|
+
process.exit(1);
|
|
65
|
+
});
|
|
66
|
+
}, this.shutdownTimeout);
|
|
67
|
+
try {
|
|
68
|
+
await this.client.close();
|
|
69
|
+
clearTimeout(timeout);
|
|
70
|
+
logger.info("PGlite client shutdown completed successfully");
|
|
71
|
+
process.exit(0);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
logger.error("Error during graceful shutdown:", error);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Sets up shutdown handlers for SIGINT, SIGTERM, and beforeExit events to gracefully shutdown the application.
|
|
79
|
+
* @private
|
|
80
|
+
*/
|
|
81
|
+
setupShutdownHandlers() {
|
|
82
|
+
process.on("SIGINT", async () => {
|
|
83
|
+
await this.gracefulShutdown();
|
|
84
|
+
});
|
|
85
|
+
process.on("SIGTERM", async () => {
|
|
86
|
+
await this.gracefulShutdown();
|
|
87
|
+
});
|
|
88
|
+
process.on("beforeExit", async () => {
|
|
89
|
+
await this.gracefulShutdown();
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Initializes the client for PGlite.
|
|
94
|
+
*
|
|
95
|
+
* @returns {Promise<void>} A Promise that resolves when the client is initialized successfully
|
|
96
|
+
*/
|
|
97
|
+
async initialize() {
|
|
98
|
+
try {
|
|
99
|
+
await this.client.waitReady;
|
|
100
|
+
logger.info("PGlite client initialized successfully");
|
|
101
|
+
} catch (error) {
|
|
102
|
+
logger.error("Failed to initialize PGlite client:", error);
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Asynchronously closes the resource. If the resource is not already shutting down,
|
|
108
|
+
* it performs a graceful shutdown before closing.
|
|
109
|
+
*
|
|
110
|
+
* @returns A promise that resolves once the resource has been closed.
|
|
111
|
+
*/
|
|
112
|
+
async close() {
|
|
113
|
+
if (!this.shuttingDown) {
|
|
114
|
+
await this.gracefulShutdown();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Check if the system is currently shutting down.
|
|
119
|
+
*
|
|
120
|
+
* @returns {boolean} True if the system is shutting down, false otherwise.
|
|
121
|
+
*/
|
|
122
|
+
isShuttingDown() {
|
|
123
|
+
return this.shuttingDown;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Asynchronously runs database migrations using Drizzle.
|
|
127
|
+
*
|
|
128
|
+
* Drizzle will first check if the migrations are already applied.
|
|
129
|
+
* If there is a diff between database schema and migrations, it will apply the migrations.
|
|
130
|
+
* If they are already applied, it will skip them.
|
|
131
|
+
*
|
|
132
|
+
* @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.
|
|
133
|
+
*/
|
|
134
|
+
async runMigrations() {
|
|
135
|
+
try {
|
|
136
|
+
const db = drizzle(this.client);
|
|
137
|
+
const packageJsonUrl = await import.meta.resolve("@elizaos/plugin-sql/package.json");
|
|
138
|
+
const packageJsonPath = fileURLToPath(packageJsonUrl);
|
|
139
|
+
const packageRoot = pathDirname(packageJsonPath);
|
|
140
|
+
const migrationsPath = pathResolve(packageRoot, "drizzle/migrations");
|
|
141
|
+
logger.debug(
|
|
142
|
+
`Resolved migrations path (pglite) using import.meta.resolve: ${migrationsPath}`
|
|
143
|
+
);
|
|
144
|
+
await migrate(db, {
|
|
145
|
+
migrationsFolder: migrationsPath,
|
|
146
|
+
migrationsSchema: "public"
|
|
147
|
+
});
|
|
148
|
+
} catch (error) {
|
|
149
|
+
logger.error("Failed to run database migrations (pglite):", error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// src/pg/manager.ts
|
|
155
|
+
import path from "node:path";
|
|
156
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
157
|
+
import { logger as logger2 } from "@elizaos/core";
|
|
158
|
+
import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
|
|
159
|
+
import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
|
|
160
|
+
import pkg from "pg";
|
|
161
|
+
var { Pool } = pkg;
|
|
162
|
+
var PostgresConnectionManager = class {
|
|
163
|
+
static {
|
|
164
|
+
__name(this, "PostgresConnectionManager");
|
|
165
|
+
}
|
|
166
|
+
pool;
|
|
167
|
+
isShuttingDown = false;
|
|
168
|
+
connectionTimeout = 5e3;
|
|
169
|
+
/**
|
|
170
|
+
* Constructor for creating a connection pool.
|
|
171
|
+
* @param {string} connectionString - The connection string used to connect to the database.
|
|
172
|
+
*/
|
|
173
|
+
constructor(connectionString) {
|
|
174
|
+
const defaultConfig = {
|
|
175
|
+
max: 20,
|
|
176
|
+
idleTimeoutMillis: 3e4,
|
|
177
|
+
connectionTimeoutMillis: this.connectionTimeout
|
|
178
|
+
};
|
|
179
|
+
this.pool = new Pool({
|
|
180
|
+
...defaultConfig,
|
|
181
|
+
connectionString
|
|
182
|
+
});
|
|
183
|
+
this.pool.on("error", (err) => {
|
|
184
|
+
logger2.error("Unexpected pool error", err);
|
|
185
|
+
this.handlePoolError(err);
|
|
186
|
+
});
|
|
187
|
+
this.setupPoolErrorHandling();
|
|
188
|
+
this.testConnection();
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Handles a pool error by attempting to reconnect the pool.
|
|
192
|
+
*
|
|
193
|
+
* @param {Error} error The error that occurred in the pool.
|
|
194
|
+
* @throws {Error} If failed to reconnect the pool.
|
|
195
|
+
*/
|
|
196
|
+
async handlePoolError(error) {
|
|
197
|
+
logger2.error("Pool error occurred, attempting to reconnect", {
|
|
198
|
+
error: error.message
|
|
199
|
+
});
|
|
200
|
+
try {
|
|
201
|
+
await this.pool.end();
|
|
202
|
+
this.pool = new Pool({
|
|
203
|
+
...this.pool.options,
|
|
204
|
+
connectionTimeoutMillis: this.connectionTimeout
|
|
205
|
+
});
|
|
206
|
+
await this.testConnection();
|
|
207
|
+
logger2.success("Pool reconnection successful");
|
|
208
|
+
} catch (reconnectError) {
|
|
209
|
+
logger2.error("Failed to reconnect pool", {
|
|
210
|
+
error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError)
|
|
211
|
+
});
|
|
212
|
+
throw reconnectError;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Asynchronously tests the database connection by executing a query to get the current timestamp.
|
|
217
|
+
*
|
|
218
|
+
* @returns {Promise<boolean>} - A Promise that resolves to true if the database connection test is successful.
|
|
219
|
+
*/
|
|
220
|
+
async testConnection() {
|
|
221
|
+
let client = null;
|
|
222
|
+
try {
|
|
223
|
+
client = await this.pool.connect();
|
|
224
|
+
const result = await client.query("SELECT NOW()");
|
|
225
|
+
logger2.success("Database connection test successful:", result.rows[0]);
|
|
226
|
+
return true;
|
|
227
|
+
} catch (error) {
|
|
228
|
+
logger2.error("Database connection test failed:", error);
|
|
229
|
+
throw new Error(`Failed to connect to database: ${error.message}`);
|
|
230
|
+
} finally {
|
|
231
|
+
if (client) client.release();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Sets up event listeners to handle pool cleanup on SIGINT, SIGTERM, and beforeExit events.
|
|
236
|
+
*/
|
|
237
|
+
setupPoolErrorHandling() {
|
|
238
|
+
process.on("SIGINT", async () => {
|
|
239
|
+
await this.cleanup();
|
|
240
|
+
process.exit(0);
|
|
241
|
+
});
|
|
242
|
+
process.on("SIGTERM", async () => {
|
|
243
|
+
await this.cleanup();
|
|
244
|
+
process.exit(0);
|
|
245
|
+
});
|
|
246
|
+
process.on("beforeExit", async () => {
|
|
247
|
+
await this.cleanup();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Get the connection pool.
|
|
252
|
+
* @returns {PgPool} The connection pool
|
|
253
|
+
* @throws {Error} If the connection manager is shutting down or an error occurs when trying to get the connection from the pool
|
|
254
|
+
*/
|
|
255
|
+
getConnection() {
|
|
256
|
+
if (this.isShuttingDown) {
|
|
257
|
+
throw new Error("Connection manager is shutting down");
|
|
258
|
+
}
|
|
259
|
+
try {
|
|
260
|
+
return this.pool;
|
|
261
|
+
} catch (error) {
|
|
262
|
+
logger2.error("Failed to get connection from pool:", error);
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Asynchronously acquires a database client from the connection pool.
|
|
268
|
+
*
|
|
269
|
+
* @returns {Promise<pkg.PoolClient>} A Promise that resolves with the acquired database client.
|
|
270
|
+
* @throws {Error} If an error occurs while acquiring the database client.
|
|
271
|
+
*/
|
|
272
|
+
async getClient() {
|
|
273
|
+
try {
|
|
274
|
+
return await this.pool.connect();
|
|
275
|
+
} catch (error) {
|
|
276
|
+
logger2.error("Failed to acquire a database client:", error);
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Initializes the PostgreSQL connection manager by testing the connection and logging the result.
|
|
282
|
+
*
|
|
283
|
+
* @returns {Promise<void>} A Promise that resolves once the manager is successfully initialized
|
|
284
|
+
* @throws {Error} If there is an error initializing the connection manager
|
|
285
|
+
*/
|
|
286
|
+
async initialize() {
|
|
287
|
+
try {
|
|
288
|
+
await this.testConnection();
|
|
289
|
+
logger2.debug("PostgreSQL connection manager initialized successfully");
|
|
290
|
+
} catch (error) {
|
|
291
|
+
logger2.error("Failed to initialize connection manager:", error);
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Asynchronously close the current process by executing a cleanup function.
|
|
297
|
+
* @returns A promise that resolves once the cleanup is complete.
|
|
298
|
+
*/
|
|
299
|
+
async close() {
|
|
300
|
+
await this.cleanup();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Cleans up and closes the database pool.
|
|
304
|
+
* @returns {Promise<void>} A Promise that resolves when the database pool is closed.
|
|
305
|
+
*/
|
|
306
|
+
async cleanup() {
|
|
307
|
+
try {
|
|
308
|
+
await this.pool.end();
|
|
309
|
+
logger2.info("Database pool closed");
|
|
310
|
+
} catch (error) {
|
|
311
|
+
logger2.error("Error closing database pool:", error);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Asynchronously runs database migrations using the Drizzle library.
|
|
316
|
+
*
|
|
317
|
+
* Drizzle will first check if the migrations are already applied.
|
|
318
|
+
* If there is a diff between database schema and migrations, it will apply the migrations.
|
|
319
|
+
* If they are already applied, it will skip them.
|
|
320
|
+
*
|
|
321
|
+
* @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.
|
|
322
|
+
*/
|
|
323
|
+
async runMigrations() {
|
|
324
|
+
try {
|
|
325
|
+
const db = drizzle2(this.pool);
|
|
326
|
+
const packageJsonUrl = await import.meta.resolve("@elizaos/plugin-sql/package.json");
|
|
327
|
+
const packageJsonPath = fileURLToPath2(packageJsonUrl);
|
|
328
|
+
const packageRoot = path.dirname(packageJsonPath);
|
|
329
|
+
const migrationsPath = path.resolve(packageRoot, "drizzle/migrations");
|
|
330
|
+
logger2.debug(`Resolved migrations path (pg) using import.meta.resolve: ${migrationsPath}`);
|
|
331
|
+
await migrate2(db, {
|
|
332
|
+
migrationsFolder: migrationsPath,
|
|
333
|
+
migrationsSchema: "public"
|
|
334
|
+
});
|
|
335
|
+
} catch (error) {
|
|
336
|
+
logger2.error("Failed to run database migrations (pg):", error);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
export {
|
|
342
|
+
__name,
|
|
343
|
+
PGliteClientManager,
|
|
344
|
+
PostgresConnectionManager
|
|
345
|
+
};
|
|
346
|
+
//# sourceMappingURL=chunk-EYE2J2N6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pglite/manager.ts","../src/pg/manager.ts"],"sourceRoot":"./","sourcesContent":["import { dirname as pathDirname, resolve as pathResolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { PGlite, type PGliteOptions } from '@electric-sql/pglite';\nimport { fuzzystrmatch } from '@electric-sql/pglite/contrib/fuzzystrmatch';\nimport { vector } from '@electric-sql/pglite/vector';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/pglite';\nimport { migrate } from 'drizzle-orm/pglite/migrator';\nimport type { IDatabaseClientManager } from '../types';\n\n/**\n * Class representing a database client manager for PGlite.\n * @implements { IDatabaseClientManager }\n */\nexport class PGliteClientManager implements IDatabaseClientManager<PGlite> {\n private client: PGlite;\n private shuttingDown = false;\n private readonly shutdownTimeout = 500;\n\n /**\n * Constructor for creating a new instance of PGlite with the provided options.\n * Initializes the PGlite client with additional extensions.\n * @param {PGliteOptions} options - The options to configure the PGlite client.\n */\n constructor(options: PGliteOptions) {\n this.client = new PGlite({\n ...options,\n extensions: {\n vector,\n fuzzystrmatch,\n },\n });\n this.setupShutdownHandlers();\n }\n\n /**\n * Retrieves the PostgreSQL lite connection.\n *\n * @returns {PGlite} The PostgreSQL lite connection.\n * @throws {Error} If the client manager is currently shutting down.\n */\n public getConnection(): PGlite {\n if (this.shuttingDown) {\n throw new Error('Client manager is shutting down');\n }\n return this.client;\n }\n\n /**\n * Initiates a graceful shutdown of the PGlite client.\n * Checks if the client is already in the process of shutting down.\n * Logs the start of shutdown process and sets shuttingDown flag to true.\n * Sets a timeout for the shutdown process and forces closure of database connection if timeout is reached.\n * Handles the shutdown process, closes the client connection, clears the timeout, and logs the completion of shutdown.\n * Logs any errors that occur during the shutdown process.\n */\n private async gracefulShutdown() {\n if (this.shuttingDown) {\n return;\n }\n\n this.shuttingDown = true;\n logger.info('Starting graceful shutdown of PGlite client...');\n\n const timeout = setTimeout(() => {\n logger.warn('Shutdown timeout reached, forcing database connection closure...');\n this.client.close().finally(() => {\n process.exit(1);\n });\n }, this.shutdownTimeout);\n\n try {\n await this.client.close();\n clearTimeout(timeout);\n logger.info('PGlite client shutdown completed successfully');\n process.exit(0);\n } catch (error) {\n logger.error('Error during graceful shutdown:', error);\n process.exit(1);\n }\n }\n\n /**\n * Sets up shutdown handlers for SIGINT, SIGTERM, and beforeExit events to gracefully shutdown the application.\n * @private\n */\n private setupShutdownHandlers() {\n process.on('SIGINT', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('SIGTERM', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('beforeExit', async () => {\n await this.gracefulShutdown();\n });\n }\n\n /**\n * Initializes the client for PGlite.\n *\n * @returns {Promise<void>} A Promise that resolves when the client is initialized successfully\n */\n public async initialize(): Promise<void> {\n try {\n await this.client.waitReady;\n logger.info('PGlite client initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize PGlite client:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the resource. If the resource is not already shutting down,\n * it performs a graceful shutdown before closing.\n *\n * @returns A promise that resolves once the resource has been closed.\n */\n public async close(): Promise<void> {\n if (!this.shuttingDown) {\n await this.gracefulShutdown();\n }\n }\n\n /**\n * Check if the system is currently shutting down.\n *\n * @returns {boolean} True if the system is shutting down, false otherwise.\n */\n public isShuttingDown(): boolean {\n return this.shuttingDown;\n }\n\n /**\n * Asynchronously runs database migrations using Drizzle.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.client);\n\n const packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = pathDirname(packageJsonPath);\n const migrationsPath = pathResolve(packageRoot, 'drizzle/migrations');\n logger.debug(\n `Resolved migrations path (pglite) using import.meta.resolve: ${migrationsPath}`\n );\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pglite):', error);\n }\n }\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/node-postgres';\nimport { migrate } from 'drizzle-orm/node-postgres/migrator';\nimport pkg, { type Pool as PgPool } from 'pg';\nimport type { IDatabaseClientManager } from '../types';\n\nconst { Pool } = pkg;\n\n/**\n * Manages connections to a PostgreSQL database using a connection pool.\n * Implements IDatabaseClientManager interface.\n */\n\nexport class PostgresConnectionManager implements IDatabaseClientManager<PgPool> {\n private pool: PgPool;\n private isShuttingDown = false;\n private readonly connectionTimeout: number = 5000;\n\n /**\n * Constructor for creating a connection pool.\n * @param {string} connectionString - The connection string used to connect to the database.\n */\n constructor(connectionString: string) {\n const defaultConfig = {\n max: 20,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: this.connectionTimeout,\n };\n\n this.pool = new Pool({\n ...defaultConfig,\n connectionString,\n });\n\n this.pool.on('error', (err) => {\n logger.error('Unexpected pool error', err);\n this.handlePoolError(err);\n });\n\n this.setupPoolErrorHandling();\n this.testConnection();\n }\n\n /**\n * Handles a pool error by attempting to reconnect the pool.\n *\n * @param {Error} error The error that occurred in the pool.\n * @throws {Error} If failed to reconnect the pool.\n */\n private async handlePoolError(error: Error) {\n logger.error('Pool error occurred, attempting to reconnect', {\n error: error.message,\n });\n\n try {\n await this.pool.end();\n\n this.pool = new Pool({\n ...this.pool.options,\n connectionTimeoutMillis: this.connectionTimeout,\n });\n\n await this.testConnection();\n logger.success('Pool reconnection successful');\n } catch (reconnectError) {\n logger.error('Failed to reconnect pool', {\n error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),\n });\n throw reconnectError;\n }\n }\n\n /**\n * Asynchronously tests the database connection by executing a query to get the current timestamp.\n *\n * @returns {Promise<boolean>} - A Promise that resolves to true if the database connection test is successful.\n */\n async testConnection(): Promise<boolean> {\n let client: pkg.PoolClient | null = null;\n try {\n client = await this.pool.connect();\n const result = await client.query('SELECT NOW()');\n logger.success('Database connection test successful:', result.rows[0]);\n return true;\n } catch (error) {\n logger.error('Database connection test failed:', error);\n throw new Error(`Failed to connect to database: ${(error as Error).message}`);\n } finally {\n if (client) client.release();\n }\n }\n\n /**\n * Sets up event listeners to handle pool cleanup on SIGINT, SIGTERM, and beforeExit events.\n */\n private setupPoolErrorHandling() {\n process.on('SIGINT', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('beforeExit', async () => {\n await this.cleanup();\n });\n }\n\n /**\n * Get the connection pool.\n * @returns {PgPool} The connection pool\n * @throws {Error} If the connection manager is shutting down or an error occurs when trying to get the connection from the pool\n */\n public getConnection(): PgPool {\n if (this.isShuttingDown) {\n throw new Error('Connection manager is shutting down');\n }\n\n try {\n return this.pool;\n } catch (error) {\n logger.error('Failed to get connection from pool:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously acquires a database client from the connection pool.\n *\n * @returns {Promise<pkg.PoolClient>} A Promise that resolves with the acquired database client.\n * @throws {Error} If an error occurs while acquiring the database client.\n */\n public async getClient(): Promise<pkg.PoolClient> {\n try {\n return await this.pool.connect();\n } catch (error) {\n logger.error('Failed to acquire a database client:', error);\n throw error;\n }\n }\n\n /**\n * Initializes the PostgreSQL connection manager by testing the connection and logging the result.\n *\n * @returns {Promise<void>} A Promise that resolves once the manager is successfully initialized\n * @throws {Error} If there is an error initializing the connection manager\n */\n public async initialize(): Promise<void> {\n try {\n await this.testConnection();\n logger.debug('PostgreSQL connection manager initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize connection manager:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously close the current process by executing a cleanup function.\n * @returns A promise that resolves once the cleanup is complete.\n */\n public async close(): Promise<void> {\n await this.cleanup();\n }\n\n /**\n * Cleans up and closes the database pool.\n * @returns {Promise<void>} A Promise that resolves when the database pool is closed.\n */\n async cleanup(): Promise<void> {\n try {\n await this.pool.end();\n logger.info('Database pool closed');\n } catch (error) {\n logger.error('Error closing database pool:', error);\n }\n }\n\n /**\n * Asynchronously runs database migrations using the Drizzle library.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.pool);\n\n const packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = path.dirname(packageJsonPath);\n const migrationsPath = path.resolve(packageRoot, 'drizzle/migrations');\n logger.debug(`Resolved migrations path (pg) using import.meta.resolve: ${migrationsPath}`);\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pg):', error);\n }\n }\n}\n"],"mappings":"+EAAA,OAAS,WAAWA,EAAa,WAAWC,MAAmB,YAC/D,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,UAAAC,MAAkC,uBAC3C,OAAS,iBAAAC,MAAqB,6CAC9B,OAAS,UAAAC,MAAc,8BACvB,OAAS,UAAAC,MAAc,gBACvB,OAAS,WAAAC,MAAe,qBACxB,OAAS,WAAAC,MAAe,8BAOjB,IAAMC,EAAN,MAAMA,CAA8D,CAUzE,YAAYC,EAAwB,CARpC,KAAQ,aAAe,GACvB,KAAiB,gBAAkB,IAQjC,KAAK,OAAS,IAAIC,EAAO,CACvB,GAAGD,EACH,WAAY,CACV,OAAAE,EACA,cAAAC,CACF,CACF,CAAC,EACD,KAAK,sBAAsB,CAC7B,CAQO,eAAwB,CAC7B,GAAI,KAAK,aACP,MAAM,IAAI,MAAM,iCAAiC,EAEnD,OAAO,KAAK,MACd,CAUA,MAAc,kBAAmB,CAC/B,GAAI,KAAK,aACP,OAGF,KAAK,aAAe,GACpBC,EAAO,KAAK,gDAAgD,EAE5D,IAAMC,EAAU,WAAW,IAAM,CAC/BD,EAAO,KAAK,kEAAkE,EAC9E,KAAK,OAAO,MAAM,EAAE,QAAQ,IAAM,CAChC,QAAQ,KAAK,CAAC,CAChB,CAAC,CACH,EAAG,KAAK,eAAe,EAEvB,GAAI,CACF,MAAM,KAAK,OAAO,MAAM,EACxB,aAAaC,CAAO,EACpBD,EAAO,KAAK,+CAA+C,EAC3D,QAAQ,KAAK,CAAC,CAChB,OAASE,EAAO,CACdF,EAAO,MAAM,kCAA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AMmB,EAANnB","names":["pathDirname","pathResolve","fileURLToPath","PGlite","fuzzystrmatch","vector","logger","drizzle","migrate","_PGliteClientManager","options","PGlite","vector","fuzzystrmatch","logger","timeout","error","db","drizzle","packageJsonUrl","packageJsonPath","fileURLToPath","packageRoot","pathDirname","migrationsPath","pathResolve","migrate","__name","PGliteClientManager","path","fileURLToPath","logger","drizzle","migrate","pkg","Pool","pkg","_PostgresConnectionManager","connectionString","defaultConfig","err","logger","error","reconnectError","client","result","db","drizzle","packageJsonUrl","packageJsonPath","fileURLToPath","packageRoot","path","migrationsPath","migrate","__name","PostgresConnectionManager"]}
|
|
1
|
+
{"version":3,"sources":["../src/pglite/manager.ts","../src/pg/manager.ts"],"sourceRoot":"./","sourcesContent":["import { dirname as pathDirname, resolve as pathResolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { PGlite, type PGliteOptions } from '@electric-sql/pglite';\nimport { fuzzystrmatch } from '@electric-sql/pglite/contrib/fuzzystrmatch';\nimport { vector } from '@electric-sql/pglite/vector';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/pglite';\nimport { migrate } from 'drizzle-orm/pglite/migrator';\nimport type { IDatabaseClientManager } from '../types';\n\n/**\n * Class representing a database client manager for PGlite.\n * @implements { IDatabaseClientManager }\n */\nexport class PGliteClientManager implements IDatabaseClientManager<PGlite> {\n private client: PGlite;\n private shuttingDown = false;\n private readonly shutdownTimeout = 500;\n\n /**\n * Constructor for creating a new instance of PGlite with the provided options.\n * Initializes the PGlite client with additional extensions.\n * @param {PGliteOptions} options - The options to configure the PGlite client.\n */\n constructor(options: PGliteOptions) {\n this.client = new PGlite({\n ...options,\n extensions: {\n vector,\n fuzzystrmatch,\n },\n });\n this.setupShutdownHandlers();\n }\n\n /**\n * Retrieves the PostgreSQL lite connection.\n *\n * @returns {PGlite} The PostgreSQL lite connection.\n * @throws {Error} If the client manager is currently shutting down.\n */\n public getConnection(): PGlite {\n if (this.shuttingDown) {\n throw new Error('Client manager is shutting down');\n }\n return this.client;\n }\n\n /**\n * Initiates a graceful shutdown of the PGlite client.\n * Checks if the client is already in the process of shutting down.\n * Logs the start of shutdown process and sets shuttingDown flag to true.\n * Sets a timeout for the shutdown process and forces closure of database connection if timeout is reached.\n * Handles the shutdown process, closes the client connection, clears the timeout, and logs the completion of shutdown.\n * Logs any errors that occur during the shutdown process.\n */\n private async gracefulShutdown() {\n if (this.shuttingDown) {\n return;\n }\n\n this.shuttingDown = true;\n logger.info('Starting graceful shutdown of PGlite client...');\n\n const timeout = setTimeout(() => {\n logger.warn('Shutdown timeout reached, forcing database connection closure...');\n this.client.close().finally(() => {\n process.exit(1);\n });\n }, this.shutdownTimeout);\n\n try {\n await this.client.close();\n clearTimeout(timeout);\n logger.info('PGlite client shutdown completed successfully');\n process.exit(0);\n } catch (error) {\n logger.error('Error during graceful shutdown:', error);\n process.exit(1);\n }\n }\n\n /**\n * Sets up shutdown handlers for SIGINT, SIGTERM, and beforeExit events to gracefully shutdown the application.\n * @private\n */\n private setupShutdownHandlers() {\n process.on('SIGINT', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('SIGTERM', async () => {\n await this.gracefulShutdown();\n });\n\n process.on('beforeExit', async () => {\n await this.gracefulShutdown();\n });\n }\n\n /**\n * Initializes the client for PGlite.\n *\n * @returns {Promise<void>} A Promise that resolves when the client is initialized successfully\n */\n public async initialize(): Promise<void> {\n try {\n await this.client.waitReady;\n logger.info('PGlite client initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize PGlite client:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the resource. If the resource is not already shutting down,\n * it performs a graceful shutdown before closing.\n *\n * @returns A promise that resolves once the resource has been closed.\n */\n public async close(): Promise<void> {\n if (!this.shuttingDown) {\n await this.gracefulShutdown();\n }\n }\n\n /**\n * Check if the system is currently shutting down.\n *\n * @returns {boolean} True if the system is shutting down, false otherwise.\n */\n public isShuttingDown(): boolean {\n return this.shuttingDown;\n }\n\n /**\n * Asynchronously runs database migrations using Drizzle.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.client);\n\n const packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = pathDirname(packageJsonPath);\n const migrationsPath = pathResolve(packageRoot, 'drizzle/migrations');\n logger.debug(\n `Resolved migrations path (pglite) using import.meta.resolve: ${migrationsPath}`\n );\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pglite):', error);\n }\n }\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { logger } from '@elizaos/core';\nimport { drizzle } from 'drizzle-orm/node-postgres';\nimport { migrate } from 'drizzle-orm/node-postgres/migrator';\nimport pkg, { type Pool as PgPool } from 'pg';\nimport type { IDatabaseClientManager } from '../types';\n\nconst { Pool } = pkg;\n\n/**\n * Manages connections to a PostgreSQL database using a connection pool.\n * Implements IDatabaseClientManager interface.\n */\n\nexport class PostgresConnectionManager implements IDatabaseClientManager<PgPool> {\n private pool: PgPool;\n private isShuttingDown = false;\n private readonly connectionTimeout: number = 5000;\n\n /**\n * Constructor for creating a connection pool.\n * @param {string} connectionString - The connection string used to connect to the database.\n */\n constructor(connectionString: string) {\n const defaultConfig = {\n max: 20,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: this.connectionTimeout,\n };\n\n this.pool = new Pool({\n ...defaultConfig,\n connectionString,\n });\n\n this.pool.on('error', (err) => {\n logger.error('Unexpected pool error', err);\n this.handlePoolError(err);\n });\n\n this.setupPoolErrorHandling();\n this.testConnection();\n }\n\n /**\n * Handles a pool error by attempting to reconnect the pool.\n *\n * @param {Error} error The error that occurred in the pool.\n * @throws {Error} If failed to reconnect the pool.\n */\n private async handlePoolError(error: Error) {\n logger.error('Pool error occurred, attempting to reconnect', {\n error: error.message,\n });\n\n try {\n await this.pool.end();\n\n this.pool = new Pool({\n ...this.pool.options,\n connectionTimeoutMillis: this.connectionTimeout,\n });\n\n await this.testConnection();\n logger.success('Pool reconnection successful');\n } catch (reconnectError) {\n logger.error('Failed to reconnect pool', {\n error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),\n });\n throw reconnectError;\n }\n }\n\n /**\n * Asynchronously tests the database connection by executing a query to get the current timestamp.\n *\n * @returns {Promise<boolean>} - A Promise that resolves to true if the database connection test is successful.\n */\n async testConnection(): Promise<boolean> {\n let client: pkg.PoolClient | null = null;\n try {\n client = await this.pool.connect();\n const result = await client.query('SELECT NOW()');\n logger.success('Database connection test successful:', result.rows[0]);\n return true;\n } catch (error) {\n logger.error('Database connection test failed:', error);\n throw new Error(`Failed to connect to database: ${(error as Error).message}`);\n } finally {\n if (client) client.release();\n }\n }\n\n /**\n * Sets up event listeners to handle pool cleanup on SIGINT, SIGTERM, and beforeExit events.\n */\n private setupPoolErrorHandling() {\n process.on('SIGINT', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n await this.cleanup();\n process.exit(0);\n });\n\n process.on('beforeExit', async () => {\n await this.cleanup();\n });\n }\n\n /**\n * Get the connection pool.\n * @returns {PgPool} The connection pool\n * @throws {Error} If the connection manager is shutting down or an error occurs when trying to get the connection from the pool\n */\n public getConnection(): PgPool {\n if (this.isShuttingDown) {\n throw new Error('Connection manager is shutting down');\n }\n\n try {\n return this.pool;\n } catch (error) {\n logger.error('Failed to get connection from pool:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously acquires a database client from the connection pool.\n *\n * @returns {Promise<pkg.PoolClient>} A Promise that resolves with the acquired database client.\n * @throws {Error} If an error occurs while acquiring the database client.\n */\n public async getClient(): Promise<pkg.PoolClient> {\n try {\n return await this.pool.connect();\n } catch (error) {\n logger.error('Failed to acquire a database client:', error);\n throw error;\n }\n }\n\n /**\n * Initializes the PostgreSQL connection manager by testing the connection and logging the result.\n *\n * @returns {Promise<void>} A Promise that resolves once the manager is successfully initialized\n * @throws {Error} If there is an error initializing the connection manager\n */\n public async initialize(): Promise<void> {\n try {\n await this.testConnection();\n logger.debug('PostgreSQL connection manager initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize connection manager:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously close the current process by executing a cleanup function.\n * @returns A promise that resolves once the cleanup is complete.\n */\n public async close(): Promise<void> {\n await this.cleanup();\n }\n\n /**\n * Cleans up and closes the database pool.\n * @returns {Promise<void>} A Promise that resolves when the database pool is closed.\n */\n async cleanup(): Promise<void> {\n try {\n await this.pool.end();\n logger.info('Database pool closed');\n } catch (error) {\n logger.error('Error closing database pool:', error);\n }\n }\n\n /**\n * Asynchronously runs database migrations using the Drizzle library.\n *\n * Drizzle will first check if the migrations are already applied.\n * If there is a diff between database schema and migrations, it will apply the migrations.\n * If they are already applied, it will skip them.\n *\n * @returns {Promise<void>} A Promise that resolves once the migrations are completed successfully.\n */\n async runMigrations(): Promise<void> {\n try {\n const db = drizzle(this.pool);\n\n const packageJsonUrl = await import.meta.resolve('@elizaos/plugin-sql/package.json');\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n const packageRoot = path.dirname(packageJsonPath);\n const migrationsPath = path.resolve(packageRoot, 'drizzle/migrations');\n logger.debug(`Resolved migrations path (pg) using import.meta.resolve: ${migrationsPath}`);\n\n await migrate(db, {\n migrationsFolder: migrationsPath,\n migrationsSchema: 'public',\n });\n } catch (error) {\n logger.error('Failed to run database migrations (pg):', error);\n }\n }\n}\n"],"mappings":";;;;AAAA,SAAS,WAAW,aAAa,WAAW,mBAAmB;AAC/D,SAAS,qBAAqB;AAC9B,SAAS,cAAkC;AAC3C,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,eAAe;AACxB,SAAS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