{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { PGlite } from '@electric-sql/pglite'\nimport { type Server, type Socket, createServer } from 'net'\n\n// Connection queue timeout in milliseconds\nexport const CONNECTION_QUEUE_TIMEOUT = 60000 // 60 seconds\n\n/**\n * Represents a queued query waiting for PGlite access\n */\ninterface QueuedQuery {\n handlerId: number\n message: Uint8Array\n resolve: (resultSize: number) => void\n reject: (error: Error) => void\n timestamp: number\n onData: (data: Uint8Array) => void\n}\n\n/**\n * Global query queue manager\n * Ensures only one query executes at a time in PGlite\n */\nclass QueryQueueManager {\n private queue: QueuedQuery[] = []\n private processing = false\n private db: PGlite\n private debug: boolean\n private lastHandlerId: null | number = null\n\n constructor(db: PGlite, debug = false) {\n this.db = db\n this.debug = debug\n }\n\n private log(message: string, ...args: any[]): void {\n if (this.debug) {\n console.log(`[QueryQueueManager] ${message}`, ...args)\n }\n }\n\n async enqueue(\n handlerId: number,\n message: Uint8Array,\n onData: (data: Uint8Array) => void,\n ): Promise {\n return new Promise((resolve, reject) => {\n const query: QueuedQuery = {\n handlerId,\n message,\n resolve,\n reject,\n timestamp: Date.now(),\n onData,\n }\n\n this.queue.push(query)\n this.log(\n `enqueued query from handler #${handlerId}, queue size: ${this.queue.length}`,\n )\n\n // Process queue if not already processing\n if (!this.processing) {\n this.processQueue()\n }\n })\n }\n\n private async processQueue(): Promise {\n if (this.processing || this.queue.length === 0) {\n return\n }\n\n this.processing = true\n\n while (this.queue.length > 0) {\n let query\n\n if (this.db.isInTransaction() && this.lastHandlerId) {\n const i = this.queue.findIndex(\n (q) => q.handlerId === this.lastHandlerId,\n )\n if (i === -1) {\n // we didn't find any other query from the same client!\n this.log(\n `transaction started, but no query from the same handler id found in queue`,\n this.lastHandlerId,\n )\n query = null\n } else {\n query = this.queue.splice(i, 1)[0]\n }\n } else {\n query = this.queue.shift()\n }\n if (!query) break\n\n const waitTime = Date.now() - query.timestamp\n this.log(\n `processing query from handler #${query.handlerId} (waited ${waitTime}ms)`,\n )\n\n let result = 0\n try {\n // Execute the query with exclusive access to PGlite\n await this.db.runExclusive(async () => {\n return await this.db.execProtocolRawStream(query.message, {\n onRawData: (data) => {\n result += data.length\n query.onData(data)\n },\n })\n })\n } catch (error) {\n this.log(`query from handler #${query.handlerId} failed:`, error)\n query.reject(error as Error)\n return\n }\n\n this.log(\n `query from handler #${query.handlerId} completed, ${result} bytes`,\n )\n this.lastHandlerId = query.handlerId\n query.resolve(result)\n }\n\n this.processing = false\n this.log(`queue processing complete, queue length is`, this.queue.length)\n }\n\n getQueueLength(): number {\n return this.queue.length\n }\n\n clearQueueForHandler(handlerId: number): void {\n const before = this.queue.length\n this.queue = this.queue.filter((q) => {\n if (q.handlerId === handlerId) {\n q.reject(new Error('Handler disconnected'))\n return false\n }\n return true\n })\n const removed = before - this.queue.length\n if (removed > 0) {\n this.log(`cleared ${removed} queries for handler #${handlerId}`)\n }\n }\n\n async clearTransactionIfNeeded(handlerId: number): Promise {\n if (this.db.isInTransaction() && this.lastHandlerId === handlerId) {\n await this.db.exec('ROLLBACK')\n this.lastHandlerId = null\n await this.processQueue()\n }\n }\n}\n\n/**\n * Options for creating a PGLiteSocketHandler\n */\nexport interface PGLiteSocketHandlerOptions {\n /** The query queue manager */\n queryQueue: QueryQueueManager\n /** Whether to close the socket when detached (default: false) */\n closeOnDetach?: boolean\n /** Print the incoming and outgoing data to the console in hex and ascii */\n inspect?: boolean\n /** Enable debug logging of method calls */\n debug?: boolean\n /** Idle timeout in ms (0 to disable, default: 0) */\n idleTimeout?: number\n}\n\n/**\n * Handler for a single socket connection to PGlite\n * Each connection can remain open and send multiple queries\n */\nexport class PGLiteSocketHandler extends EventTarget {\n private queryQueue: QueryQueueManager\n private socket: Socket | null = null\n private active = false\n private closeOnDetach: boolean\n private inspect: boolean\n private debug: boolean\n private readonly id: number\n private messageBuffer: Buffer = Buffer.alloc(0)\n private idleTimer?: NodeJS.Timeout\n private idleTimeout: number\n private lastActivityTime: number = Date.now()\n\n // Static counter for generating unique handler IDs\n private static nextHandlerId = 1\n\n constructor(options: PGLiteSocketHandlerOptions) {\n super()\n this.queryQueue = options.queryQueue\n this.closeOnDetach = options.closeOnDetach ?? false\n this.inspect = options.inspect ?? false\n this.debug = options.debug ?? false\n this.idleTimeout = options.idleTimeout ?? 0\n this.id = PGLiteSocketHandler.nextHandlerId++\n\n this.log('constructor: created new handler')\n }\n\n public get handlerId(): number {\n return this.id\n }\n\n private log(message: string, ...args: any[]): void {\n if (this.debug) {\n console.log(`[PGLiteSocketHandler#${this.id}] ${message}`, ...args)\n }\n }\n\n public async attach(socket: Socket): Promise {\n this.log(\n `attach: attaching socket from ${socket.remoteAddress}:${socket.remotePort}`,\n )\n\n if (this.socket) {\n throw new Error('Socket already attached')\n }\n\n this.socket = socket\n this.active = true\n this.lastActivityTime = Date.now()\n\n // Set up socket options\n socket.setNoDelay(true)\n\n // Set up idle timeout if configured\n if (this.idleTimeout > 0) {\n this.resetIdleTimer()\n }\n\n // Setup event handlers\n this.log(`attach: setting up socket event handlers`)\n\n socket.on('data', (data) => {\n this.lastActivityTime = Date.now()\n this.resetIdleTimer()\n\n setImmediate(async () => {\n try {\n await this.handleData(data)\n } catch (err) {\n this.log('socket on data error: ', err)\n this.handleError(err as Error)\n }\n })\n })\n\n socket.on('error', (err) => {\n setImmediate(() => this.handleError(err))\n })\n\n socket.on('close', () => {\n setImmediate(() => this.handleClose())\n })\n\n this.log(`attach: socket handler ready`)\n return this\n }\n\n private resetIdleTimer(): void {\n if (this.idleTimeout <= 0) return\n\n if (this.idleTimer) {\n clearTimeout(this.idleTimer)\n }\n\n this.idleTimer = setTimeout(() => {\n const idleTime = Date.now() - this.lastActivityTime\n this.log(`idle timeout after ${idleTime}ms`)\n this.handleError(new Error('Idle timeout'))\n }, this.idleTimeout)\n }\n\n public async detach(close?: boolean): Promise {\n this.log(`detach: detaching socket, close=${close ?? this.closeOnDetach}`)\n\n if (this.idleTimer) {\n clearTimeout(this.idleTimer)\n this.idleTimer = undefined\n }\n\n // Clear any pending queries for this handler\n this.queryQueue.clearQueueForHandler(this.id)\n\n await this.queryQueue.clearTransactionIfNeeded(this.id)\n\n if (!this.socket) {\n this.log(`detach: no socket attached, nothing to do`)\n return this\n }\n\n // Remove all listeners\n this.socket.removeAllListeners('data')\n this.socket.removeAllListeners('error')\n this.socket.removeAllListeners('close')\n\n // Close the socket if requested\n if (close ?? this.closeOnDetach) {\n if (this.socket.writable) {\n this.log(`detach: closing socket`)\n try {\n this.socket.end()\n this.socket.destroy()\n } catch (err) {\n this.log(`detach: error closing socket:`, err)\n }\n }\n }\n\n this.socket = null\n this.active = false\n this.messageBuffer = Buffer.alloc(0)\n\n this.log(`detach: handler cleaned up`)\n return this\n }\n\n public get isAttached(): boolean {\n return this.socket !== null\n }\n\n private async handleData(data: Buffer): Promise {\n if (!this.socket || !this.active) {\n this.log(`handleData: no active socket, ignoring data`)\n return 0\n }\n\n this.log(`handleData: received ${data.length} bytes`)\n\n // Append to buffer for message reassembly\n this.messageBuffer = Buffer.concat([this.messageBuffer, data])\n\n // Print the incoming data to the console\n this.inspectData('incoming', data)\n\n try {\n let totalProcessed = 0\n\n while (this.messageBuffer.length > 0) {\n // Determine message length\n let messageLength = 0\n let isComplete = false\n\n // Handle startup message (no type byte, just length)\n if (this.messageBuffer.length >= 4) {\n const firstInt = this.messageBuffer.readInt32BE(0)\n\n if (this.messageBuffer.length >= 8) {\n const secondInt = this.messageBuffer.readInt32BE(4)\n // PostgreSQL 3.0 protocol version\n if (secondInt === 196608 || secondInt === 0x00030000) {\n messageLength = firstInt\n isComplete = this.messageBuffer.length >= messageLength\n }\n }\n\n // Regular message (type byte + length)\n if (!isComplete && this.messageBuffer.length >= 5) {\n const msgLength = this.messageBuffer.readInt32BE(1)\n messageLength = 1 + msgLength\n isComplete = this.messageBuffer.length >= messageLength\n }\n }\n\n if (!isComplete || messageLength === 0) {\n this.log(\n `handleData: incomplete message, buffering ${this.messageBuffer.length} bytes`,\n )\n break\n }\n\n // Extract and process complete message\n const message = this.messageBuffer.slice(0, messageLength)\n this.messageBuffer = this.messageBuffer.slice(messageLength)\n\n this.log(`handleData: processing message of ${message.length} bytes`)\n\n // Check if socket is still active before processing\n if (!this.active || !this.socket) {\n this.log(`handleData: socket no longer active, stopping processing`)\n break\n }\n\n let socketWriteError: any = undefined\n // Queue the query for execution\n // This allows multiple connections to queue queries simultaneously\n await this.queryQueue.enqueue(\n this.id,\n new Uint8Array(message),\n (data) => {\n this.log(`handleData: received ${data.length} bytes from PGlite`)\n\n // Print the outgoing data to the console\n this.inspectData('outgoing', data)\n\n // Send response if available\n if (\n data.length > 0 &&\n this.socket &&\n this.socket.writable &&\n this.active\n ) {\n // await new Promise((resolve, reject) => {\n this.log(`handleData: writing response to socket`)\n if (this.socket?.writable) {\n this.socket.write(Buffer.from(data), (err?: any) => {\n if (err) {\n this.log(`handleData: error writing to socket:`, err)\n socketWriteError = err\n } else {\n this.log(`handleData: socket sent: ${data.length} bytes`)\n }\n })\n } else {\n this.log(`handleData: socket no longer writable`)\n }\n }\n totalProcessed += data.length\n },\n )\n if (socketWriteError) throw socketWriteError\n }\n\n // Emit data event with byte sizes\n this.dispatchEvent(\n new CustomEvent('data', {\n detail: { incoming: data.length, outgoing: totalProcessed },\n }),\n )\n\n return totalProcessed\n } catch (err) {\n this.log(`handleData: error processing data:`, err)\n throw err\n }\n }\n\n private handleError(err: Error): void {\n if (!this.active) {\n this.log(`handleError: handler not active, ignoring error`)\n return\n }\n\n // ECONNRESET is expected behavior when clients disconnect\n if (err.message?.includes('ECONNRESET')) {\n this.log(\n `handleError: client disconnected (ECONNRESET) - normal behavior`,\n )\n } else if (err.message?.includes('Idle timeout')) {\n this.log(`handleError: connection idle timeout`)\n } else {\n this.log(`handleError:`, err)\n }\n\n this.active = false\n\n // Emit error event\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n\n // Clean up\n this.detach(true)\n }\n\n private handleClose(): void {\n this.log(`handleClose: socket closed`)\n this.active = false\n this.dispatchEvent(new CustomEvent('close'))\n this.detach(false)\n }\n\n private inspectData(\n direction: 'incoming' | 'outgoing',\n data: Buffer | Uint8Array,\n ): void {\n if (!this.inspect) return\n console.log('-'.repeat(75))\n if (direction === 'incoming') {\n console.log('-> incoming', data.length, 'bytes')\n } else {\n console.log('<- outgoing', data.length, 'bytes')\n }\n\n for (let offset = 0; offset < data.length; offset += 16) {\n const chunkSize = Math.min(16, data.length - offset)\n\n let hexPart = ''\n for (let i = 0; i < 16; i++) {\n if (i < chunkSize) {\n const byte = data[offset + i]\n hexPart += byte.toString(16).padStart(2, '0') + ' '\n } else {\n hexPart += ' '\n }\n }\n\n let asciiPart = ''\n for (let i = 0; i < chunkSize; i++) {\n const byte = data[offset + i]\n asciiPart += byte >= 32 && byte <= 126 ? String.fromCharCode(byte) : '.'\n }\n\n console.log(\n `${offset.toString(16).padStart(8, '0')} ${hexPart} ${asciiPart}`,\n )\n }\n }\n}\n\n/**\n * Options for creating a PGLiteSocketServer\n */\nexport interface PGLiteSocketServerOptions {\n /** The PGlite database instance */\n db: PGlite\n /** The port to listen on (default: 5432) */\n port?: number\n /** The host to bind to (default: 127.0.0.1) */\n host?: string\n /** Unix socket path to bind to (default: undefined) */\n path?: string\n /** Print the incoming and outgoing data to the console in hex and ascii */\n inspect?: boolean\n /** Enable debug logging of method calls */\n debug?: boolean\n /** Idle timeout in ms (0 to disable, default: 0) */\n idleTimeout?: number\n /** Maximum concurrent connections (default: 100) */\n maxConnections?: number\n}\n\n/**\n * PGLite Socket Server with support for multiple concurrent connections\n * Connections remain open and queries are queued at the query level\n */\nexport class PGLiteSocketServer extends EventTarget {\n readonly db: PGlite\n private server: Server | null = null\n private port?: number\n private host?: string\n private path?: string\n private active = false\n private inspect: boolean\n private debug: boolean\n private idleTimeout: number\n private maxConnections: number\n private handlers: Set = new Set()\n private queryQueue: QueryQueueManager\n\n constructor(options: PGLiteSocketServerOptions) {\n super()\n this.db = options.db\n if (options.path) {\n this.path = options.path\n } else {\n if (typeof options.port === 'number') {\n // Keep port undefined on port 0, will be set by the OS when we start the server.\n this.port = options.port ?? options.port\n } else {\n this.port = 5432\n }\n this.host = options.host || '127.0.0.1'\n }\n this.inspect = options.inspect ?? false\n this.debug = options.debug ?? false\n this.idleTimeout = options.idleTimeout ?? 0\n this.maxConnections = options.maxConnections ?? 1\n\n // Create the shared query queue\n this.queryQueue = new QueryQueueManager(this.db, this.debug)\n\n this.log(`constructor: created server on ${this.getServerConn()}`)\n this.log(`constructor: max connections: ${this.maxConnections}`)\n if (this.idleTimeout > 0) {\n this.log(`constructor: idle timeout: ${this.idleTimeout}ms`)\n }\n }\n\n private log(message: string, ...args: any[]): void {\n if (this.debug) {\n console.log(`[PGLiteSocketServer] ${message}`, ...args)\n }\n }\n\n public async start(): Promise {\n this.log(`start: starting server on ${this.getServerConn()}`)\n\n if (this.server) {\n throw new Error('Socket server already started')\n }\n\n // Ensure PGlite is ready before accepting connections\n await this.db.waitReady\n\n this.active = true\n this.server = createServer((socket) => {\n setImmediate(() => this.handleConnection(socket))\n })\n\n this.server.maxConnections = this.maxConnections\n\n return new Promise((resolve, reject) => {\n if (!this.server) return reject(new Error('Server not initialized'))\n\n this.server.on('error', (err) => {\n this.log(`start: server error:`, err)\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n if (!this.active) {\n reject(err)\n }\n })\n\n if (this.path) {\n this.server.listen(this.path, () => {\n this.log(`start: server listening on ${this.getServerConn()}`)\n this.dispatchEvent(\n new CustomEvent('listening', {\n detail: { path: this.path },\n }),\n )\n resolve()\n })\n } else {\n const server = this.server\n server.listen(this.port, this.host, () => {\n const address = server.address()\n // We are not using pipes, so return type should be AddressInfo\n if (address === null || typeof address !== 'object') {\n throw Error('Expected address info')\n }\n // Assign the new port number\n this.port = address.port\n this.log(`start: server listening on ${this.getServerConn()}`)\n this.dispatchEvent(\n new CustomEvent('listening', {\n detail: { port: this.port, host: this.host },\n }),\n )\n resolve()\n })\n }\n })\n }\n\n public getServerConn(): string {\n if (this.path) return this.path\n return `${this.host}:${this.port}`\n }\n\n public async stop(): Promise {\n this.log(`stop: stopping server`)\n\n this.active = false\n\n // Detach all handlers\n this.log(`stop: detaching ${this.handlers.size} handlers`)\n for (const handler of this.handlers) {\n handler.detach(true)\n }\n this.handlers.clear()\n\n if (!this.server) {\n this.log(`stop: server not running, nothing to do`)\n return Promise.resolve()\n }\n\n return new Promise((resolve) => {\n if (!this.server) return resolve()\n\n this.server.close(() => {\n this.log(`stop: server closed`)\n this.server = null\n this.dispatchEvent(new CustomEvent('close'))\n resolve()\n })\n })\n }\n\n private async handleConnection(socket: Socket): Promise {\n const clientInfo = {\n clientAddress: socket.remoteAddress || 'unknown',\n clientPort: socket.remotePort || 0,\n }\n\n this.log(\n `handleConnection: new connection from ${clientInfo.clientAddress}:${clientInfo.clientPort}`,\n )\n this.log(\n `handleConnection: active connections: ${this.handlers.size}, queued queries: ${this.queryQueue.getQueueLength()}`,\n )\n\n if (!this.active) {\n this.log(`handleConnection: server not active, closing connection`)\n try {\n socket.end()\n } catch (err) {\n this.log(`handleConnection: error closing socket:`, err)\n }\n return\n }\n\n // Check connection limit\n if (this.handlers.size >= this.maxConnections) {\n this.log(`handleConnection: max connections reached, rejecting`)\n socket.write(Buffer.from('Too many connections\\n'))\n socket.end()\n return\n }\n\n // Create a new handler for this connection\n const handler = new PGLiteSocketHandler({\n queryQueue: this.queryQueue,\n closeOnDetach: true,\n inspect: this.inspect,\n debug: this.debug,\n idleTimeout: this.idleTimeout,\n })\n\n // Track this handler\n this.handlers.add(handler)\n\n // Handle errors\n handler.addEventListener('error', (event) => {\n const error = (event as CustomEvent).detail\n\n if (error?.message?.includes('ECONNRESET')) {\n this.log(\n `handler #${handler.handlerId}: client disconnected (ECONNRESET)`,\n )\n } else if (error?.message?.includes('Idle timeout')) {\n this.log(`handler #${handler.handlerId}: idle timeout`)\n } else {\n this.log(`handler #${handler.handlerId}: error:`, error)\n }\n })\n\n // Handle close event\n handler.addEventListener('close', () => {\n this.log(`handler #${handler.handlerId}: closed`)\n this.handlers.delete(handler)\n this.log(`handleConnection: active connections: ${this.handlers.size}`)\n })\n\n try {\n await handler.attach(socket)\n this.dispatchEvent(new CustomEvent('connection', { detail: clientInfo }))\n } catch (err) {\n this.log(`handleConnection: error attaching socket:`, err)\n this.handlers.delete(handler)\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n try {\n socket.end()\n } catch (closeErr) {\n this.log(`handleConnection: error closing socket:`, closeErr)\n }\n }\n }\n\n public getStats() {\n return {\n activeConnections: this.handlers.size,\n queuedQueries: this.queryQueue.getQueueLength(),\n maxConnections: this.maxConnections,\n }\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,EAAA,wBAAAC,EAAA,uBAAAC,IAAA,eAAAC,EAAAL,GACA,IAAAM,EAAuD,eAG1CC,EAA2B,IAkBlCC,EAAN,KAAwB,CAOtB,YAAYC,EAAYC,EAAQ,GAAO,CANvC,KAAQ,MAAuB,CAAC,EAChC,KAAQ,WAAa,GAGrB,KAAQ,cAA+B,KAGrC,KAAK,GAAKD,EACV,KAAK,MAAQC,CACf,CAEQ,IAAIC,KAAoBC,EAAmB,CAC7C,KAAK,OACP,QAAQ,IAAI,uBAAuBD,CAAO,GAAI,GAAGC,CAAI,CAEzD,CAEA,MAAM,QACJC,EACAF,EACAG,EACiB,CACjB,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CACtC,IAAMC,EAAqB,CACzB,UAAAJ,EACA,QAAAF,EACA,QAAAI,EACA,OAAAC,EACA,UAAW,KAAK,IAAI,EACpB,OAAAF,CACF,EAEA,KAAK,MAAM,KAAKG,CAAK,EACrB,KAAK,IACH,gCAAgCJ,CAAS,iBAAiB,KAAK,MAAM,MAAM,EAC7E,EAGK,KAAK,YACR,KAAK,aAAa,CAEtB,CAAC,CACH,CAEA,MAAc,cAA8B,CAC1C,GAAI,OAAK,YAAc,KAAK,MAAM,SAAW,GAM7C,KAFA,KAA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AAK,WAAW,eAAe,EAC9C,eAAgB,KAAK,cACvB,CACF,CACF","names":["src_exports","__export","CONNECTION_QUEUE_TIMEOUT","PGLiteSocketHandler","PGLiteSocketServer","__toCommonJS","import_net","CONNECTION_QUEUE_TIMEOUT","QueryQueueManager","db","debug","message","args","handlerId","onData","resolve","reject","query","i","q","waitTime","result","data","error","before","removed","_PGLiteSocketHandler","options","socket","err","idleTime","close","totalProcessed","messageLength","isComplete","firstInt","secondInt","socketWriteError","direction","offset","chunkSize","hexPart","byte","asciiPart","PGLiteSocketHandler","PGLiteSocketServer","server","address","handler","clientInfo","event","closeErr"]}