Repository navigation
Conversation
When a parameterized query fails during PostgreSQL Extended Query Protocol Parse or Bind, PGlite discards trailing pipelined messages (such as Describe or Execute) until Sync and returns an empty Uint8Array(0). Previously, PostgresServer's onMessage generator yielded nothing and returned undefined, causing pg-gateway to fall through to handleRegularMessage() and emit a spurious ErrorResponse (SQLSTATE 123: "Message code not yet implemented") plus an extra ReadyForQuery. This desynchronized lib/pq and pg clients, triggered TCP RST/ECONNRESET, and left PGlite wedged in SQLSTATE 25P02 when a client terminated inside an aborted transaction. Fix this in src/emulator/dataconnect/pgliteServer.ts: - Yield an empty Uint8Array(0) when PGlite returns no messages on a non-Terminate frame so pg-gateway treats the frame as handled. - On Terminate, log the frame, run DEALLOCATE ALL via db.exec(), and roll back strictly on SQLSTATE 25P02 so healthy concurrent transactions are untouched while aborted sessions recover cleanly. - Close the per-connection pglite-debug.log stream on socket close and ignore writes after stream end to prevent ERR_STREAM_WRITE_AFTER_END. - Add unit tests in src/emulator/dataconnect/pgliteServer.spec.ts. Change-Id: Ic19bef5008c05709035f1c0e8b2b32bf8a29c96e
There was a problem hiding this comment.
Code Review
This pull request improves the robustness of the PGlite emulator server by properly handling client terminations, rolling back aborted transactions to prevent subsequent connections from getting stuck, and ensuring correct signaling to pg-gateway when no output is produced. It also adds comprehensive unit tests in pgliteServer.spec.ts. The review feedback focuses on aligning the code with the repository's TypeScript guidelines by converting isPgErrorCode into a proper type guard and replacing unsafe 'as any' type assertions with type-safe Buffer.from() conversions.
| function isPgErrorCode(err: unknown, code: string): boolean { | ||
| return typeof err === "object" && err !== null && "code" in err && err.code === code; | ||
| } |
There was a problem hiding this comment.
To adhere to the TypeScript guidelines in the repository style guide (which recommends defining proper interfaces/types or using type guards), we should make isPgErrorCode a proper TypeScript type guard by using the err is { code: string } return type. This allows the TypeScript compiler to safely narrow the type of err in blocks where this function returns true.
function isPgErrorCode(err: unknown, code: string): err is { code: string } {
return (
typeof err === "object" &&
err !== null &&
"code" in err &&
typeof err.code === "string" &&
err.code === code
);
}References
- Never use
anyorunknownas an escape hatch. Define proper interfaces/types or use type guards. (link)
| /** Logs a raw Postgres frontend wire frame to pglite-debug.log. */ | ||
| logRequest(request: Uint8Array): void { | ||
| this.writeLog( | ||
| `\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(request as any as Buffer), |
There was a problem hiding this comment.
Avoid using as any as an escape hatch to cast Uint8Array to Buffer. Instead, use the standard and type-safe Buffer.from(request) to perform the conversion, adhering to the repository style guide's TypeScript guidelines.
| `\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(request as any as Buffer), | |
| `\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(Buffer.from(request)), |
References
- Never use
anyorunknownas an escape hatch. Define proper interfaces/types or use type guards. (link)
| for await (const bm of getMessages(response)) { | ||
| this.pgliteDebugLog.write( | ||
| this.writeLog( | ||
| `\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(bm as any as Buffer)}`, |
There was a problem hiding this comment.
Avoid using as any as an escape hatch to cast Uint8Array to Buffer. Instead, use the standard and type-safe Buffer.from(bm) to perform the conversion, adhering to the repository style guide's TypeScript guidelines.
| `\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(bm as any as Buffer)}`, | |
| `\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(Buffer.from(bm))}`, |
References
- Never use
anyorunknownas an escape hatch. Define proper interfaces/types or use type guards. (link)
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #11633 +/- ##
=======================================
Coverage ? 61.56%
=======================================
Files ? 870
Lines ? 51215
Branches ? 10353
=======================================
Hits ? 31531
Misses ? 18528
Partials ? 1156 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Description
When a parameterized SQL query fails during PostgreSQL Extended Query Protocol
ParseorBind, PGlite discards trailing pipelined frames (Describe/Execute) untilSyncand returns an emptyUint8Array(0). Previously,PostgresServer'sonMessagegenerator insrc/emulator/dataconnect/pgliteServer.tsyielded zero items and returnedundefined, causingpg-gatewayto fall through tohandleRegularMessage()and inject a bogusErrorResponse(SQLSTATE 123: "Message code not yet implemented") plus an extraReadyForQuery(Z).This wire desync caused
lib/pqto fail withpq: unexpected message 'E'; expected ReadyForQuery(masking real PostgreSQL errors asINTERNALand triggeringECONNRESET/EPIPE), and permanently wedged PGlite in25P02if triggered inside a@transactionwhenTerminateranDEALLOCATE ALL.Changes
new Uint8Array(0)when PGlite intentionally produces no response bytes for a non-Terminateframe sopg-gatewaymarks the message handled instead of falling through tohandleRegularMessage().Terminate, log the frame, executeDEALLOCATE ALLviadb.exec(), and runROLLBACK+ retryDEALLOCATE ALLstrictly whenDEALLOCATE ALLfails with25P02(leaving healthy concurrent transactions untouched).pglite-debug.logstream on socket close and guard writes against already-ended streams.src/emulator/dataconnect/pgliteServer.spec.tscoveringParse/Binderrors,pg.Clientreuse, concurrent transactions onTerminate,25P02recovery, debug-modeTerminatewithout25P01warnings, and closed debug log stream safety.Scenarios Tested
eslint --config .eslintrc.js src/emulator/dataconnect/pgliteServer.ts src/emulator/dataconnect/pgliteServer.spec.ts(0 errors)tsc --project tsconfig.compile.json --noEmit(0 errors)nyc mocha --forbid-only src/emulator/dataconnect/pgliteServer.spec.ts(7/7 passing)Prepared with the Firebase SQL Connect team agent and reviewed by @fredzqm.