Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
43 changes: 29 additions & 14 deletions src/client/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,32 +53,47 @@ fn http_error(status: u16, body: &str, context: impl std::fmt::Display) -> Error
struct ErrorWrapper {
error: ServiceError,
}
// Try the bare envelope first, then the `{"error": ...}` wrapper.
let svc: Option<ServiceError> = serde_json::from_str::<ServiceError>(body)
// Parse the body once into a `Value`, then try both envelope shapes
// off it (bare `ServiceError`, then the `{"error": ...}` wrapper) —
// avoids re-walking the raw string twice.
let svc: Option<ServiceError> = serde_json::from_str::<serde_json::Value>(body)
.ok()
.filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some())
.or_else(|| {
serde_json::from_str::<ErrorWrapper>(body)
.and_then(|v| {
serde_json::from_value::<ServiceError>(v.clone())
.ok()
.map(|w| w.error)
.filter(|e| e.error_code.is_some() || e.message.is_some() || e.sql_state.is_some())
.or_else(|| {
serde_json::from_value::<ErrorWrapper>(v)
.ok()
.map(|w| w.error)
})
});

let mut err = Error::from_http_status(status);
match svc {
Some(svc) => {
// Prefer the server's structured message; keep the caller
// context as a prefix for continuity with existing logs.
let msg = svc.message.as_deref().unwrap_or(body);
let error_code = svc.error_code.as_deref().filter(|s| !s.is_empty());
// Prefer the server's structured message. If it's absent but
// an error_code is present, synthesize a readable message
// rather than folding the raw JSON body in. Only fall back to
// the raw body when neither is available.
let msg = match (svc.message.as_deref(), error_code) {
(Some(m), _) => m.to_string(),
(None, Some(ec)) => format!("server returned error_code {ec}"),
(None, None) => body.to_string(),
};
err = err.message(format!("{context}: {msg}"));
if let Some(ec) = svc.error_code.as_deref().filter(|s| !s.is_empty()) {
if let Some(ec) = error_code {
err = err.with_error_code(ec);
}
// SQL state: explicit field, else the "SQLSTATE: XXXXX"
// pattern in the message — same precedence as terminal_outcome.
// SQL state: explicit field (must be the canonical 5-char
// shape — same predicate as terminal_outcome, so we don't
// surface junk like "X" or "garbage"), else the
// "SQLSTATE: XXXXX" pattern in the message.
let sql_state = svc
.sql_state
.filter(|s| !s.is_empty())
.or_else(|| crate::kernel_error::extract_sqlstate_from_message(msg));
.filter(|s| s.len() == 5)
.or_else(|| crate::kernel_error::extract_sqlstate_from_message(&msg));
if let Some(s) = sql_state {
err = err.with_sql_state(s);
}
Expand Down
48 changes: 22 additions & 26 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ use crate::metadata_v0::Metadata;
use crate::reader::ResultReaderFactory;
use crate::statement::executed_async::ExecutedAsyncStatement;
use crate::statement::mutable::Statement;
use crate::statement::validity::ValidityFlag;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use tracing::{info_span, Instrument, Span};
Expand Down Expand Up @@ -373,17 +371,20 @@ impl Session {
/// [`status`] surfaces the real server state.
///
/// The returned handle is standalone and **non-owning**: its
/// [`ValidityFlag`] is fresh (not shared with any parent
/// `Statement`, since there is none), and it does **not** close the
/// server statement on `Drop` or via [`close`] — attach is a
/// read-only adopt. The statement's lifecycle stays with whatever
/// validity flag is fresh (not shared with any parent `Statement`,
/// since there is none), and it does **not** close the server
/// statement on `Drop` or via [`close`], does **not** cancel it on a
/// dropped `await_result()` poll, and its [`cancel`] errors — attach
/// is a read-only adopt. The statement's lifecycle stays with
/// whatever
/// submitted it (or an explicit `close_statement`); a transient
/// handle a poller creates and drops must not tear it down. (This is
/// what lets `get_query_state` re-attach on every poll without the
/// poll loop closing the statement it's watching.)
///
/// [`status`]: ExecutedAsyncStatement::status
/// [`close`]: ExecutedAsyncStatement::close
/// [`cancel`]: ExecutedAsyncStatement::cancel
/// [`ErrorCode::NotFound`]: crate::kernel_error::ErrorCode::NotFound
pub async fn attach_async_statement(
&self,
Expand All @@ -395,32 +396,27 @@ impl Session {
// Seed initial_status from the wire — the same RPC
// `ExecutedAsyncStatement::status` makes. Surfaces NotFound
// here (rather than on the caller's first poll) for an
// unknown/expired id.
// unknown/expired id. Stamp the statement id onto the error
// (mirrors `terminal_outcome`, which sets query_id on every
// error it builds) so callers can correlate which id was not
// found.
let response = self
.inner
.transport()
.statement_status(&statement_id)
.await?;
Ok(ExecutedAsyncStatement::new(
.await
.map_err(|e| e.with_query_id(&statement_id))?;
// NON-OWNING read-only adopt: `new_attached` gives the handle
// a fresh standalone `ValidityFlag`, `closed=true` (so `Drop`
// / `close()` never fire `close_statement`), and
// `owning=false` (so `await_result` doesn't arm the
// drop-cancel guard and `cancel()` errors). The statement's
// lifecycle stays with whoever submitted it; a poller that
// re-attaches each tick can't tear down the statement it's
// watching.
Ok(ExecutedAsyncStatement::new_attached(
Arc::clone(&self.inner),
statement_id,
// Standalone handle: no parent Statement to share the
// flag with, so a re-execute elsewhere can't invalidate
// it. Starts valid.
ValidityFlag::new(),
// NON-OWNING: start `closed=true` so this handle never
// closes the server statement — neither on `Drop` (its
// `swap(true)` sees already-closed and skips the
// fire-and-forget `close_statement`) nor via an explicit
// `close()` (which short-circuits on the flag). Attach is
// a *read-only adopt*: the statement's lifecycle is owned
// by whatever submitted it (or by an explicit
// `close_statement`), NOT by a transient handle a poller
// creates and drops. Without this, every `status()` poll
// through a fresh attached handle would close the very
// statement it's polling on Drop — turning a poll loop
// into a self-close.
Arc::new(AtomicBool::new(true)),
response.status,
))
}
Expand Down
108 changes: 103 additions & 5 deletions src/statement/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,23 @@ pub struct ExecutedAsyncStatement {
/// short-circuited) `close()`. Tells `Drop` to skip its
/// fire-and-forget cleanup.
closed: Arc<AtomicBool>,
/// Whether this handle *owns* the server statement's lifecycle.
///
/// `true` for handles produced by [`Statement::submit`] (the
/// submitting handle): they may close the statement on `Drop` /
/// `close()`, cancel it on a dropped `await_result()` poll (the
/// drop-cancel DBU-safety guard), and `cancel()` actively
/// terminates it.
///
/// `false` for handles produced by
/// [`Session::attach_async_statement`](crate::Session::attach_async_statement)
/// — a *read-only adopt* of a statement someone else owns. A
/// non-owning handle must never tear the statement down out from
/// under its owner: it does not arm the `await_result` drop-cancel
/// guard, and `cancel()` returns an error instead of firing a
/// server-side cancel. (`Drop` / `close()` are already inert on
/// attached handles via `closed=true`.)
owning: bool,
/// Last SEA `StatementStatus` observed by this handle (initial
/// `submit_statement` response or any subsequent `status()` /
/// `await_result` poll). Read by the `num_modified_rows()` /
Expand Down Expand Up @@ -236,6 +253,40 @@ impl ExecutedAsyncStatement {
statement_id,
valid,
closed,
// The submitting handle owns the statement lifecycle.
owning: true,
latest_status: Arc::new(std::sync::Mutex::new(initial_status)),
}
}

/// Crate-internal constructor for a **non-owning** (read-only
/// adopt) handle, built by
/// [`Session::attach_async_statement`](crate::Session::attach_async_statement).
///
/// The handle observes a statement someone else owns, so it must
/// never tear it down:
/// - `valid` is a fresh standalone [`ValidityFlag`] — no parent
/// `Statement` to share with, so a re-execute elsewhere can't
/// invalidate it.
/// - `closed` starts `true` so `Drop` and `close()` are inert (they
/// never fire `close_statement`).
/// - `owning` is `false` so `await_result()` does not arm the
/// drop-cancel guard and `cancel()` errors instead of firing a
/// server-side cancel.
///
/// `initial_status` is seeded from the `GetStatementStatus` the
/// attach path already issued.
pub(crate) fn new_attached(
session: Arc<SessionInner>,
statement_id: String,
initial_status: crate::types::sea::StatementStatus,
) -> Self {
Self {
session,
statement_id,
valid: ValidityFlag::new(),
closed: Arc::new(AtomicBool::new(true)),
owning: false,
latest_status: Arc::new(std::sync::Mutex::new(initial_status)),
}
}
Expand Down Expand Up @@ -379,8 +430,21 @@ impl ExecutedAsyncStatement {
// best-effort `cancel_statement` so the server stops
// charging DBUs on a now-orphaned query. Defused once we
// reach a terminal state on the success or error path.
let cancel_guard =
AwaitResultCancelGuard::new(Arc::clone(&self.session), self.statement_id.clone());
//
// ONLY for owning handles. A non-owning (attached) handle is
// a read-only adopt of a statement someone else owns —
// dropping its `await_result()` mid-poll (e.g. a passive
// observer wrapping it in a `tokio::time::timeout`) must NOT
// cancel the owner's statement. Leaving the guard `None`
// makes the drop a true no-op.
let mut cancel_guard = if self.owning {
Some(AwaitResultCancelGuard::new(
Arc::clone(&self.session),
self.statement_id.clone(),
))
} else {
None
};

loop {
self.valid.check()?;
Expand All @@ -395,17 +459,23 @@ impl ExecutedAsyncStatement {
self.record_latest_status(response.status.clone());
match StatementStatus::from_sea_response(&response) {
StatementStatus::Succeeded | StatementStatus::Closed => {
cancel_guard.defuse();
if let Some(g) = cancel_guard.take() {
g.defuse();
}
return self.materialise_result().await;
}
StatementStatus::Failed(e) => {
// Server already decided this is terminal — no
// need to fire a redundant cancel.
cancel_guard.defuse();
if let Some(g) = cancel_guard.take() {
g.defuse();
}
return Err(e);
}
StatementStatus::Cancelled => {
cancel_guard.defuse();
if let Some(g) = cancel_guard.take() {
g.defuse();
}
// Carry the SEA extended status fields onto
// the returned Error — mirrors the sync
// `terminal_outcome::Canceled` arm so the
Expand Down Expand Up @@ -563,6 +633,17 @@ impl ExecutedStatementHandle for ExecutedAsyncStatement {
async fn cancel(&self) -> Result<()> {
async {
self.valid.check()?;
// A non-owning (attached) handle must not cancel a statement
// it merely adopted to observe — that would terminate the
// owner's query. Refuse rather than silently firing the
// server-side cancel.
if !self.owning {
return Err(Error::invalid_state().message(
"cancel() is not permitted on an attached (read-only) \
ExecutedAsyncStatement; the statement is owned by whoever \
submitted it",
));
}
self.session
.transport()
.cancel_statement(&self.statement_id)
Expand Down Expand Up @@ -628,6 +709,11 @@ impl ExecutedAsyncStatement {
session: Arc::clone(&self.session),
statement_id: self.statement_id.clone(),
valid: self.valid.clone(),
// Inherit ownership: a canceller derived from an attached
// (read-only) handle must not cancel the owner's statement
// either — otherwise the footgun just moves to the detached
// canceller.
owning: self.owning,
}
}
}
Expand All @@ -647,6 +733,11 @@ pub struct AsyncStatementCanceller {
session: Arc<SessionInner>,
statement_id: String,
valid: ValidityFlag,
/// Inherited from the producing handle — `false` for a canceller
/// derived from an attached (read-only) handle, which must not
/// cancel a statement it doesn't own. See
/// [`ExecutedAsyncStatement::owning`].
owning: bool,
}

impl AsyncStatementCanceller {
Expand All @@ -663,6 +754,13 @@ impl AsyncStatementCanceller {
pub async fn cancel(&self) -> Result<()> {
async {
self.valid.check()?;
if !self.owning {
return Err(Error::invalid_state().message(
"cancel() is not permitted on a canceller derived from an \
attached (read-only) ExecutedAsyncStatement; the statement \
is owned by whoever submitted it",
));
}
self.session
.transport()
.cancel_statement(&self.statement_id)
Expand Down
Loading
Loading