| 65 | |
| 66 | // Main function to start the server |
| 67 | async function main() { |
| 68 | try { |
| 69 | // Parse arguments |
| 70 | const dbPath = args.values.db as string |
| 71 | const port = parseInt(args.values.port as string, 10) |
| 72 | const host = args.values.host as string |
| 73 | const path = args.values.path as string |
| 74 | const debugStr = args.values.debug as string |
| 75 | const debugLevel = parseInt(debugStr, 10) as DebugLevel |
| 76 | |
| 77 | console.log(`Initializing PGLite with database: ${dbPath}`) |
| 78 | console.log(`Debug level: ${debugLevel}`) |
| 79 | |
| 80 | // Create PGlite instance |
| 81 | const db = new PGlite(dbPath, { debug: debugLevel }) |
| 82 | |
| 83 | // Wait for PGlite to be ready |
| 84 | await db.waitReady |
| 85 | console.log('PGlite database initialized') |
| 86 | |
| 87 | // Create and start the socket server |
| 88 | const server = new PGLiteSocketServer({ |
| 89 | db, |
| 90 | port, |
| 91 | host, |
| 92 | path, |
| 93 | inspect: debugLevel > 0, |
| 94 | }) |
| 95 | |
| 96 | // Listen for server events |
| 97 | server.addEventListener('listening', (event) => { |
| 98 | const detail = ( |
| 99 | event as CustomEvent<{ port: number; host: string } | { host: string }> |
| 100 | ).detail |
| 101 | console.log(`PGLiteSocketServer listening on ${JSON.stringify(detail)}`) |
| 102 | }) |
| 103 | |
| 104 | server.addEventListener('connection', (event) => { |
| 105 | const { clientAddress, clientPort } = ( |
| 106 | event as CustomEvent<{ clientAddress: string; clientPort: number }> |
| 107 | ).detail |
| 108 | console.log(`Client connected from ${clientAddress}:${clientPort}`) |
| 109 | }) |
| 110 | |
| 111 | server.addEventListener('error', (event) => { |
| 112 | const error = (event as CustomEvent<Error>).detail |
| 113 | console.error('Socket server error:', error) |
| 114 | }) |
| 115 | |
| 116 | // Start the server |
| 117 | await server.start() |
| 118 | |
| 119 | // Handle process termination to stop the server gracefully |
| 120 | const shutdown = async () => { |
| 121 | console.log('\nShutting down PGLiteSocketServer...') |
| 122 | await server.stop() |
| 123 | await db.close() |
| 124 | console.log('Server stopped') |