Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/sql/postgres/protocol/NewWriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ pub trait WriterContext: Copy {
fn offset(self) -> usize;
fn write(self, bytes: &[u8]) -> Result<(), AnyPostgresError>;
fn pwrite(self, bytes: &[u8], offset: usize) -> Result<(), AnyPostgresError>;
/// Discard every byte written at or after `offset`.
fn truncate(self, offset: usize);
/// Changes when another writer is handed out or the buffer is drained.
fn epoch(self) -> u32;
}

#[derive(Copy, Clone)]
Expand Down Expand Up @@ -60,6 +64,20 @@ impl<C: WriterContext> NewWriter<C> {
C::pwrite(self.wrapped, data, i)
}

/// Run `f`. If it fails and nothing else touched the buffer, discard what it wrote.
pub fn atomically(
self,
f: impl FnOnce(Self) -> Result<(), AnyPostgresError>,
) -> Result<(), AnyPostgresError> {
let start = self.offset();
let epoch = C::epoch(self.wrapped);
let result = f(self);
if result.is_err() && C::epoch(self.wrapped) == epoch {
C::truncate(self.wrapped, start);
}
result
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
pub fn int4(self, value: PostgresInt32) -> Result<(), AnyPostgresError> {
self.write(&value.to_be_bytes())
}
Expand Down
192 changes: 99 additions & 93 deletions src/sql_jsc/postgres/PostgresRequest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,66 +292,70 @@ pub(crate) fn prepare_and_query_with_signature<Context: WriterContext>(
global: &JSGlobalObject,
query: &[u8],
array_value: JSValue,
mut writer: protocol::NewWriter<Context>,
writer: protocol::NewWriter<Context>,
signature: &mut Signature,
) -> Result<(), AnyPostgresError> {
write_query(
query,
&signature.prepared_statement_name,
&signature.fields,
writer,
)?;
write_bind(
&signature.prepared_statement_name,
&BunString::EMPTY,
global,
array_value,
JSValue::ZERO,
&[],
&[],
writer,
)?;
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(
writer.atomically(|mut writer| {
write_query(
query,
&signature.prepared_statement_name,
),
..Default::default()
};
exec.write_internal(&mut writer)?;
&signature.fields,
writer,
)?;
write_bind(
&signature.prepared_statement_name,
&BunString::EMPTY,
global,
array_value,
JSValue::ZERO,
&[],
&[],
writer,
)?;
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(
&signature.prepared_statement_name,
),
..Default::default()
};
exec.write_internal(&mut writer)?;

writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
})
}

pub(crate) fn bind_and_execute<Context: WriterContext>(
global: &JSGlobalObject,
statement: &PostgresSQLStatement,
array_value: JSValue,
columns_value: JSValue,
mut writer: protocol::NewWriter<Context>,
writer: protocol::NewWriter<Context>,
) -> Result<(), AnyPostgresError> {
write_bind(
&statement.signature.prepared_statement_name,
&BunString::EMPTY,
global,
array_value,
columns_value,
&statement.parameters,
&statement.fields,
writer,
)?;
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(
writer.atomically(|mut writer| {
write_bind(
&statement.signature.prepared_statement_name,
),
..Default::default()
};
exec.write_internal(&mut writer)?;
&BunString::EMPTY,
global,
array_value,
columns_value,
&statement.parameters,
&statement.fields,
writer,
)?;
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(
&statement.signature.prepared_statement_name,
),
..Default::default()
};
exec.write_internal(&mut writer)?;

writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
})
}

