Skip to content

Calling sql.end() or sql.close() after a server disconnection causes a permanent hang #1097

@a-robinson

Description

@a-robinson

I've found that if I experience a disconnection from the server, then attempting to clean up by calling sql.end() or sql.close() before exiting returns a promise that will never resolve. Below is a small reproduction which causes node to exit with exit status 13, which indicates that the process exited because an awaited top-level promise would never resolve:

import postgres from "postgres";

async function test() {
  const sql = postgres();

  try {
    // Run a slow query to give time to kill the DB process while the query is still running
    const result = await sql`select pg_sleep(10)`;

    console.log({ success: true, result: result });
  } catch (e) {
    console.error("Caught error: " + e);
  }

  try {
    await sql.end();
  } catch (err) {
    console.error("Caught error shutting down sql: " + err);
  }

  console.log("All done!");
}

await test();

If I then run this and kill the postgres database while the pg_sleep(10) query is running, then the script outputs:

$ node postgres.mjs
Caught error: Error: write CONNECTION_CLOSED 127.0.0.1:8257
$ echo $?
13

There's something important here about needing the disconnection to happen after we've connected to the server; if I just don't have a running postgres instance in the first place or if I leave the postgres instance running the entire time without disturbing it, then the script will happily run to completion, printing All done! before exiting cleanly with exit status 0.

This may be the same underlying problem as #861, I'm not sure. But having a simpler repro seemed valuable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions