porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.26k stars 262 forks source link

Connection timeout with cloudflare hyperdrive #702

Closed eduardvercaemer closed 10 months ago

eduardvercaemer commented 10 months ago

I setup my hyperdrive connection as per https://developers.cloudflare.com/hyperdrive/get-started/ (I tried a supabase database and also a neon database). In either case, requests fail with

Uncaught (in response) Error: write CONNECT_TIMEOUT xxxxxxxxxxxxxxxxxxxxxxxxxxxxx.hyperdrive.local:5432

Exact code, tested with wrangler dev --remote:

import postgres from "postgres";

export default {
  async fetch(request, env, ctx) {
    const url = env.HYPERDRIVE.connectionString;
    console.info("using", url);

    const sql = postgres(env.HYPERDRIVE.connectionString);
    const rows = await sql`select now()`;
    return Response.json(rows);
  },
};

I then switched the code to use regular pg library and it works as expected, so it looks like this is a "postgres" (as in this library) issue.

anirudhsama commented 10 months ago

I'm also facing the same issue. Can also confirm that it works fine with the pg library.

anirudhsama commented 10 months ago

If it helps in debugging, the hyperdrive connection string has sslmode=disabled as a query param. It will be like postgresql://user:password@xxxx.hyperdrive.local:5432/dbxxx?sslmode=disable

eduardvercaemer commented 10 months ago

Btw this is exclusively a postgres + hyperdrive issue. Using pg library or skipping hyperdrive and using postgres server directly both work as expected.

porsager commented 10 months ago

What happens if you remove the sslmode part? I am not a computer, so can't try anything myself.

ItsWendell commented 10 months ago

@porsager I tried both removing the sslmode query in the URL before passing it to postgres.js and adding { rejectUnauthorized: false, } to ssl option, in both cases, timeouts, I also disabled prepare and fetch_types

I took a peek in the cf folder and how the polyfills are handled, and I suspect (not verified) that it has something to do with how TLS / SSL is handled there, which first of all, doesn't seem to adjust to sslmode query param like node-postgres does, looks like postgres.js in the cf polyfills always has a default tls settings which might be the issue here.

KianNH commented 10 months ago

The CONNECT_TIMEOUT error is fixed by https://github.com/porsager/postgres/commit/09e6cb5247c514e5cf50faced6452fae956edeb9, so you will want to upgrade to at least 3.4.1.

porsager commented 10 months ago

Thanks a lot for confirming @KianNH