/// Atomically sends Parse + [Describe] + Bind + Execute + Flush + Sync as a single message batch.
Expand All @@ -366,61 +370,63 @@ pub(crate) fn parse_and_bind_and_execute<Context: WriterContext>(
array_value: JSValue,
columns_value: JSValue,
include_describe: bool,
mut writer: protocol::NewWriter<Context>,
writer: protocol::NewWriter<Context>,
) -> Result<(), AnyPostgresError> {
let name = &statement.signature.prepared_statement_name;

// Parse
{
let q = protocol::Parse {
name,
params: &statement.signature.fields,
query,
writer.atomically(|mut writer| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 With prepare: false, a script whose last query rejects while a parameter is encoded no longer exits on its own. do_run takes the connection's KeepAlive ref (PostgresSQLQuery.rs:817) and then runs advance_and_flush(); when parse_and_bind_and_execute fails, the rollback at PostgresRequest.rs:377 leaves nothing to send, so no reply ever reaches the idle check in on_data that releases the ref. Fix: when a rolled-back batch leaves the queue and write buffer empty, release the ref as on_data's idle block does (or take it only if the request is still queued after advance_and_flush). On the base the partial Bind went out and the server's close released it.

Why this was flagged

A connection created with prepare: false (ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS) runs one query with a parameter whose encoding fails (throwing toString, number[] to bytea) while no other query is in flight, e.g. the last statement of a CLI script that does not call sql.close(). PostgresSQLQuery.rs:693-769 skips writing for unnamed statements with params, pushes the request at :810, refs poll_ref at :817, then calls connection.advance_and_flush() at :832. advance() at PostgresSQLConnection.rs:2183 calls parse_and_bind_and_execute; the closure at PostgresRequest.rs:377 fails, NewWriter.rs:75-76 truncates the buffer to its start, the request is rejected via req.on_js_error at :2194 and popped by discard_request at :2207; flush_data at :1837 finds an empty buffer. poll_ref is only unref'd in on_data's idle block (PostgresSQLConnection.rs:1053-1062), on close/failure (:814, :1413, :1509) or by an explicit unref(); none of those runs because no bytes were sent and no reply arrives, and idleTimeout defaults to 0 (shared.ts:878) so no timer closes the connection. The process therefore…

Verification: normal — when a prepare: false connection is idle and the next query's parameter encoding fails with nothing else in flight (e.g. last statement of a script that never calls sql.close(), default idleTimeout 0), the process no longer exits. Mechanism traced in code: do_run (src/sql_jsc/postgres/PostgresSQLQuery.rs:766-768) skips writing for unnamed statements with params, pushes the…

// Parse
{
let q = protocol::Parse {
name,
params: &statement.signature.fields,
query,
};
q.write_internal(&mut writer)?;
bun_core::scoped_log!(Postgres, "Parse: {}", bun_fmt::quote(query));
}

// Describe (needed on first execution to learn parameter/result types for caching)
if include_describe {
let d = protocol::Describe {
p: protocol::PortalOrPreparedStatement::PreparedStatement(name),
};
d.write_internal(writer)?;
bun_core::scoped_log!(Postgres, "Describe: {}", bun_fmt::quote(name));
}

// Bind — use server-provided types if available (binary format), otherwise
// fall back to signature types (text format for unknowns). The server will
// handle text-to-type conversion based on the parameter types from Parse.
Comment thread
robobun marked this conversation as resolved.
Resolved
let param_fields = if !statement.parameters.is_empty() {
&statement.parameters[..]
} else {
&statement.signature.fields[..]
};
q.write_internal(&mut writer)?;
bun_core::scoped_log!(Postgres, "Parse: {}", bun_fmt::quote(query));
}
let result_fields = &statement.fields;

// Describe (needed on first execution to learn parameter/result types for caching)
if include_describe {
let d = protocol::Describe {
write_bind(
name,
&BunString::EMPTY,
global,
array_value,
columns_value,
param_fields,
result_fields,
writer,
)?;

// Execute
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(name),
..Default::default()
};
d.write_internal(writer)?;
bun_core::scoped_log!(Postgres, "Describe: {}", bun_fmt::quote(name));
}
exec.write_internal(&mut writer)?;

// Bind — use server-provided types if available (binary format), otherwise
// fall back to signature types (text format for unknowns). The server will
// handle text-to-type conversion based on the parameter types from Parse.
let param_fields = if !statement.parameters.is_empty() {
&statement.parameters[..]
} else {
&statement.signature.fields[..]
};
let result_fields = &statement.fields;

write_bind(
name,
&BunString::EMPTY,
global,
array_value,
columns_value,
param_fields,
result_fields,
writer,
)?;

// Execute
let exec = protocol::Execute {
p: protocol::PortalOrPreparedStatement::PreparedStatement(name),
..Default::default()
};
exec.write_internal(&mut writer)?;

writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
writer.write(&protocol::FLUSH)?;
writer.write(&protocol::SYNC)?;
Ok(())
})
}

pub(crate) fn execute_query<Context: WriterContext>(
Expand Down
26 changes: 26 additions & 0 deletions src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ pub struct PostgresSQLConnection {
ref_count: Cell<u32>,

pub(crate) write_buffer: JsCell<OffsetByteList>,
/// Bumped when a `Writer` is handed out and when `write_buffer` is drained or freed.
write_epoch: Cell<u32>,
// Private — `JsCell` aliasing invariant; only `Reader` and `on_data`
// touch these (both in this module).
read_buffer: JsCell<OffsetByteList>,
Expand Down Expand Up @@ -708,6 +710,7 @@ impl PostgresSQLConnection {
SocketMonitor::write(&chunk[..usize::try_from(wrote).expect("int cast")]);
self.write_buffer
.with_mut(|b| b.consume(u32::try_from(wrote).expect("int cast")));
self.bump_write_epoch();
}
}

Expand Down Expand Up @@ -1181,6 +1184,7 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR
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()),
Expand Down Expand Up @@ -1412,6 +1416,7 @@ impl PostgresSQLConnection {
}
self.unregister_auto_flusher();
self.write_buffer.with_mut(|b| b.clear_and_free());
self.bump_write_epoch();
}

pub fn do_close(
Expand Down Expand Up @@ -1610,6 +1615,7 @@ impl Writer {

pub(crate) fn pwrite(&mut self, data: &[u8], index: usize) -> Result<(), AnyPostgresError> {
self.connection.write_buffer.with_mut(|b| {
let index = b.head as usize + index;
b.byte_list.slice_mut()[index..][..data.len()].copy_from_slice(data);
});
Ok(())
Expand All @@ -1618,6 +1624,13 @@ impl Writer {
pub(crate) fn offset(self) -> usize {
self.connection.write_buffer.get().len() as usize
}

pub(crate) fn truncate(&mut self, offset: usize) {
self.connection.write_buffer.with_mut(|b| {
let len = b.head as usize + offset;
b.byte_list.truncate(len);
Comment thread
robobun marked this conversation as resolved.
Resolved
});
}
}

impl protocol::WriterContext for Writer {
Expand All @@ -1633,10 +1646,23 @@ impl protocol::WriterContext for Writer {
fn pwrite(mut self, bytes: &[u8], i: usize) -> Result<(), AnyPostgresError> {
Writer::pwrite(&mut self, bytes, i)
}
#[inline]
fn truncate(mut self, offset: usize) {
Writer::truncate(&mut self, offset)
}
#[inline]
fn epoch(self) -> u32 {
self.connection.write_epoch.get()
}
}

impl PostgresSQLConnection {
fn bump_write_epoch(&self) {
self.write_epoch.set(self.write_epoch.get().wrapping_add(1));
}

pub(crate) fn writer(&self) -> protocol::NewWriter<Writer> {
self.bump_write_epoch();
protocol::NewWriter {
wrapped: Writer {
connection: BackRef::new(self),
Expand Down
Loading
Loading