diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index 7335d527fbdb..c9ce3d978e29 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -469,14 +469,22 @@ const result = await sql.unsafe("SELECT * FROM users WHERE id = :id", { id: 1 }) ### Execute and Cancelling Queries Queries are lazy: they only start executing when awaited or run with `.execute()`. -To cancel a running query, call `cancel()` on the query object. +To cancel a query, call `cancel()` on the query object. ```ts -const query = sql`SELECT * FROM users`.execute(); +const query = sql`SELECT pg_sleep(30)`.execute(); setTimeout(() => query.cancel(), 100); + +// PostgresError: canceling statement due to user request (SQLSTATE 57014) await query; ``` +On PostgreSQL, what `cancel()` does depends on how far the query got: + +- A query that was started and that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. +- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. The server also ignores a request that arrives before the query does, which can happen when you cancel a query with megabytes of parameters at once. A server that sent no cancel key when the connection opened, as some connection poolers do, cannot be asked: the query runs on. +- A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. + --- ## Database Environment Variables diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index 36d3d6e60311..4f5777597e83 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -470,7 +470,17 @@ declare module "bun" { cancelled: boolean; /** - * Cancels the executing query + * Requests cancellation of the query. + * + * For PostgreSQL, a query that was started and is not sent yet never runs. + * It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. A query the server is + * running is cancelled with a `CancelRequest` on a second connection. If + * the server stops the query, it rejects with SQLSTATE 57014. If the query + * finishes first, it resolves as usual, and the request can stop the next + * query on that connection instead. The server ignores a request that + * arrives before the query does. A query that was already sent behind + * another query rejects with `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, + * but the server still runs it. */ cancel(): Query; diff --git a/src/runtime/api/sql.classes.ts b/src/runtime/api/sql.classes.ts index c4c7ca8ef009..1f49e9df7f7f 100644 --- a/src/runtime/api/sql.classes.ts +++ b/src/runtime/api/sql.classes.ts @@ -89,7 +89,11 @@ for (const type of types) { length: 1, }, }, - values: ["pendingValue", "target", "columns", "binding"], + // `connection` lets a Postgres query find its BackendKeyData for cancel(). + values: + type === "PostgresSQL" + ? ["pendingValue", "target", "columns", "binding", "connection"] + : ["pendingValue", "target", "columns", "binding"], estimatedSize: true, }), ); diff --git a/src/runtime/hw_exports.rs b/src/runtime/hw_exports.rs index 350996358d76..209a65414deb 100644 --- a/src/runtime/hw_exports.rs +++ b/src/runtime/hw_exports.rs @@ -254,6 +254,11 @@ mod sql_hooks { // `ssl_config_from_js`; sql_jsc's `SSLConfig::drop` guards null/double. drop(unsafe { bun_core::heap::take(this.cast::()) }); } + unsafe fn ssl_config_clone(this: *const c_void) -> *mut c_void { + // SAFETY: `this` is a live boxed `SSLConfig` from `ssl_config_from_js`. + let config = unsafe { &*this.cast::() }.clone(); + bun_core::heap::into_raw(Box::new(config)).cast::() + } unsafe fn ssl_config_as_usockets_client( this: *const c_void, ) -> bun_uws::us_bun_socket_context_options_t { @@ -295,6 +300,7 @@ mod sql_hooks { ssl_ctx_get_or_create, ssl_config_from_js, ssl_config_free, + ssl_config_clone, ssl_config_as_usockets_client, ssl_config_server_name, ssl_config_reject_unauthorized, diff --git a/src/sql/postgres/AnyPostgresError.rs b/src/sql/postgres/AnyPostgresError.rs index e34482d4a086..cc78f3978ed5 100644 --- a/src/sql/postgres/AnyPostgresError.rs +++ b/src/sql/postgres/AnyPostgresError.rs @@ -28,6 +28,7 @@ pub enum AnyPostgresError { OutOfMemory, Overflow, PBKDFD2, + QueryCancelled, SASL_SIGNATURE_MISMATCH, SASL_SIGNATURE_INVALID_BASE64, ShortRead, diff --git a/src/sql/postgres/protocol/BackendKeyData.rs b/src/sql/postgres/protocol/BackendKeyData.rs index 3f94f1339b95..33e27e8ec2dd 100644 --- a/src/sql/postgres/protocol/BackendKeyData.rs +++ b/src/sql/postgres/protocol/BackendKeyData.rs @@ -1,9 +1,26 @@ use super::new_reader::NewReader; use crate::postgres::AnyPostgresError; -pub struct BackendKeyData {} +/// CancelRequest's stand-in for the protocol version: `(1234 << 16) | 5678`. +const CANCEL_REQUEST_CODE: u32 = 80877102; + +pub struct BackendKeyData { + pub process_id: u32, + pub secret_key: u32, +} impl BackendKeyData { + /// `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`: no type byte, it + /// is the only message on a connection opened just to carry it. + pub fn cancel_request(&self) -> [u8; 16] { + let mut packet = [0u8; 16]; + packet[0..4].copy_from_slice(&16u32.to_be_bytes()); + packet[4..8].copy_from_slice(&CANCEL_REQUEST_CODE.to_be_bytes()); + packet[8..12].copy_from_slice(&self.process_id.to_be_bytes()); + packet[12..16].copy_from_slice(&self.secret_key.to_be_bytes()); + packet + } + pub fn decode_internal( mut reader: NewReader, ) -> Result { @@ -11,9 +28,9 @@ impl BackendKeyData { return Err(AnyPostgresError::InvalidBackendKeyData); } - // process_id, secret_key - reader.int4()?; - reader.int4()?; - Ok(Self {}) + Ok(Self { + process_id: reader.int4()?, + secret_key: reader.int4()?, + }) } } diff --git a/src/sql/postgres/protocol/ErrorResponse.rs b/src/sql/postgres/protocol/ErrorResponse.rs index 1181f8437a8e..a179e0f4b9d7 100644 --- a/src/sql/postgres/protocol/ErrorResponse.rs +++ b/src/sql/postgres/protocol/ErrorResponse.rs @@ -30,6 +30,13 @@ impl ErrorResponse { } Ok(Self::default()) } + + /// SQLSTATE 57014: a cancel request or a timeout stopped the query. + pub fn is_query_canceled(&self) -> bool { + self.messages + .iter() + .any(|message| matches!(message, FieldMessage::Code(code) if code.eq_ascii(b"57014"))) + } } // `to_js` lives on an extension trait in the `bun_sql_jsc` crate. diff --git a/src/sql/shared/ConnectionFlags.rs b/src/sql/shared/ConnectionFlags.rs index ec85975fffe3..1c7ce9e58119 100644 --- a/src/sql/shared/ConnectionFlags.rs +++ b/src/sql/shared/ConnectionFlags.rs @@ -10,6 +10,8 @@ bitflags! { const HAS_BACKPRESSURE = 1 << 4; /// `ref()` was called; `on_data` must not unref the idle connection. const KEEP_ALIVE_REQUESTED = 1 << 5; + /// Postgres: exists only to deliver a CancelRequest in place of the StartupMessage. + const IS_CANCEL_REQUEST = 1 << 6; } } diff --git a/src/sql_jsc/jsc.rs b/src/sql_jsc/jsc.rs index 378017437dcb..05b57cc0aa51 100644 --- a/src/sql_jsc/jsc.rs +++ b/src/sql_jsc/jsc.rs @@ -238,6 +238,8 @@ pub struct SqlRuntimeHooks { pub ssl_config_from_js: unsafe fn(&JSGlobalObject, JSValue) -> *mut c_void, /// Drop a boxed `SSLConfig` returned by `ssl_config_from_js`. pub ssl_config_free: unsafe fn(*mut c_void), + /// Copy a boxed `SSLConfig` (caller frees via `ssl_config_free`). + pub ssl_config_clone: unsafe fn(*const c_void) -> *mut c_void, /// `SSLConfig::asUSocketsForClientVerification`. pub ssl_config_as_usockets_client: unsafe fn(*const c_void) -> bun_uws::us_bun_socket_context_options_t, @@ -477,6 +479,15 @@ pub mod api { } } + impl Clone for SSLConfig { + fn clone(&self) -> Self { + Self(self.0.and_then(|p| { + // SAFETY: `p` is a live boxed SSLConfig; the hook returns a fresh box. + NonNull::new(unsafe { (hooks().ssl_config_clone)(p.as_ptr()) }) + })) + } + } + impl SSLConfig { /// `SSLConfig.server_name` — the SNI hostname C string, or null /// when unset / default. @@ -660,6 +671,7 @@ pub mod codegen { impl_js_class { binding, columns, + connection, pendingValue, target } diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index a3af1fcb24ca..1ee4249a7d87 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -454,40 +454,52 @@ pub(crate) enum EncodeRequest<'a> { } impl PostgresSQLConnection { - /// The only caller of the batch writers above. + /// The only caller of the batch writers above. Nothing stays in the buffer for a `request` that its own parameter got rejected. pub(crate) fn encode_request( &self, global: &JSGlobalObject, - request: EncodeRequest<'_>, + request: &PostgresSQLQuery, + batch: EncodeRequest<'_>, ) -> Result<(), AnyPostgresError> { - let writer = self.writer(); - match request { - EncodeRequest::BindAndExecute { - statement, - binding_value, - columns_value, - } => bind_and_execute(global, statement, binding_value, columns_value, writer), - EncodeRequest::ParseBindAndExecute { - query, - statement, - binding_value, - columns_value, - include_describe, - } => parse_and_bind_and_execute( - global, - query, - statement, - binding_value, - columns_value, - include_describe, - writer, - ), - EncodeRequest::PrepareAndQuery { - query, - signature, - binding_value, - } => prepare_and_query_with_signature(global, query, binding_value, writer, signature), - } + self.writer().atomically(|writer| { + match batch { + EncodeRequest::BindAndExecute { + statement, + binding_value, + columns_value, + } => bind_and_execute(global, statement, binding_value, columns_value, writer), + EncodeRequest::ParseBindAndExecute { + query, + statement, + binding_value, + columns_value, + include_describe, + } => parse_and_bind_and_execute( + global, + query, + statement, + binding_value, + columns_value, + include_describe, + writer, + ), + EncodeRequest::PrepareAndQuery { + query, + signature, + binding_value, + } => prepare_and_query_with_signature( + global, + query, + binding_value, + writer, + signature, + ), + }?; + if request.is_rejected() { + return Err(AnyPostgresError::QueryCancelled); + } + Ok(()) + }) } } diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index d6b87a535944..1525a99d340e 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -52,6 +52,9 @@ pub use bun_sql::postgres::TLSStatus as TlsStatus; type Socket = uws::AnySocket; +/// The longest that the connection that delivers a CancelRequest lives, from dial to hang-up. +const CANCEL_REQUEST_TIMEOUT_MS: i32 = 5_000; + bun_core::define_scoped_log!(debug, Postgres, visible); const MAX_PIPELINE_SIZE: usize = u16::MAX as usize; // about 64KB per connection @@ -137,9 +140,12 @@ pub struct PostgresSQLConnection { pub(crate) js_value: JsCell, pub(crate) backend_parameters: JsCell, + pub(crate) backend_key_data: JsCell>, + /// What a cancel connection stops, until it writes the CancelRequest or fails. + cancel_target: JsCell>, // Self-referential — `database`/`user`/`password`/`path`/`options` are slices - // into `options_buf` (built via StringBuilder in `call`). Struct is Box-allocated + // into `options_buf` (built by `ConnectionStrings::new`). Struct is Box-allocated // and never moves (intrusive refcount), so the `RawSlice` backing-outlives-holder // invariant holds. Private — reassigning `options_buf` is UAF. // Reach via `database()`/`user()`/`password()`/`path()`/`options()`. @@ -267,9 +273,7 @@ impl PostgresSQLConnection { // ---- self-referential connection-string slices ---------------------------- // `database`/`user`/`password`/`path`/`options` are raw `*const [u8]` fat - // pointers into `self.options_buf`. They are populated once in `call()` (each - // initialised to `b""` then re-pointed at the StringBuilder allocation that - // becomes `options_buf`) and never reassigned. The struct is Box-allocated + // pointers into `self.options_buf`. `open` sets them once. The struct is Box-allocated // via `heap::alloc` and freed only when the intrusive refcount hits zero, // so `options_buf` — and thus every slice — remains valid for any `&self`. // @@ -512,7 +516,10 @@ impl PostgresSQLConnection { })); // ext is now repointed; safe to kick the handshake (any dispatch lands here). sock.start_tls_handshake(); - self.start(); + // A cancel connection decides what to write when the handshake has ended. + if !self.is_cancel_request() { + self.start(); + } } fn setup_max_lifetime_timer_if_necessary(&self) { @@ -598,9 +605,18 @@ impl PostgresSQLConnection { ); } + fn is_cancel_request(&self) -> bool { + self.flags + .get() + .contains(ConnectionFlags::IS_CANCEL_REQUEST) + } + fn start(&self) { self.setup_max_lifetime_timer_if_necessary(); - self.reset_connection_timeout(); + // A cancel connection has one time budget, from dial to hang-up. + if !self.is_cancel_request() { + self.reset_connection_timeout(); + } self.send_startup_message(); self.drain_internal(); @@ -735,6 +751,8 @@ impl PostgresSQLConnection { } self.status.set(Status::Failed); + // A cancel connection that fails before it writes lets go of its session and query here. + self.cancel_target.set(None); let _guard = self.ref_guard(); // we defer the refAndClose so the on_close will be called first before we reject the pending requests @@ -833,6 +851,17 @@ impl PostgresSQLConnection { } debug!("sendStartupMessage"); self.status.set(Status::SentStartupMessage); + if self.is_cancel_request() { + let target = self.cancel_target.with_mut(Option::take); + let Some(packet) = target.and_then(|target| target.cancel_request()) else { + self.fail(b"Connection closed", AnyPostgresError::ConnectionClosed); + return; + }; + if let Err(err) = self.writer().write(&packet) { + self.fail(b"Failed to write cancel request", err); + } + return; + } let msg = protocol::StartupMessage { user: Data::Temporary(self.user), database: Data::Temporary(self.database), @@ -927,6 +956,7 @@ impl PostgresSQLConnection { if !ok { let v = verify_error_to_js(&ssl_error, self.global()); self.fail_with_js_value(v); + return; } } } @@ -934,6 +964,9 @@ impl PostgresSQLConnection { SSLMode::Require | SSLMode::Prefer | SSLMode::Disable => {} } } + if self.is_cancel_request() { + self.start(); + } } else { // if we are here is because server rejected us, and the error_no is the cause of this // no matter if reject_unauthorized is false because we are disconnected by the server @@ -980,6 +1013,11 @@ impl PostgresSQLConnection { pub(crate) fn on_data(&self, data: &[u8]) { let _guard = self.ref_guard(); + if self.is_cancel_request() && self.status.get() == Status::SentStartupMessage { + // A server answers a CancelRequest by hanging up, so this is no server to talk to. + self.fail(b"Connection closed", AnyPostgresError::ConnectionClosed); + return; + } self.update_flags(|f| f.insert(ConnectionFlags::IS_PROCESSING_DATA)); if self.status.get() == Status::Connected { @@ -1095,71 +1133,26 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR }; let (secure, tls_config) = (args.secure, args.tls_config); - // `StringBuilder::append` takes `&mut self` and returns a borrow - // of the backing buffer, so successive appends can't keep their `&[u8]` - // results live across each other. The buffer is allocated once and never - // moved (`move_to_slice` hands back the same allocation), so detach each - // result to a `RawSlice` immediately — the struct stores them as - // `RawSlice` (self-referential into `options_buf`). - let username: bun_ptr::RawSlice; - let password: bun_ptr::RawSlice; - let database: bun_ptr::RawSlice; - let options: bun_ptr::RawSlice; - let path: bun_ptr::RawSlice; - let options_str = arguments[7].to_bun_string(global_object)?; - let path_str = arguments[8].to_bun_string(global_object)?; - - let options_buf: Box<[u8]> = 'brk: { - let mut b = bun_core::StringBuilder::default(); - b.cap += args.username_str.utf8_byte_length() - + 1 - + args.password_str.utf8_byte_length() - + 1 - + args.database_str.utf8_byte_length() - + 1 - + options_str.utf8_byte_length() - + 1 - + path_str.utf8_byte_length() - + 1; - - let _ = b.allocate(); - let u = args.username_str.to_utf8(); - username = bun_ptr::RawSlice::new(b.append(u.slice())); - drop(u); - - let p = args.password_str.to_utf8(); - password = bun_ptr::RawSlice::new(b.append(p.slice())); - drop(p); - - let d = args.database_str.to_utf8(); - database = bun_ptr::RawSlice::new(b.append(d.slice())); - drop(d); - - let o = options_str.to_utf8(); - options = bun_ptr::RawSlice::new(b.append(o.slice())); - drop(o); - - let _path = path_str.to_utf8(); - path = bun_ptr::RawSlice::new(b.append(_path.slice())); - drop(_path); - - break 'brk b.move_to_slice(); - }; + let (username, password, database, options, path) = ( + args.username_str.to_utf8(), + args.password_str.to_utf8(), + args.database_str.to_utf8(), + options_str.to_utf8(), + path_str.to_utf8(), + ); // Reject null bytes in connection parameters to prevent Postgres startup // message parameter injection (null bytes act as field terminators in the // wire protocol's key\0value\0 format). for (entry, name) in [ - (username, &b"username"[..]), - (password, b"password"), - (database, b"database"), - (path, b"path"), + (username.slice(), &b"username"[..]), + (password.slice(), b"password"), + (database.slice(), b"database"), + (path.slice(), b"path"), ] { - let entry = entry.slice(); if !entry.is_empty() && strings::contains_char(entry, 0) { - drop(options_buf); return Err(global_object.throw_invalid_arguments(format_args!( "{} must not contain null bytes", bstr::BStr::new(name) @@ -1167,129 +1160,261 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR } } - let on_connect = arguments[9]; - let on_close = arguments[10]; - let idle_timeout = arguments[11].to_int32(); - let connection_timeout = arguments[12].to_int32(); - let max_lifetime = arguments[13].to_int32(); - let use_unnamed_prepared_statements = arguments[14].as_boolean(); - - let ptr: *mut PostgresSQLConnection = - bun_core::heap::into_raw(Box::new(PostgresSQLConnection { - socket: JsCell::new(Socket::SocketTcp(uws::SocketTCP { - socket: uws::InternalSocket::Detached, - })), - status: Cell::new(Status::Connecting), - ref_count: Cell::new(1), - write_buffer: JsCell::new(OffsetByteList::default()), - write_epoch: Cell::new(0), - read_buffer: JsCell::new(OffsetByteList::default()), - last_message_start: Cell::new(0), - requests: JsCell::new(PostgresRequest::Queue::new()), - pipelined_requests: Cell::new(0), - nonpipelinable_requests: Cell::new(0), - pending_requests: Cell::new(0), - poll_ref: JsCell::new(KeepAlive::default()), - global_object: BackRef::new(global_object), - vm: BackRef::from( - core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"), + let hostname = args.hostname_str.to_utf8(); + PostgresSQLConnection::open( + global_object, + vm.postgres_socket_group::(context), + ConnectParams { + hostname: hostname.slice(), + port: args.port, + strings: ConnectionStrings::new( + username.slice(), + password.slice(), + database.slice(), + options.slice(), + path.slice(), ), - statements: JsCell::new(PreparedStatementsMap::default()), - prepared_statement_id: Cell::new(0), - pending_activity_count: AtomicU32::new(0), - js_value: JsCell::new(crate::jsc::JsRef::empty()), - backend_parameters: JsCell::new(StringMap::init(true)), - database, - user: username, + secure, + tls_config, + ssl_mode: args.ssl_mode, + idle_timeout: arguments[11].to_int32(), + connection_timeout: arguments[12].to_int32(), + max_lifetime: arguments[13].to_int32(), + use_unnamed_prepared_statements: arguments[14].as_boolean(), + on_connect: arguments[9], + on_close: arguments[10], + cancel: None, + }, + ) + .map_err(|err| { + global_object.throw_error( + bun_jsc::CrateError::from(err), + "failed to connect to postgresql", + ) + }) +} + +/// The strings of a connection, in one buffer that moves into the connection with them. +pub(crate) struct ConnectionStrings { + buf: Box<[u8]>, + user: bun_ptr::RawSlice, + password: bun_ptr::RawSlice, + database: bun_ptr::RawSlice, + options: bun_ptr::RawSlice, + path: bun_ptr::RawSlice, +} + +impl ConnectionStrings { + pub(crate) fn new( + user: &[u8], + password: &[u8], + database: &[u8], + options: &[u8], + path: &[u8], + ) -> Self { + let mut b = bun_core::StringBuilder::default(); + for string in [user, password, database, options, path] { + b.count_z(string); + } + let _ = b.allocate(); + // The buffer never moves again, so each slice can outlive the borrow of `b`. + let user = bun_ptr::RawSlice::new(b.append_z(user).as_bytes()); + let password = bun_ptr::RawSlice::new(b.append_z(password).as_bytes()); + let database = bun_ptr::RawSlice::new(b.append_z(database).as_bytes()); + let options = bun_ptr::RawSlice::new(b.append_z(options).as_bytes()); + let path = bun_ptr::RawSlice::new(b.append_z(path).as_bytes()); + Self { + buf: b.move_to_slice(), + user, password, - path, + database, options, - options_buf, - authentication_state: JsCell::new(AuthenticationState::Pending), + path, + } + } +} + +/// What `PostgresSQLConnection::open` builds a connection from. +pub(crate) struct ConnectParams<'a> { + /// Dialed when the path of `strings` is empty. + pub hostname: &'a [u8], + pub port: i32, + pub strings: ConnectionStrings, + pub secure: Option, + pub tls_config: jsc::api::ServerConfig::SSLConfig, + pub ssl_mode: SSLMode, + pub idle_timeout: i32, + pub connection_timeout: i32, + pub max_lifetime: i32, + pub use_unnamed_prepared_statements: bool, + pub on_connect: JSValue, + pub on_close: JSValue, + /// Set for a connection that only delivers the CancelRequest for this target. + pub cancel: Option, +} + +/// The query that a cancel connection stops, and the session whose backend runs it. +pub(crate) struct CancelTarget { + session: RefPtr, + request: RefPtr, +} + +impl CancelTarget { + /// `None` when the session is still connected and its backend runs another query by now. + fn cancel_request(&self) -> Option<[u8; 16]> { + let session = &*self.session; + if session.status.get() == Status::Connected && !session.is_running(&self.request) { + return None; + } + let key = session.backend_key_data.get().as_ref()?; + Some(key.cancel_request()) + } +} + +impl PostgresSQLConnection { + /// Allocates the connection, dials it in `group` and wraps it for JS. + pub(crate) fn open( + global_object: &JSGlobalObject, + group: &mut bun_uws::SocketGroup, + params: ConnectParams<'_>, + ) -> Result { + let ConnectParams { + hostname, + port, + strings: + ConnectionStrings { + buf: options_buf, + user: username, + password, + database, + options, + path, + }, secure, tls_config, - tls_status: Cell::new(if args.ssl_mode != SSLMode::Disable { - TLSStatus::Pending - } else { - TLSStatus::None - }), - ssl_mode: args.ssl_mode, - idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), - connection_timeout_ms: u32::try_from(connection_timeout).expect("int cast"), - flags: Cell::new(if use_unnamed_prepared_statements { - ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS + ssl_mode, + idle_timeout, + connection_timeout, + max_lifetime, + use_unnamed_prepared_statements, + on_connect, + on_close, + cancel, + } = params; + let mut flags = ConnectionFlags::empty(); + flags.set( + ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS, + use_unnamed_prepared_statements, + ); + flags.set(ConnectionFlags::IS_CANCEL_REQUEST, cancel.is_some()); + + let ptr: *mut PostgresSQLConnection = + bun_core::heap::into_raw(Box::new(PostgresSQLConnection { + socket: JsCell::new(Socket::SocketTcp(uws::SocketTCP { + socket: uws::InternalSocket::Detached, + })), + status: Cell::new(Status::Connecting), + ref_count: Cell::new(1), + write_buffer: JsCell::new(OffsetByteList::default()), + write_epoch: Cell::new(0), + read_buffer: JsCell::new(OffsetByteList::default()), + last_message_start: Cell::new(0), + requests: JsCell::new(PostgresRequest::Queue::new()), + pipelined_requests: Cell::new(0), + nonpipelinable_requests: Cell::new(0), + pending_requests: Cell::new(0), + poll_ref: JsCell::new(KeepAlive::default()), + global_object: BackRef::new(global_object), + vm: BackRef::from( + core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"), + ), + statements: JsCell::new(PreparedStatementsMap::default()), + prepared_statement_id: Cell::new(0), + pending_activity_count: AtomicU32::new(0), + js_value: JsCell::new(crate::jsc::JsRef::empty()), + backend_parameters: JsCell::new(StringMap::init(true)), + backend_key_data: JsCell::new(None), + cancel_target: JsCell::new(cancel), + database, + user: username, + password, + path, + options, + options_buf, + authentication_state: JsCell::new(AuthenticationState::Pending), + secure, + tls_config, + tls_status: Cell::new(if ssl_mode != SSLMode::Disable { + TLSStatus::Pending + } else { + TLSStatus::None + }), + ssl_mode, + idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), + connection_timeout_ms: u32::try_from(connection_timeout).expect("int cast"), + flags: Cell::new(flags), + timer: JsCell::new(EventLoopTimer::init_paused( + EventLoopTimerTag::PostgresSQLConnectionTimeout, + )), + max_lifetime_interval_ms: u32::try_from(max_lifetime).expect("int cast"), + max_lifetime_timer: JsCell::new(EventLoopTimer::init_paused( + EventLoopTimerTag::PostgresSQLConnectionMaxLifetime, + )), + auto_flusher: JsCell::new(AutoFlusher::default()), + channel_names: JsCell::new(Vec::new()), + })); + + // Sole owner until `to_js` below. Every field is interior-mutable. + let this = ParentRef::from(core::ptr::NonNull::new(ptr).expect("heap::into_raw non-null")); + + { + // Plain TCP in every sslmode: `setup_tls` adopts the socket after the server's `S`. + let path_slice = this.path.slice(); + let result = if !path_slice.is_empty() { + uws::SocketTCP::connect_unix_group( + group, + uws::SocketKind::Postgres, + None, + path_slice, + ptr, + false, + ) } else { - ConnectionFlags::empty() - }), - timer: JsCell::new(EventLoopTimer::init_paused( - EventLoopTimerTag::PostgresSQLConnectionTimeout, - )), - max_lifetime_interval_ms: u32::try_from(max_lifetime).expect("int cast"), - max_lifetime_timer: JsCell::new(EventLoopTimer::init_paused( - EventLoopTimerTag::PostgresSQLConnectionMaxLifetime, - )), - auto_flusher: JsCell::new(AutoFlusher::default()), - channel_names: JsCell::new(Vec::new()), - })); + uws::SocketTCP::connect_group( + group, + uws::SocketKind::Postgres, + None, + hostname, + port, + ptr, + false, + ) + }; - // `heap::into_raw` is `Box::into_raw` — never null. Sole owner until - // `to_js` below. R-2: every field is interior-mutable, so a shared - // `ParentRef` deref is sufficient for the writes below. - let this = ParentRef::from(core::ptr::NonNull::new(ptr).expect("heap::into_raw non-null")); - - { - let hostname = args.hostname_str.to_utf8(); - - // Postgres always opens plain TCP first (SSLRequest happens in-band), - // so even `ssl_mode != .disable` lands in the TCP group; `setupTLS()` - // adopts into `postgres_tls_group` after the server's `S`. - let group = vm.postgres_socket_group::(context); - let path_slice = this.path.slice(); - let result = if !path_slice.is_empty() { - uws::SocketTCP::connect_unix_group( - group, - uws::SocketKind::Postgres, - None, - path_slice, - ptr, - false, - ) - } else { - uws::SocketTCP::connect_group( - group, - uws::SocketKind::Postgres, - None, - hostname.slice(), - args.port, - ptr, - false, - ) - }; + this.socket.set(Socket::SocketTcp(match result { + Ok(s) => s, + Err(err) => { + // SAFETY: fresh allocation, sole ref. + drop(unsafe { bun_core::heap::take(ptr) }); + return Err(err); + } + })); + } - this.socket.set(Socket::SocketTcp(match result { - Ok(s) => s, - Err(err) => { - // SAFETY: fresh allocation, sole ref. - drop(unsafe { bun_core::heap::take(ptr) }); - return Err(global_object.throw_error( - bun_jsc::CrateError::from(err), - "failed to connect to postgresql", - )); - } - })); + // only call toJS if connectUnixAnon does not fail immediately + this.update_has_pending_activity(); + this.reset_connection_timeout(); + this.poll_ref.with_mut(|r| r.ref_(this.vm_ctx())); + let js_value = js::to_js(ptr, global_object); + js_value.ensure_still_alive(); + this.js_value.set(crate::jsc::JsRef::init_weak(js_value)); + js::onconnect_set_cached(js_value, global_object, on_connect); + js::onclose_set_cached(js_value, global_object, on_close); + if !this.is_cancel_request() { + bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); + } + Ok(js_value) } - - // only call toJS if connectUnixAnon does not fail immediately - this.update_has_pending_activity(); - this.reset_connection_timeout(); - this.poll_ref.with_mut(|r| r.ref_(this.vm_ctx())); - let js_value = js::to_js(ptr, global_object); - js_value.ensure_still_alive(); - this.js_value.set(crate::jsc::JsRef::init_weak(js_value)); - js::onconnect_set_cached(js_value, global_object, on_connect); - js::onclose_set_cached(js_value, global_object, on_close); - bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); - Ok(js_value) } pub struct SocketHandler; @@ -1442,7 +1567,7 @@ impl PostgresSQLConnection { match request.status.get() { // pending we will fail the request and the stmt will be marked as error ConnectionClosed too QueryStatus::Pending => { - self.note_request_written(); + self.finish_request(&request); let Some(stmt) = request.statement_mut() else { // The deref/discard at the bottom of the loop is intentionally skipped here. continue; @@ -1539,6 +1664,141 @@ impl PostgresSQLConnection { .map(|req| ParentRef::from(req.as_non_null())) } + /// Whether `request` is the FIFO head, the one the backend is executing now. + pub(crate) fn is_current_request(&self, request: &PostgresSQLQuery) -> bool { + self.requests + .get() + .front() + .is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) + } + + /// Whether `request` is the FIFO head and the backend has not finished it. + fn is_running(&self, request: &PostgresSQLQuery) -> bool { + self.is_current_request(request) + && matches!( + request.status.get(), + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse + ) + } + + /// `Query.cancel()` on a request that was dispatched to this connection. + pub(crate) fn cancel(&self, request: &PostgresSQLQuery) { + let global = self.global(); + match request.status.get() { + QueryStatus::Success | QueryStatus::Fail => {} + // Its Bind, Execute or Query is not written, and a request that failed never writes one. + QueryStatus::Pending => { + let err = postgres_error_to_js( + global, + Some(b"Query cancelled"), + AnyPostgresError::QueryCancelled, + ); + self.finish_request(request); + request.on_js_error(err, global); + } + // A CancelRequest names the backend process, so it stops what the backend runs: the FIFO head. + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse + if self.is_current_request(request) => + { + self.send_cancel_request(request); + } + // Written behind the head: the backend runs it whatever this client does. + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse => { + let err = postgres_error_to_js_with_hint( + global, + Some(b"Query cancelled"), + Some(b"The server already received this query and still runs it. Bun discards the result."), + AnyPostgresError::QueryCancelled, + ); + request.reject_in_flight(err, global); + } + } + } + + /// Asks the server, on a second connection like this one, to cancel `request`, which this backend runs. + fn send_cancel_request(&self, request: &PostgresSQLQuery) { + // A server that sent no BackendKeyData cannot be asked. + if self.backend_key_data.get().is_none() { + return; + } + let socket = self.socket.get(); + let uws::InternalSocket::Connected(raw) = *socket.socket() else { + return; + }; + + // The peer address, not the host name: the name can resolve to another server. + let mut hostname = [0u8; 46]; + let mut hostname_len = 0; + let mut port = 0; + if self.path.slice().is_empty() { + let mut address = [0u8; 16]; + let (peer, peer_port) = match socket { + Socket::SocketTcp(tcp) => (tcp.remote_address(&mut address), tcp.remote_port()), + Socket::SocketTls(tls) => (tls.remote_address(&mut address), tls.remote_port()), + }; + let (Some(peer), Some(peer_port)) = (peer, peer_port) else { + return; + }; + let ip: std::net::IpAddr = match *peer { + [a, b, c, d] => std::net::Ipv4Addr::new(a, b, c, d).into(), + _ => match <[u8; 16]>::try_from(peer) { + Ok(v6) => std::net::Ipv6Addr::from(v6).into(), + Err(_) => return, + }, + }; + use std::io::Write as _; + let mut unwritten = &mut hostname[..]; + if write!(unwritten, "{ip}").is_err() { + return; + } + let unwritten = unwritten.len(); + hostname_len = hostname.len() - unwritten; + port = i32::from(peer_port); + } + + // SAFETY: `raw` is the live connected socket of this session, in a group of its context. + let group = unsafe { + bun_jsc::rare_data::SocketGroups::of((*raw).group()) + .postgres_group::(self.vm_mut().uws_loop()) + }; + // The connection timeout of this session when that is the shorter one. + let connection_timeout = match i32::try_from(self.connection_timeout_ms) { + Ok(session @ 1..) => session.min(CANCEL_REQUEST_TIMEOUT_MS), + _ => CANCEL_REQUEST_TIMEOUT_MS, + }; + let dialed = Self::open( + self.global(), + group, + ConnectParams { + hostname: &hostname[..hostname_len], + port, + strings: ConnectionStrings::new(b"", b"", b"", b"", self.path.slice()), + secure: self.secure.clone(), + tls_config: self.tls_config.clone(), + // Encrypted exactly when this session is, whatever `prefer` would allow. + ssl_mode: match (self.tls_status.get(), self.ssl_mode) { + (TLSStatus::SslOk, SSLMode::Prefer) => SSLMode::Require, + (TLSStatus::SslOk, mode) => mode, + _ => SSLMode::Disable, + }, + idle_timeout: 0, + connection_timeout, + max_lifetime: 0, + use_unnamed_prepared_statements: false, + on_connect: JSValue::ZERO, + on_close: JSValue::ZERO, + cancel: Some(CancelTarget { + session: self.ref_guard(), + request: request.ref_guard(), + }), + }, + ); + // Best effort: a cancel that cannot be dialed leaves the query running. + if let Err(err) = dialed { + debug!("cancel request not dialed: {:?}", err); + } + } + /// Pop the FIFO head if it is still `request` (re-entrant JS may already /// have removed it), dropping the queue's ref. #[inline] @@ -1561,18 +1821,14 @@ impl PostgresSQLConnection { || self.current().is_some() } + /// Counts `request` as queued with its Bind, Execute or Query not written. #[inline] - pub(crate) fn note_request_pending(&self) { + pub(crate) fn note_request_pending(&self, request: &PostgresSQLQuery) { + debug_assert!(request.flags.get().counter == RequestCounter::None); + request.update_flags(|f| f.counter = RequestCounter::Pending); self.pending_requests.set(self.pending_requests.get() + 1); } - #[inline] - pub(crate) fn note_request_written(&self) { - let n = self.pending_requests.get(); - debug_assert!(n > 0, "pending_requests underflow"); - self.pending_requests.set(n.wrapping_sub(1)); - } - pub(crate) fn can_pipeline(&self) -> bool { if bun_core::env_var::feature_flag::BUN_FEATURE_FLAG_DISABLE_SQL_AUTO_PIPELINING .get() @@ -1779,32 +2035,19 @@ impl PostgresSQLConnection { } } - fn finish_request(&self, item: &PostgresSQLQuery) { - match item.status.get() { - QueryStatus::Running | QueryStatus::Binding | QueryStatus::PartialResponse => { - let counter = item.flags.get().counter; - item.update_flags(|f| f.counter = RequestCounter::None); - match counter { - RequestCounter::None => {} - RequestCounter::Nonpipelinable => { - let n = self.nonpipelinable_requests.get(); - debug_assert!(n > 0, "nonpipelinable_requests underflow"); - self.nonpipelinable_requests.set(n.saturating_sub(1)); - } - RequestCounter::Pipelined => { - let n = self.pipelined_requests.get(); - debug_assert!(n > 0, "pipelined_requests underflow"); - self.pipelined_requests.set(n.saturating_sub(1)); - } - } - } - QueryStatus::Pending => { - // ErrorResponse on a Parse-in-flight request: it never reached - // Binding, so account for it leaving the pending set here. - self.note_request_written(); - } - QueryStatus::Success | QueryStatus::Fail => {} - } + /// Takes `item` out of the connection counter it is in. A second call does nothing. + pub(crate) fn finish_request(&self, item: &PostgresSQLQuery) { + let counter = item.flags.get().counter; + item.update_flags(|f| f.counter = RequestCounter::None); + let counted = match counter { + RequestCounter::None => return, + RequestCounter::Pending => &self.pending_requests, + RequestCounter::Nonpipelinable => &self.nonpipelinable_requests, + RequestCounter::Pipelined => &self.pipelined_requests, + }; + let n = counted.get(); + debug_assert!(n > 0, "request counter underflow"); + counted.set(n.saturating_sub(1)); } /// What a request rejects with for a row the client cannot decode. `Err`: the VM is stopping. @@ -1851,6 +2094,10 @@ impl PostgresSQLConnection { req.on_js_error(err_, self.global()); return; } + // `encode_request` stopped for a request that was already rejected. + if req.status.get() == QueryStatus::Fail { + return; + } if let Some(statement) = new_statement { statement.status = StatementStatus::Failed; statement.error_response = Some(StatementError::PostgresError(err)); @@ -1897,7 +2144,7 @@ impl PostgresSQLConnection { // few paths below that keep it Pending (can't execute yet / // Parse written but not Bind / statement still Parsing) undo // this via note_request_pending() before returning/continuing. - self.note_request_written(); + self.finish_request(&req); if req.flags.get().simple { if self.pipelined_requests.get() > 0 || !self @@ -1913,7 +2160,7 @@ impl PostgresSQLConnection { .contains(ConnectionFlags::IS_READY_FOR_QUERY) ); // need to wait for the previous request to finish before starting simple queries - self.note_request_pending(); + self.note_request_pending(&req); defer_cleanup!(self); return; } @@ -2004,6 +2251,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::ParseBindAndExecute { query: query_str.slice(), statement, @@ -2031,6 +2279,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::BindAndExecute { statement, binding_value, @@ -2078,7 +2327,7 @@ impl PostgresSQLConnection { "need to wait to finish the pipeline before starting a new query preparation" ); // need to wait to finish the pipeline before starting a new query preparation - self.note_request_pending(); + self.note_request_pending(&req); defer_cleanup!(self); return; } @@ -2110,6 +2359,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::PrepareAndQuery { query: query_str.slice(), signature: &mut statement.signature, @@ -2174,6 +2424,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::ParseBindAndExecute { query: query_str.slice(), statement, @@ -2244,20 +2495,20 @@ impl PostgresSQLConnection { statement.status = StatementStatus::Parsing; // Parse+Describe+Sync written; Bind+Execute deferred to the // next advance(), so the request is still pending on the wire. - self.note_request_pending(); + self.note_request_pending(&req); self.flush_data_and_reset_timeout(); defer_cleanup!(self); return; } StatementStatus::Parsing => { // we are still parsing, lets wait for it to be prepared or failed - self.note_request_pending(); + self.note_request_pending(&req); offset += 1; continue; } } } else { - self.note_request_pending(); + self.note_request_pending(&req); offset += 1; continue; } @@ -2431,7 +2682,7 @@ impl PostgresSQLConnection { return Err(err); } let js_err = self.undecodable_row_error(err)?; - request.on_undecodable_row(js_err, self.global()); + request.reject_in_flight(js_err, self.global()); return Ok(()); } @@ -2455,7 +2706,7 @@ impl PostgresSQLConnection { Ok(result) => result, Err(err) => { let js_err = self.undecodable_row_error(err)?; - request.on_undecodable_row(js_err, self.global()); + request.reject_in_flight(js_err, self.global()); return Ok(()); } }; @@ -2945,7 +3196,10 @@ impl PostgresSQLConnection { } } MessageType::BackendKeyData => { - let _ = protocol::BackendKeyData::decode_internal(reader.reborrow())?; + self.backend_key_data + .set(Some(protocol::BackendKeyData::decode_internal( + reader.reborrow(), + )?)); } MessageType::ErrorResponse => { let err = protocol::ErrorResponse::decode_internal(reader.reborrow())?; @@ -2973,7 +3227,10 @@ impl PostgresSQLConnection { let js_err = crate::postgres::protocol::error_response_jsc::to_js(&err, self.global()); if let Some(stmt) = request.statement_mut() { - if stmt.status == StatementStatus::Parsing { + if stmt.status == StatementStatus::Parsing && err.is_query_canceled() { + // A canceled Parse says nothing about the statement: the next request parses it again. + stmt.status = StatementStatus::Pending; + } else if stmt.status == StatementStatus::Parsing { stmt.status = StatementStatus::Failed; stmt.error_response = Some( crate::postgres::postgres_sql_statement::Error::Protocol(err), diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 31590b249bab..85572604f83b 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -78,7 +78,7 @@ pub struct Flags { pub(crate) binary: bool, pub(crate) bigint: bool, pub(crate) simple: bool, - /// Rejected for an undecodable row: in flight, its response skipped, until `ReadyForQuery`. + /// Rejected while in flight: its response is skipped until `ReadyForQuery`. pub(crate) discard_response: bool, /// Which connection counter this request's dispatch incremented; reset to /// `None` when `finish_request` consumes that contribution, so the @@ -90,6 +90,8 @@ pub struct Flags { #[derive(Clone, Copy, PartialEq, Eq)] pub enum RequestCounter { None, + /// `PostgresSQLConnection::pending_requests` + Pending, /// `PostgresSQLConnection::nonpipelinable_requests` Nonpipelinable, /// `PostgresSQLConnection::pipelined_requests` @@ -191,6 +193,7 @@ impl PostgresSQLQuery { let Some(this_value) = self.this_value.get().try_get() else { return; }; + Self::release_connection(this_value, global_object); let _downgrade = scopeguard::guard((), |_| self.this_value.with_mut(|r| r.downgrade())); let Some(target_value) = self.get_target(global_object, true) else { return; @@ -219,13 +222,19 @@ impl PostgresSQLQuery { ); } + /// The cached `connection` is a strong GC edge; every terminal path must + /// clear it or a retained `Query` pins the whole connection. + fn release_connection(this_value: JSValue, global_object: &JSGlobalObject) { + js::connection_set_cached(this_value, global_object, JSValue::ZERO); + } + pub(crate) fn on_js_error(&self, err: JSValue, global_object: &JSGlobalObject) { self.status.set(Status::Fail); self.reject(err, global_object); } /// Rejects now, but `status` stays in flight: the server is still answering this query. - pub(crate) fn on_undecodable_row(&self, err: JSValue, global_object: &JSGlobalObject) { + pub(crate) fn reject_in_flight(&self, err: JSValue, global_object: &JSGlobalObject) { self.update_flags(|f| f.discard_response = true); self.reject(err, global_object); } @@ -240,6 +249,7 @@ impl PostgresSQLQuery { let Some(this_value) = self.this_value.get().try_get() else { return; }; + Self::release_connection(this_value, global_object); let _downgrade = scopeguard::guard((), |_| self.this_value.with_mut(|r| r.downgrade())); let Some(target_value) = self.get_target(global_object, true) else { return; @@ -283,6 +293,7 @@ impl PostgresSQLQuery { js::binding_set_cached(this_value, global_object, JSValue::ZERO); js::pending_value_set_cached(this_value, global_object, JSValue::ZERO); js::target_set_cached(this_value, global_object, JSValue::ZERO); + Self::release_connection(this_value, global_object); } pub(crate) fn on_result( @@ -467,7 +478,8 @@ impl PostgresSQLQuery { // duration of this call, satisfying the `ParentRef` outlives-holder // invariant. R-2: shared borrow — every connection field accessed below is // `Cell`/`JsCell`. - let Some(connection) = postgres_sql_connection::js::from_js_ref(arguments[0]) else { + let connection_value = arguments[0]; + let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else { return Err( global_object.throw(format_args!("connection must be a PostgresSQLConnection")) ); @@ -491,6 +503,12 @@ impl PostgresSQLQuery { // is already pending. let throw_write_error = |msg: &[u8], err: AnyPostgresError| -> JsError { if !global_object.has_exception() { + // `cancel()` from the code of a parameter stopped the write. The write did not fail. + let msg = if matches!(err, AnyPostgresError::QueryCancelled) { + b"Query cancelled" + } else { + msg + }; return global_object.throw_value(postgres_error_to_js( global_object, Some(msg), @@ -548,7 +566,7 @@ impl PostgresSQLQuery { } connection.requests.with_mut(|q| q.push_back(queued)); if this.status.get() == Status::Pending { - connection.note_request_pending(); + connection.note_request_pending(this); } // Request is enqueued: keep the event loop alive until the server @@ -563,6 +581,7 @@ impl PostgresSQLQuery { this.this_value.with_mut(|r| r.upgrade(global_object)); js::target_set_cached(this_value, global_object, query); + js::connection_set_cached(this_value, global_object, connection_value); if this.status.get() == Status::Running { connection.flush_data_and_reset_timeout(); } else { @@ -594,6 +613,14 @@ impl PostgresSQLQuery { } }; + // The code of a binding ran, and it can have called `cancel()`. + if this.is_rejected() { + return Err(throw_write_error( + b"Query cancelled", + AnyPostgresError::QueryCancelled, + )); + } + let has_params = signature.fields.len() > 0; let mut did_write = false; 'enqueue: { @@ -642,6 +669,7 @@ impl PostgresSQLQuery { // bindAndExecute will bind + execute, it will change to running after binding is complete if let Err(err) = connection.encode_request( global_object, + this, EncodeRequest::BindAndExecute { statement: stmt, binding_value, @@ -701,6 +729,7 @@ impl PostgresSQLQuery { // prepareAndQueryWithSignature will write + bind + execute, it will change to running after binding is complete if let Err(err) = connection.encode_request( global_object, + this, EncodeRequest::PrepareAndQuery { query: query_str.slice(), signature: &mut signature, @@ -812,7 +841,7 @@ impl PostgresSQLQuery { connection.requests.with_mut(|q| q.push_back(queued)); if this.status.get() == Status::Pending { - connection.note_request_pending(); + connection.note_request_pending(this); } // Request is enqueued: keep the event loop alive until the server // responds. See the matching call in the simple-query branch above @@ -828,6 +857,7 @@ impl PostgresSQLQuery { this.this_value.with_mut(|r| r.upgrade(global_object)); js::target_set_cached(this_value, global_object, query); + js::connection_set_cached(this_value, global_object, connection_value); if did_write { connection.flush_data_and_reset_timeout(); } else { @@ -841,13 +871,21 @@ impl PostgresSQLQuery { pub fn do_cancel( this: &Self, - global_object: &JSGlobalObject, + _global_object: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { - let _ = callframe; - let _ = global_object; - let _ = this; - + // Set from the end of `do_run` until the query settles. + let Some(connection_value) = js::connection_get_cached(callframe.this()) else { + // Not dispatched, or the code of a parameter called this from inside `do_run`. + if this.status.get() == Status::Pending { + this.status.set(Status::Fail); + } + return Ok(JSValue::UNDEFINED); + }; + let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else { + return Ok(JSValue::UNDEFINED); + }; + connection.cancel(this); Ok(JSValue::UNDEFINED) } } diff --git a/src/sql_jsc/postgres/error_jsc.rs b/src/sql_jsc/postgres/error_jsc.rs index 54385930a370..e1f0ebdc953d 100644 --- a/src/sql_jsc/postgres/error_jsc.rs +++ b/src/sql_jsc/postgres/error_jsc.rs @@ -84,6 +84,7 @@ pub(crate) fn postgres_error_to_js_with_hint( NullsInArrayNotSupportedYet => b"ERR_POSTGRES_NULLS_IN_ARRAY_NOT_SUPPORTED_YET", Overflow => b"ERR_POSTGRES_OVERFLOW", PBKDFD2 => b"ERR_POSTGRES_AUTHENTICATION_FAILED_PBKDF2", + QueryCancelled => b"ERR_POSTGRES_QUERY_CANCELLED", SASL_SIGNATURE_MISMATCH => b"ERR_POSTGRES_SASL_SIGNATURE_MISMATCH", SASL_SIGNATURE_INVALID_BASE64 => b"ERR_POSTGRES_SASL_SIGNATURE_INVALID_BASE64", TLSNotAvailable => b"ERR_POSTGRES_TLS_NOT_AVAILABLE", diff --git a/test/js/sql/postgres-pending-dial-fixture.ts b/test/js/sql/postgres-pending-dial-fixture.ts new file mode 100644 index 000000000000..b1028f25c9fb --- /dev/null +++ b/test/js/sql/postgres-pending-dial-fixture.ts @@ -0,0 +1,102 @@ +// cancel() opens a second connection for a running query. This process is left +// with the dial of that connection, which never completes, and it has to exit +// on its own once the dial times out. +// +// The listener is a raw libc socket. Its backlog holds one connection, which no +// listener of Bun can ask for. `blackholePortSource` in harness.ts is the same +// listener, but it never accepts, and this one has to serve the session first. +// With the backlog full the kernel drops every SYN. +import { SQL } from "bun"; +import { dlopen, ptr } from "bun:ffi"; +import net from "node:net"; +import { pgAuthenticationOk, pgBackendKeyData, pgReadyForQuery } from "./wire-frames"; + +const darwin = process.platform === "darwin"; +const libc = dlopen(darwin ? "libSystem.B.dylib" : "libc.so.6", { + socket: { args: ["int", "int", "int"], returns: "int" }, + bind: { args: ["int", "ptr", "int"], returns: "int" }, + listen: { args: ["int", "int"], returns: "int" }, + getsockname: { args: ["int", "ptr", "ptr"], returns: "int" }, + accept: { args: ["int", "ptr", "ptr"], returns: "int" }, + poll: { args: ["ptr", "u64", "int"], returns: "int" }, + read: { args: ["int", "ptr", "usize"], returns: "int" }, + write: { args: ["int", "ptr", "usize"], returns: "int" }, + close: { args: ["int"], returns: "int" }, +}).symbols; + +const AF_INET = 2; +const SOCK_STREAM = 1; +const POLLIN = 1; + +const address = new Uint8Array(16); +if (darwin) { + address[0] = 16; + address[1] = AF_INET; +} else { + new DataView(address.buffer).setUint16(0, AF_INET, true); +} +address.set([127, 0, 0, 1], 4); +const listener = libc.socket(AF_INET, SOCK_STREAM, 0); +// The smallest backlog that admits one connection: macOS reads 0 as no limit. +if (listener < 0 || libc.bind(listener, ptr(address), 16) !== 0 || libc.listen(listener, darwin ? 1 : 0) !== 0) { + throw new Error("listen failed"); +} +if (libc.getsockname(listener, ptr(address), ptr(new Uint32Array([16]))) !== 0) { + throw new Error("getsockname failed"); +} +const port = (address[2] << 8) | address[3]; +const url = `postgres://postgres@127.0.0.1:${port}/postgres?sslmode=disable`; + +/** Resolves once a read of `fd`, or an accept from it, does not block. */ +async function readable(fd: number) { + const pollfd = new DataView(new ArrayBuffer(8)); + pollfd.setInt32(0, fd, true); + pollfd.setInt16(4, POLLIN, true); + while (libc.poll(ptr(pollfd), 1, 0) === 0) await new Promise(resolve => setImmediate(resolve)); +} + +/** From here on the kernel answers no SYN for `port`. */ +async function fillBacklog() { + const filler = net.connect(port, "127.0.0.1"); + await new Promise((resolve, reject) => filler.on("connect", resolve).on("error", reject)); + return filler; +} + +const code = (query: Promise) => + query.then( + () => "resolved", + err => err.code, + ); + +const sql = new SQL({ url, max: 1, connectionTimeout: 1 }); +const query = sql`select pg_sleep(10)`.simple(); +const settled = code(query); + +await readable(listener); +const session = libc.accept(listener, null, null); +if (session < 0) throw new Error("accept failed"); +const handshake = Buffer.concat([pgAuthenticationOk(), pgBackendKeyData(4242, 13371337), pgReadyForQuery()]); +if (libc.write(session, ptr(handshake), handshake.length) !== handshake.length) throw new Error("write failed"); + +// The startup message, then the query: Byte1('Q') Int32(length) String. With +// the whole query read, the query is the one the backend runs. +const received = Buffer.alloc(4096); +let length = 0; +const queryReceived = () => { + if (length < 4) return false; + const query = received.readUInt32BE(0); + return length >= query + 5 && length >= query + 1 + received.readUInt32BE(query + 1); +}; +while (!queryReceived()) { + await readable(session); + const read = libc.read(session, ptr(received, length), received.length - length); + if (read <= 0) throw new Error("the client closed the session"); + length += read; +} + +const filler = await fillBacklog(); +query.cancel(); +// The backend goes away. The cancel connection is still in its dial. +libc.close(session); +console.log(await settled); +filler.destroy(); diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts new file mode 100644 index 000000000000..0496484fdb98 --- /dev/null +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -0,0 +1,1117 @@ +// A backend that is running a query reads nothing from its connection until the +// query finishes, so the only way to stop it is the CancelRequest message on a +// *second* connection (protocol §55.2.3). Asserting those bytes, and asserting +// that they are NOT sent for a query the backend never started, needs a server +// that answers on demand, which is why this uses a scripted one instead of +// describeWithContainer. All wire bytes come from test/js/sql/wire-frames.ts. +// +// Query.cancel() used to be a no-op for Postgres: nothing was ever written, so a +// cancelled query ran to completion and resolved with its rows. +import { SQL } from "bun"; +import { heapStats } from "bun:jsc"; +import { expect, test } from "bun:test"; +import { + bunEnv, + bunExe, + describeWithContainer, + expiredTls, + isIPv6, + isMusl, + isWindows, + tempDir, + tls as tlsCert, +} from "harness"; +import { readFileSync } from "node:fs"; +import net from "node:net"; +import { join } from "node:path"; +import tls from "node:tls"; +import { + pgAuthenticationOk, + pgBackendKeyData, + pgBindComplete, + pgCancelRequest, + pgCommandComplete, + pgDataRow, + pgErrorResponse, + pgParameterDescription, + pgParseComplete, + pgReadFrontendMessages, + pgReadyForQuery, + pgRowDescription, +} from "./wire-frames"; + +const PROCESS_ID = 4242; +const SECRET_KEY = 13371337; +// text: its binary and text encodings are the same bytes, so the mock does not +// have to care whether Bun asked for binary results (it does for a statement it +// has already prepared). +const TEXT_OID = 25; + +// A certificate that names `localhost` and no address: both of its names are DNS entries. +const hostNameOnlyTls = { + cert: readFileSync(join(import.meta.dir, "docker-tls", "server.crt"), "utf8"), + key: readFileSync(join(import.meta.dir, "docker-tls", "server.key"), "utf8"), +}; + +// Int32(8) Int32(80877103): the one message a client sends in plaintext before TLS. +const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); + +/** + * Scripted Postgres backend. + * + * While `autoReply` is on it answers each query unit with one text row, which is + * what drives a statement to the Prepared state. With it off, queries are left + * unanswered the way a backend stuck inside pg_sleep() would leave them, and the + * test writes every reply itself. A CancelRequest always arrives on the second + * connection, because the first one is busy running the query. + * + * With `tls` every connection has to start with an SSLRequest. The backend answers + * `S` and reads everything else through TLS, and `plaintext` keeps what each + * connection sent in the clear. + * + * `cancelConnection` makes the second connection meet a server no real backend is: + * one that answers a CancelRequest like the start of a session and does not hang + * up, one that takes the CancelRequest and then stays silent, one that declines + * TLS, one whose certificate the session's CA did not sign, or one that stops in + * the dial until the test calls `answerCancelConnection()`: before it answers the + * SSLRequest, or after its `S` and before the TLS handshake. + */ +async function backend( + options: { + tls?: boolean; + certificate?: { cert: string; key: string }; + host?: string; + socketPath?: string; + cancelConnection?: + | "answers" + | "silent" + | "declines-tls" + | "other-certificate" + | "holds-ssl-answer" + | "holds-handshake"; + /** The BackendKeyData of the session. `null`: the server sends none. */ + key?: { processId: number; secretKey: number } | null; + } = {}, +) { + const host = options.host ?? "127.0.0.1"; + const plaintext: Buffer[] = []; + const cancelPacket = Promise.withResolvers(); + const cancelConnectionClosed = Promise.withResolvers(); + const cancelConnectionWaiting = Promise.withResolvers<() => void>(); + const queryConnectionClosed = Promise.withResolvers(); + const sockets = new Set(); + const waiters = new Map void>(); + let queryConnection: net.Socket | undefined; + let connections = 0; + let queryUnits = 0; + let frontendMessages = ""; + let autoReply = true; + let cancelPacketSeen = false; + const key = options.key === undefined ? { processId: PROCESS_ID, secretKey: SECRET_KEY } : options.key; + + // Answer a Parse+Describe+Bind+Execute with one text row: ParseComplete and + // the two Describe replies, then the Execute replies. + const preparedReply = () => + Buffer.concat([ + pgParseComplete(), + pgParameterDescription([]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("ok")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ]); + + function onQueryUnit() { + queryUnits++; + waiters.get(queryUnits)?.(); + if (autoReply) queryConnection!.write(preparedReply()); + } + + const server = net.createServer(rawSocket => { + sockets.add(rawSocket); + rawSocket.on("close", () => sockets.delete(rawSocket)); + rawSocket.on("error", () => {}); + const connection = ++connections; + if (!options.tls) return serve(connection, rawSocket); + + const cancel = connection > 1 ? options.cancelConnection : undefined; + if (connection > 1) rawSocket.on("close", () => cancelConnectionClosed.resolve()); + let buffered = Buffer.alloc(0); + const onPlaintext = (data: Buffer) => { + const answered = buffered.length >= SSL_REQUEST.length; + buffered = Buffer.concat([buffered, data]); + if (buffered.length < SSL_REQUEST.length) return; + if (cancel === "declines-tls") { + // Keep everything the client sends in the clear after it was told N. + plaintext[connection - 1] = buffered; + if (!answered) rawSocket.write("N"); + return; + } + plaintext[connection - 1] = buffered.subarray(0, SSL_REQUEST.length); + // What follows the SSLRequest is the ClientHello: hand it to the TLS engine. + rawSocket.removeListener("data", onPlaintext); + rawSocket.pause(); + const leftover = buffered.subarray(SSL_REQUEST.length); + if (leftover.length) rawSocket.unshift(leftover); + const handshake = () => { + const certificate = cancel === "other-certificate" ? expiredTls : (options.certificate ?? tlsCert); + const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); + secure.on("error", () => {}); + serve(connection, secure); + }; + if (cancel === "holds-ssl-answer") { + cancelConnectionWaiting.resolve(() => { + rawSocket.write("S"); + handshake(); + }); + } else if (cancel === "holds-handshake") { + rawSocket.write("S"); + // The ClientHello shows that the client is in the handshake now. + rawSocket.once("data", clientHello => { + rawSocket.pause(); + rawSocket.unshift(clientHello); + cancelConnectionWaiting.resolve(handshake); + }); + rawSocket.resume(); + } else { + rawSocket.write("S"); + handshake(); + } + }; + rawSocket.on("data", onPlaintext); + }); + + function serve(connection: number, socket: net.Socket) { + if (connection > 1) { + let buffered = Buffer.alloc(0); + socket.on("close", () => cancelConnectionClosed.resolve()); + socket.on("data", data => { + buffered = Buffer.concat([buffered, data]); + if (buffered.length < 16) return; + cancelPacketSeen = true; + cancelPacket.resolve(buffered); + if (options.cancelConnection === "silent") return; + // A real backend acts on the CancelRequest and hangs up. + if (options.cancelConnection !== "answers") return void socket.end(); + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + }); + return; + } + + queryConnection = socket; + socket.on("close", () => queryConnectionClosed.resolve()); + let handshaken = false; + let buffered = Buffer.alloc(0); + socket.on("data", data => { + if (!handshaken) { + handshaken = true; + socket.write( + Buffer.concat([ + pgAuthenticationOk(), + ...(key ? [pgBackendKeyData(key.processId, key.secretKey)] : []), + pgReadyForQuery(), + ]), + ); + return; + } + buffered = pgReadFrontendMessages(Buffer.concat([buffered, data]), type => { + // Sync ends every extended-protocol unit; the simple protocol's Query is + // its own sync point. + const message = String.fromCharCode(type); + frontendMessages += message; + if (message === "S" || message === "Q") onQueryUnit(); + }); + }); + } + await new Promise(resolve => + options.socketPath ? server.listen(options.socketPath, resolve) : server.listen(0, host, resolve), + ); + const port = options.socketPath ? 5432 : (server.address() as net.AddressInfo).port; + + return { + url: `postgres://postgres@${net.isIPv6(host) ? `[${host}]` : host}:${port}/postgres`, + /** What each connection sent before TLS, by connection order. */ + plaintext, + cancelPacket: cancelPacket.promise, + /** Resolves once the second connection is closed. */ + cancelConnectionClosed: cancelConnectionClosed.promise, + /** Resolves once the second connection has stopped in its dial, for the two modes that hold it. */ + cancelConnectionWaiting: cancelConnectionWaiting.promise.then(() => {}), + /** Lets the second connection finish its dial. */ + async answerCancelConnection() { + (await cancelConnectionWaiting.promise)(); + }, + get cancelPacketSeen() { + return cancelPacketSeen; + }, + /** Resolves once the client has closed the connection its queries run on. */ + queryConnectionClosed: queryConnectionClosed.promise, + get connections() { + return connections; + }, + /** How many complete query units the client has sent. */ + get queryUnits() { + return queryUnits; + }, + /** The type byte of each message the session has sent after its startup message. */ + get frontendMessages() { + return frontendMessages; + }, + set autoReply(value: boolean) { + autoReply = value; + }, + /** Resolves once the client has sent its `n`th complete query unit. */ + untilQueryUnits(n: number): Promise { + if (queryUnits >= n) return Promise.resolve(); + const { promise, resolve } = Promise.withResolvers(); + waiters.set(n, resolve); + return promise; + }, + /** Answer one Bind+Execute of a statement the backend already prepared. */ + answerPrepared(value: string) { + queryConnection!.write( + Buffer.concat([ + pgBindComplete(), + pgDataRow([Buffer.from(value)]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ]), + ); + }, + reply(...frames: Buffer[]) { + queryConnection!.write(Buffer.concat(frames)); + }, + async [Symbol.asyncDispose]() { + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(() => resolve())); + }, + }; +} + +// Both the extended protocol (the default) and the simple protocol put the +// query on the wire before the backend answers anything, so both are +// cancellable the same way. +const protocols: [name: string, start: (query: any) => any][] = [ + ["extended", query => query.execute()], + ["simple", query => query.simple().execute()], +]; + +test.each(protocols)("cancel() on a running %s query sends a CancelRequest", async (_name, start) => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = start(sql`select pg_sleep(10)`); + const settled = query.then( + (rows: unknown) => rows, + (err: any) => err, + ); + await server.untilQueryUnits(1); + + query.cancel(); + + // The CancelRequest names the backend by the pid/secret pair it handed out in + // BackendKeyData, on a connection of its own. + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + expect(server.connections).toBe(2); + + // A real backend answers the cancelled query on its own connection, with + // SQLSTATE 57014 (query_canceled). + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + + const err = await settled; + expect({ name: err.name, code: err.code, errno: err.errno, message: err.message }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_SERVER_ERROR", + errno: "57014", + message: "canceling statement due to user request", + }); +}); + +// The cancel connection has to reach the server the way the session does. A +// plaintext one leaks the cancel key of a TLS session, and a server that only +// accepts TLS never sees it. +const tlsSessions: [sslmode: string, options: (url: string) => object][] = [ + // `ca` alone makes the session verify-full, so the cancel connection only gets + // through the handshake if it uses the same TLS options. + ["verify-full", url => ({ url, tls: { ca: tlsCert.cert } })], + ["verify-ca", url => ({ url: `${url}?sslmode=verify-ca`, tls: { ca: tlsCert.cert } })], + ["require", url => ({ url: `${url}?sslmode=require` })], + ["prefer", url => ({ url: `${url}?sslmode=prefer` })], +]; +test.each(tlsSessions)( + "cancel() on a TLS session (sslmode=%s) sends the CancelRequest through TLS", + async (_sslmode, options) => { + await using server = await backend({ tls: true }); + server.autoReply = false; + await using sql = new SQL({ ...options(server.url), max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + // Both connections sent an SSLRequest in the clear, and nothing else. + expect(server.plaintext).toEqual([SSL_REQUEST, SSL_REQUEST]); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); + }, +); + +// A session that is encrypted must not lose its cancel key to a cancel connection +// that is not. `prefer` counts once the session has negotiated TLS. +test.each(["prefer", "require"])( + "cancel() on a TLS session (sslmode=%s) sends nothing when TLS is declined", + async sslmode => { + await using server = await backend({ tls: true, cancelConnection: "declines-tls" }); + server.autoReply = false; + await using sql = new SQL({ url: `${server.url}?sslmode=${sslmode}`, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + await server.cancelConnectionClosed; + // The SSLRequest, then nothing: no CancelRequest after the N. + expect(server.plaintext[1]).toEqual(SSL_REQUEST); + + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgCommandComplete("SELECT 0"), + pgReadyForQuery(), + ); + expect(await settled).toEqual([]); + }, +); + +test("cancel() on a verify-full session sends nothing to a server it cannot verify", async () => { + await using server = await backend({ tls: true, cancelConnection: "other-certificate" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + await server.cancelConnectionClosed; + expect({ plaintext: server.plaintext[1], cancelPacketSeen: server.cancelPacketSeen }).toEqual({ + plaintext: SSL_REQUEST, + cancelPacketSeen: false, + }); + + server.reply(pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), pgCommandComplete("SELECT 0"), pgReadyForQuery()); + expect(await settled).toEqual([]); +}); + +// The cancel connection dials the address of the session's peer, not its host +// name. The certificate still has to match the host name. This one names only +// `localhost`, so a check against the dialed address refuses it, as the session +// that is addressed by 127.0.0.1 shows. +test("cancel() on a verify-full session checks the certificate against the host name", async () => { + const tls = { ca: hostNameOnlyTls.cert }; + { + await using byAddress = await backend({ tls: true, certificate: hostNameOnlyTls }); + await using sql = new SQL({ url: byAddress.url, tls, max: 1, connectionTimeout: 5 }); + const err = await sql`select 1`.catch((e: any) => e); + expect(err.message).toBe("Hostname/IP does not match certificate's altnames"); + } + + await using server = await backend({ tls: true, certificate: hostNameOnlyTls, host: "localhost" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// URL parsing keeps the brackets of an IPv6 literal in the hostname. The session's +// connect strips them, so the cancel connection has to as well. +test.skipIf(!isIPv6())("cancel() reaches a server that is addressed by an IPv6 literal", async () => { + await using server = await backend({ host: "::1" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +test.skipIf(isWindows)("cancel() reaches a server on a unix socket", async () => { + using dir = tempDir("pg-cancel", {}); + const socketPath = join(String(dir), "pg.sock"); + await using server = await backend({ socketPath }); + server.autoReply = false; + await using sql = new SQL({ adapter: "postgres", path: socketPath, username: "postgres", max: 1 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// The cancel connection carries one packet. It must not turn into a session, with +// no timeout and no owner, because a server answers it. +test("the cancel connection closes when the server answers it", async () => { + await using server = await backend({ cancelConnection: "answers" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + await server.cancelConnectionClosed; + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// A server that takes the CancelRequest and then neither answers nor hangs up must +// not keep the cancel connection open. The cancel connection has the connection +// timeout of its session, 1 s here, from its dial to its end. +test("the cancel connection ends when the server stays silent after the CancelRequest", async () => { + await using server = await backend({ cancelConnection: "silent" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 1 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + await server.cancelConnectionClosed; + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// Some servers and poolers send no BackendKeyData. Then there is no key to send, +// and the query runs on. +test("cancel() on a running query opens no connection when the server sent no cancel key", async () => { + await using server = await backend({ key: null }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.simple().execute(); + await server.untilQueryUnits(1); + query.cancel(); + + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("done")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await query).toEqual([{ v: "done" }]); + // A cancel connection would have arrived by the end of one more round trip. + server.autoReply = true; + expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); + expect(server.connections).toBe(1); +}); + +// The process id in a cancel key is opaque to the client, and 0 is a value like any other. +test("cancel() sends a cancel key whose process id is 0", async () => { + await using server = await backend({ key: { processId: 0, secretKey: SECRET_KEY } }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(0, SECRET_KEY)); + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// The dial of the cancel connection is a TCP handshake and, for a TLS session, an +// SSLRequest and a TLS handshake. The query can end in that time, and a +// CancelRequest that is sent then stops the query that the backend runs next. So +// the cancel connection looks at its query again when the dial has ended, which +// for TLS is the end of the handshake. +test.each(["holds-ssl-answer", "holds-handshake"] as const)( + "the cancel connection sends nothing when its query ended during the dial (%s)", + async cancelConnection => { + await using server = await backend({ tls: true, cancelConnection }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + await server.untilQueryUnits(1); + query.cancel(); + await server.cancelConnectionWaiting; + + // The query ends by itself while the cancel connection is held in its dial. + server.reply( + pgParseComplete(), + pgParameterDescription([]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("done")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await query).toEqual([{ v: "done" }]); + + await server.answerCancelConnection(); + await server.cancelConnectionClosed; + expect(server.cancelPacketSeen).toBe(false); + }, +); + +// reserved.close() cancels its running queries and closes the connection in the +// same tick, so the session is gone when the cancel connection is ready to write. +// The backend still runs the query, and nothing else of this client can reach that +// backend, so the CancelRequest has to go out. +test("cancel() still reaches the server when the session closes during the dial", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const reserved = await sql.reserve(); + const query = reserved`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + + await reserved.close(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + expect((await settled).code).toBe("ERR_POSTGRES_CONNECTION_CLOSED"); +}); + +// The timeout of the cancel connection closes a dial that never completes, and +// the process has to exit then. +// Not on Windows and musl: the fixture loads glibc or libSystem for its raw listener. +test.skipIf(isWindows || isMusl)( + "the process exits when the dial of the cancel connection never completes", + async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "postgres-pending-dial-fixture.ts")], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("ERR_POSTGRES_CONNECTION_CLOSED\n"); + expect(exitCode).toBe(0); + }, +); + +// The first run of a statement sends its Parse together with the Bind and the +// Execute. A backend that waits for a lock waits inside that Parse, so the error +// of a cancel arrives with no ParseComplete before it. That error belongs to the +// cancelled query. A query with the same text that waits behind it shares the +// statement and has to parse it again. +test("cancel() during the Parse of a statement does not fail the queries that share it", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const cancelled = sql`select 'shared'`.execute(); + const cancelledSettled = cancelled.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + const waiting = sql`select 'shared'`.execute(); + const waitingSettled = waiting.then( + rows => rows, + err => err, + ); + + cancelled.cancel(); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + server.autoReply = true; + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + + expect((await cancelledSettled).errno).toBe("57014"); + expect(await waitingSettled).toEqual([{ v: "ok" }]); + // The second unit is the Parse, Bind and Execute of the waiting query. + expect(server.queryUnits).toBe(2); +}); + +// The first run of a statement with parameters sends Parse, Describe and Sync and +// waits for the parameter types. Its Bind is not written, so cancel() rejects the +// query at once and opens no connection. The backend still answers the Parse, and +// the statement is prepared for the next query with that text. +test("cancel() while only the Parse of a query is on the wire rejects it and keeps the statement", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const statement = (value: string) => sql`select ${value}::text as v`; + + const cancelled = statement("x").execute(); + const cancelledSettled = cancelled.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + cancelled.cancel(); + const err = await cancelledSettled; + expect({ code: err.code, hint: err.hint }).toEqual({ code: "ERR_POSTGRES_QUERY_CANCELLED", hint: undefined }); + + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgReadyForQuery(), + ); + + // The next run needs no Parse: its unit is a Bind and an Execute. + const next = statement("z").execute(); + await server.untilQueryUnits(2); + server.answerPrepared("z"); + expect(await next).toEqual([{ v: "z" }]); + expect({ + parses: server.frontendMessages.match(/P/g)?.length, + binds: server.frontendMessages.match(/B/g)?.length, + connections: server.connections, + }).toEqual({ parses: 1, binds: 1, connections: 1 }); +}); + +test("cancel() on a queued query does not cancel the one the backend is running", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const running = sql`select 'kept'`.simple().execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + + // Dispatched onto the same connection, but behind the running query: none of + // its bytes are on the wire, so a CancelRequest would stop the wrong query. + const queued = sql`select 'cancelled'`.simple().execute(); + const queuedSettled = queued.then( + rows => rows, + err => err, + ); + queued.cancel(); + + // No hint: this query never reaches the server. + const err = await queuedSettled; + expect({ name: err.name, code: err.code, message: err.message, hint: err.hint }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_QUERY_CANCELLED", + message: "Query cancelled", + hint: undefined, + }); + + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("kept")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + + expect(await runningSettled).toEqual([{ v: "kept" }]); + // A cancel connection would have arrived by the end of one more round trip. + server.autoReply = true; + expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); + expect(server.connections).toBe(1); +}); + +// The connection counts queued requests whose bytes are not written yet, and only +// pipelines a prepared query at enqueue time while that count is zero. A queued +// query that is cancelled leaves the queue without ever being written, so it has +// to leave that count too, or the connection stops pipelining for good. +test("a connection still pipelines after a queued query on it was cancelled", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + // Warm the statement so each later run of it is a bare Bind/Execute. + expect(await sql`select 'p'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'kept'`.simple().execute(); + await server.untilQueryUnits(2); + const queued = sql`select 'cancelled'`.simple().execute(); + const queuedSettled = queued.then( + rows => rows, + err => err, + ); + queued.cancel(); + expect((await queuedSettled).code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("kept")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await running).toEqual([{ v: "kept" }]); + + // Both Bind/Execute units must reach the backend before it answers either: + // the second one rides the wire behind the first instead of waiting for it. + const first = sql`select 'p'`.execute(); + const second = sql`select 'p'`.execute(); + await server.untilQueryUnits(4); + server.answerPrepared("first"); + server.answerPrepared("second"); + expect(await Promise.all([first, second])).toEqual([[{ v: "first" }], [{ v: "second" }]]); +}); + +// A CancelRequest names the backend process, not a statement. Once a statement is +// prepared, Bun pipelines the next query's Bind/Execute straight onto the wire +// behind the running one (do_run's Prepared arm writes when `can_pipeline()`), so +// the pipelined query's bytes are on the socket while the backend is still busy +// with the query ahead of it. Cancelling it on the server would kill that other +// query instead. +test("cancel() on a pipelined query does not cancel the one the backend is running", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + // Warm both statements so each reaches the Prepared state. + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + // `running` is the head of the connection's FIFO and the query the backend is + // executing; `pipelined` goes onto the wire right behind it. + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'b'`.execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + const pipelinedSettled = pipelined.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + pipelined.cancel(); + + // The hint tells this case apart from a query that was never sent: the backend + // still runs this one, so a retry of a write would apply it twice. + const err = await pipelinedSettled; + expect({ name: err.name, code: err.code, message: err.message, hint: err.hint }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_QUERY_CANCELLED", + message: "Query cancelled", + hint: "The server already received this query and still runs it. Bun discards the result.", + }); + server.answerPrepared("kept"); + expect(await runningSettled).toEqual([{ v: "kept" }]); + + // The pipelined query's Bind/Execute were already on the wire, so the backend + // answers it too. Those replies have to be consumed in order or the connection + // desyncs, which the next query proves it did not. + server.answerPrepared("drained"); + server.autoReply = true; + expect(await sql`select 'c'`).toEqual([{ v: "ok" }]); + // Two round trips after the cancel, a cancel connection would have arrived. + expect(server.connections).toBe(1); +}); + +// Under load the query that the backend runs has other queries written behind it. +// The CancelRequest stops the first one, and the server answers the others as usual. +test("cancel() on the running query leaves the queries that are pipelined behind it", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'a'`.execute(); + const behind = sql`select 'b'`.execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + running.cancel(); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await runningSettled).errno).toBe("57014"); + + server.answerPrepared("kept"); + expect(await behind).toEqual([{ v: "kept" }]); + + // The statement of the cancelled query is still prepared: its next run is a bare Bind and Execute. + const again = sql`select 'a'`.execute(); + await server.untilQueryUnits(5); + server.answerPrepared("again"); + expect(await again).toEqual([{ v: "again" }]); +}); + +// The server still answers a pipelined query that cancel() rejected, and the +// answer can be an error. The connection takes it like the rows of such a query. +test("a cancelled pipelined query that the server answers with an error leaves the connection in sync", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'b'`.execute(); + const pipelinedSettled = pipelined.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + pipelined.cancel(); + expect((await pipelinedSettled).code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + server.answerPrepared("kept"); + expect(await running).toEqual([{ v: "kept" }]); + server.reply(pgErrorResponse({ S: "ERROR", C: "22012", M: "division by zero" }), pgReadyForQuery()); + + // The error was for the cancelled query alone: its statement is still prepared. + const again = sql`select 'b'`.execute(); + await server.untilQueryUnits(5); + server.answerPrepared("again"); + expect(await again).toEqual([{ v: "again" }]); + expect(server.connections).toBe(1); +}); + +// The connection turns a parameter into its wire form when it encodes the Bind, +// and an object does that with its own code. That code can call cancel() on the +// query that it belongs to. Nothing of the query is on the wire then, and nothing +// of it may get there. +const cancelling = (query: () => { cancel(): unknown }) => ({ + toString() { + query().cancel(); + return "x"; + }, +}); +const settledCode = (query: Promise) => + query.then( + () => "resolved", + (err: any) => err.code, + ); + +test("cancel() from the code of a parameter rejects the query and sends no Bind for it", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const statement = (parameter: object) => sql`select ${parameter}::text as v`; + + // First run: Parse, Describe and Sync go out, and the Bind waits for the + // parameter types. The connection encodes it when they arrive. + const first: any = statement(cancelling(() => first)); + const firstSettled = settledCode(first.execute()); + await server.untilQueryUnits(1); + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgReadyForQuery(), + ); + expect(await firstSettled).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + // Second run: the statement is prepared, so the Bind is encoded at dispatch. + const second: any = statement(cancelling(() => second)); + expect(await settledCode(second.execute())).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + // Third run, with a parameter that cancels nothing. Its Bind is the only one + // that the server has seen. + const third = statement({ toString: () => "z" }).execute(); + await server.untilQueryUnits(2); + server.answerPrepared("z"); + expect(await third).toEqual([{ v: "z" }]); + expect({ binds: server.frontendMessages.match(/B/g)?.length, connections: server.connections }).toEqual({ + binds: 1, + connections: 1, + }); +}); + +// Without prepared statements the Parse, the Bind and the Execute of a query are +// one batch, encoded at dispatch. +test("cancel() from the code of a parameter sends nothing when statements are not prepared", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5, prepare: false }); + + const cancelled: any = sql`select ${cancelling(() => cancelled)}::text as v`; + expect(await settledCode(cancelled.execute())).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + const next = sql`select ${{ toString: () => "z" }}::text as v`.execute(); + await server.untilQueryUnits(1); + expect(server.frontendMessages.match(/[PB]/g)).toEqual(["P", "B"]); + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("z")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await next).toEqual([{ v: "z" }]); +}); + +// A query caches the connection that it was dispatched to, because cancel() +// needs it. A query that has settled, by any of the ways above, must let go of +// it, or a Query that user code keeps also keeps the connection. +test("a settled query does not keep its connection alive", async () => { + const connections = () => heapStats().objectTypeCounts["PostgresSQLConnection"] || 0; + Bun.gc(true); + const before = connections(); + const kept: unknown[] = []; + const rounds = 10; + + for (let round = 0; round < rounds; round++) { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const resolved = sql`select 'a'`.execute(); + await resolved; + server.autoReply = false; + + // The running query, one that is written behind it, and one that is not written. + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'a'`.execute(); + const queued = sql`select 'q'`.simple().execute(); + const cancelled = [running, pipelined, queued]; + const settled = Promise.all(cancelled.map(settledCode)); + await server.untilQueryUnits(3); + for (const query of cancelled) query.cancel(); + await server.cancelPacket; + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + server.answerPrepared("discarded"); + expect(await settled).toEqual([ + "ERR_POSTGRES_SERVER_ERROR", + "ERR_POSTGRES_QUERY_CANCELLED", + "ERR_POSTGRES_QUERY_CANCELLED", + ]); + kept.push(resolved, ...cancelled); + } + + // Each round made a session and a cancel connection. GC finalizes them over a few cycles. + const deadline = performance.now() + 5_000; + Bun.gc(true); + while (connections() > before + 2 && performance.now() < deadline) { + await Bun.sleep(20); + Bun.gc(true); + } + expect(connections()).toBeLessThanOrEqual(before + 2); + expect(kept).toHaveLength(rounds * 4); +}); + +// The scripted backend compares the packet with `pgCancelRequest`, which this +// change also wrote. Here a real server is the judge of the bytes. +describeWithContainer("postgres", { image: "postgres_plain" }, container => { + test("cancel() stops a query that a real server is running", async () => { + await container.ready; + const url = `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`; + await using sql = new SQL({ url, max: 1, connectionTimeout: 5 }); + await using observer = new SQL({ url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(30) as cancel_running_query`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + // The backend is inside pg_sleep, so the server runs the query and does not only hold its bytes. + const deadline = performance.now() + 4_000; + while (true) { + const seen = await observer` + select state, wait_event from pg_stat_activity + where query like '%cancel_running_query%' and pid <> pg_backend_pid()`; + if (seen.some((row: any) => row.wait_event === "PgSleep")) break; + if (performance.now() > deadline) throw new Error(`the query did not reach pg_sleep: ${JSON.stringify(seen)}`); + } + query.cancel(); + + const err = await settled; + expect({ code: err.code, errno: err.errno }).toEqual({ code: "ERR_POSTGRES_SERVER_ERROR", errno: "57014" }); + // The connection is in sync: the next query runs on it. + expect(await sql`select 1 as x`).toEqual([{ x: 1 }]); + }); +}); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index af2030885250..f2390fb3e738 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -71,6 +71,23 @@ export function pgSSLResponse(answer: "S" | "N"): Buffer { return Buffer.from(answer, "latin1"); } +// PostgreSQL FE/BE protocol §55.2.3 CancelRequest: Int32(16) Int32(80877102) Int32(pid) Int32(secret) +// Sent by the client as the first (and only) message of a second connection; it +// has no message-type byte, same as the startup packet. +export function pgCancelRequest(processId: number, secretKey: number): Buffer { + const buf = Buffer.alloc(16); + buf.writeInt32BE(16, 0); + buf.writeInt32BE(80877102, 4); // 0x04d2162e + buf.writeInt32BE(processId, 8); + buf.writeInt32BE(secretKey, 12); + return buf; +} + +// PostgreSQL FE/BE protocol §55.7 BackendKeyData: Byte1('K') Int32(12) Int32(pid) Int32(secret) +export function pgBackendKeyData(processId: number, secretKey: number): Buffer { + return pgRaw("K", Buffer.concat([pgInt32(processId), pgInt32(secretKey)])); +} + // PostgreSQL FE/BE protocol §55.7 AuthenticationOk: Byte1('R') Int32(8) Int32(0) export function pgAuthenticationOk(): Buffer { const buf = Buffer.alloc(9);