LCOV - code coverage report
Current view: top level - proxy/src/serverless - sql_over_http.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 5.3 % 870 46
Test Date: 2025-05-26 10:37:33 Functions: 4.3 % 93 4

            Line data    Source code
       1              : use std::pin::pin;
       2              : use std::sync::Arc;
       3              : 
       4              : use bytes::Bytes;
       5              : use futures::future::{Either, select, try_join};
       6              : use futures::{StreamExt, TryFutureExt};
       7              : use http::Method;
       8              : use http::header::AUTHORIZATION;
       9              : use http_body_util::combinators::BoxBody;
      10              : use http_body_util::{BodyExt, Full};
      11              : use http_utils::error::ApiError;
      12              : use hyper::body::Incoming;
      13              : use hyper::http::{HeaderName, HeaderValue};
      14              : use hyper::{HeaderMap, Request, Response, StatusCode, header};
      15              : use indexmap::IndexMap;
      16              : use postgres_client::error::{DbError, ErrorPosition, SqlState};
      17              : use postgres_client::{
      18              :     GenericClient, IsolationLevel, NoTls, ReadyForQueryStatus, RowStream, Transaction,
      19              : };
      20              : use pq_proto::StartupMessageParamsBuilder;
      21              : use serde::Serialize;
      22              : use serde_json::Value;
      23              : use serde_json::value::RawValue;
      24              : use tokio::time::{self, Instant};
      25              : use tokio_util::sync::CancellationToken;
      26              : use tracing::{debug, error, info};
      27              : use typed_json::json;
      28              : use url::Url;
      29              : use uuid::Uuid;
      30              : 
      31              : use super::backend::{LocalProxyConnError, PoolingBackend};
      32              : use super::conn_pool::{AuthData, ConnInfoWithAuth};
      33              : use super::conn_pool_lib::{self, ConnInfo};
      34              : use super::error::HttpCodeError;
      35              : use super::http_util::json_response;
      36              : use super::json::{JsonConversionError, json_to_pg_text, pg_text_row_to_json};
      37              : use crate::auth::backend::{ComputeCredentialKeys, ComputeUserInfo};
      38              : use crate::auth::{ComputeUserInfoParseError, endpoint_sni};
      39              : use crate::config::{AuthenticationConfig, HttpConfig, ProxyConfig, TlsConfig};
      40              : use crate::context::RequestContext;
      41              : use crate::error::{ErrorKind, ReportableError, UserFacingError};
      42              : use crate::http::{ReadBodyError, read_body_with_limit};
      43              : use crate::metrics::{HttpDirection, Metrics, SniGroup, SniKind};
      44              : use crate::proxy::{NeonOptions, run_until_cancelled};
      45              : use crate::serverless::backend::HttpConnError;
      46              : use crate::types::{DbName, RoleName};
      47              : use crate::usage_metrics::{MetricCounter, MetricCounterRecorder};
      48              : 
      49           11 : #[derive(serde::Deserialize)]
      50              : #[serde(rename_all = "camelCase")]
      51              : struct QueryData {
      52              :     query: String,
      53              :     #[serde(deserialize_with = "bytes_to_pg_text")]
      54              :     #[serde(default)]
      55              :     params: Vec<Option<String>>,
      56              :     #[serde(default)]
      57              :     array_mode: Option<bool>,
      58              : }
      59              : 
      60            1 : #[derive(serde::Deserialize)]
      61              : struct BatchQueryData {
      62              :     queries: Vec<QueryData>,
      63              : }
      64              : 
      65              : #[derive(serde::Deserialize)]
      66              : #[serde(untagged)]
      67              : enum Payload {
      68              :     Single(QueryData),
      69              :     Batch(BatchQueryData),
      70              : }
      71              : 
      72              : pub(super) static NEON_REQUEST_ID: HeaderName = HeaderName::from_static("neon-request-id");
      73              : 
      74              : static CONN_STRING: HeaderName = HeaderName::from_static("neon-connection-string");
      75              : static RAW_TEXT_OUTPUT: HeaderName = HeaderName::from_static("neon-raw-text-output");
      76              : static ARRAY_MODE: HeaderName = HeaderName::from_static("neon-array-mode");
      77              : static ALLOW_POOL: HeaderName = HeaderName::from_static("neon-pool-opt-in");
      78              : static TXN_ISOLATION_LEVEL: HeaderName = HeaderName::from_static("neon-batch-isolation-level");
      79              : static TXN_READ_ONLY: HeaderName = HeaderName::from_static("neon-batch-read-only");
      80              : static TXN_DEFERRABLE: HeaderName = HeaderName::from_static("neon-batch-deferrable");
      81              : 
      82              : static HEADER_VALUE_TRUE: HeaderValue = HeaderValue::from_static("true");
      83              : 
      84            3 : fn bytes_to_pg_text<'de, D>(deserializer: D) -> Result<Vec<Option<String>>, D::Error>
      85            3 : where
      86            3 :     D: serde::de::Deserializer<'de>,
      87            3 : {
      88              :     // TODO: consider avoiding the allocation here.
      89            3 :     let json: Vec<Value> = serde::de::Deserialize::deserialize(deserializer)?;
      90            3 :     Ok(json_to_pg_text(json))
      91            3 : }
      92              : 
      93              : #[derive(Debug, thiserror::Error)]
      94              : pub(crate) enum ConnInfoError {
      95              :     #[error("invalid header: {0}")]
      96              :     InvalidHeader(&'static HeaderName),
      97              :     #[error("invalid connection string: {0}")]
      98              :     UrlParseError(#[from] url::ParseError),
      99              :     #[error("incorrect scheme")]
     100              :     IncorrectScheme,
     101              :     #[error("missing database name")]
     102              :     MissingDbName,
     103              :     #[error("invalid database name")]
     104              :     InvalidDbName,
     105              :     #[error("missing username")]
     106              :     MissingUsername,
     107              :     #[error("invalid username: {0}")]
     108              :     InvalidUsername(#[from] std::string::FromUtf8Error),
     109              :     #[error("missing authentication credentials: {0}")]
     110              :     MissingCredentials(Credentials),
     111              :     #[error("missing hostname")]
     112              :     MissingHostname,
     113              :     #[error("invalid hostname: {0}")]
     114              :     InvalidEndpoint(#[from] ComputeUserInfoParseError),
     115              :     #[error("malformed endpoint")]
     116              :     MalformedEndpoint,
     117              : }
     118              : 
     119              : #[derive(Debug, thiserror::Error)]
     120              : pub(crate) enum Credentials {
     121              :     #[error("required password")]
     122              :     Password,
     123              :     #[error("required authorization bearer token in JWT format")]
     124              :     BearerJwt,
     125              : }
     126              : 
     127              : impl ReportableError for ConnInfoError {
     128            0 :     fn get_error_kind(&self) -> ErrorKind {
     129            0 :         ErrorKind::User
     130            0 :     }
     131              : }
     132              : 
     133              : impl UserFacingError for ConnInfoError {
     134            0 :     fn to_string_client(&self) -> String {
     135            0 :         self.to_string()
     136            0 :     }
     137              : }
     138              : 
     139            0 : fn get_conn_info(
     140            0 :     config: &'static AuthenticationConfig,
     141            0 :     ctx: &RequestContext,
     142            0 :     headers: &HeaderMap,
     143            0 :     tls: Option<&TlsConfig>,
     144            0 : ) -> Result<ConnInfoWithAuth, ConnInfoError> {
     145            0 :     let connection_string = headers
     146            0 :         .get(&CONN_STRING)
     147            0 :         .ok_or(ConnInfoError::InvalidHeader(&CONN_STRING))?
     148            0 :         .to_str()
     149            0 :         .map_err(|_| ConnInfoError::InvalidHeader(&CONN_STRING))?;
     150              : 
     151            0 :     let connection_url = Url::parse(connection_string)?;
     152              : 
     153            0 :     let protocol = connection_url.scheme();
     154            0 :     if protocol != "postgres" && protocol != "postgresql" {
     155            0 :         return Err(ConnInfoError::IncorrectScheme);
     156            0 :     }
     157              : 
     158            0 :     let mut url_path = connection_url
     159            0 :         .path_segments()
     160            0 :         .ok_or(ConnInfoError::MissingDbName)?;
     161              : 
     162            0 :     let dbname: DbName =
     163            0 :         urlencoding::decode(url_path.next().ok_or(ConnInfoError::InvalidDbName)?)?.into();
     164            0 :     ctx.set_dbname(dbname.clone());
     165              : 
     166            0 :     let username = RoleName::from(urlencoding::decode(connection_url.username())?);
     167            0 :     if username.is_empty() {
     168            0 :         return Err(ConnInfoError::MissingUsername);
     169            0 :     }
     170            0 :     ctx.set_user(username.clone());
     171              : 
     172            0 :     let auth = if let Some(auth) = headers.get(&AUTHORIZATION) {
     173            0 :         if !config.accept_jwts {
     174            0 :             return Err(ConnInfoError::MissingCredentials(Credentials::Password));
     175            0 :         }
     176              : 
     177            0 :         let auth = auth
     178            0 :             .to_str()
     179            0 :             .map_err(|_| ConnInfoError::InvalidHeader(&AUTHORIZATION))?;
     180              :         AuthData::Jwt(
     181            0 :             auth.strip_prefix("Bearer ")
     182            0 :                 .ok_or(ConnInfoError::MissingCredentials(Credentials::BearerJwt))?
     183            0 :                 .into(),
     184              :         )
     185            0 :     } else if let Some(pass) = connection_url.password() {
     186              :         // wrong credentials provided
     187            0 :         if config.accept_jwts {
     188            0 :             return Err(ConnInfoError::MissingCredentials(Credentials::BearerJwt));
     189            0 :         }
     190            0 : 
     191            0 :         AuthData::Password(match urlencoding::decode_binary(pass.as_bytes()) {
     192            0 :             std::borrow::Cow::Borrowed(b) => b.into(),
     193            0 :             std::borrow::Cow::Owned(b) => b.into(),
     194              :         })
     195            0 :     } else if config.accept_jwts {
     196            0 :         return Err(ConnInfoError::MissingCredentials(Credentials::BearerJwt));
     197              :     } else {
     198            0 :         return Err(ConnInfoError::MissingCredentials(Credentials::Password));
     199              :     };
     200              : 
     201            0 :     let endpoint = match connection_url.host() {
     202            0 :         Some(url::Host::Domain(hostname)) => {
     203            0 :             if let Some(tls) = tls {
     204            0 :                 endpoint_sni(hostname, &tls.common_names).ok_or(ConnInfoError::MalformedEndpoint)?
     205              :             } else {
     206            0 :                 hostname
     207            0 :                     .split_once('.')
     208            0 :                     .map_or(hostname, |(prefix, _)| prefix)
     209            0 :                     .into()
     210              :             }
     211              :         }
     212              :         Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) | None => {
     213            0 :             return Err(ConnInfoError::MissingHostname);
     214              :         }
     215              :     };
     216            0 :     ctx.set_endpoint_id(endpoint.clone());
     217            0 : 
     218            0 :     let pairs = connection_url.query_pairs();
     219            0 : 
     220            0 :     let mut options = Option::None;
     221            0 : 
     222            0 :     let mut params = StartupMessageParamsBuilder::default();
     223            0 :     params.insert("user", &username);
     224            0 :     params.insert("database", &dbname);
     225            0 :     for (key, value) in pairs {
     226            0 :         params.insert(&key, &value);
     227            0 :         if key == "options" {
     228            0 :             options = Some(NeonOptions::parse_options_raw(&value));
     229            0 :         }
     230              :     }
     231              : 
     232              :     // check the URL that was used, for metrics
     233              :     {
     234            0 :         let host_endpoint = headers
     235            0 :             // get the host header
     236            0 :             .get("host")
     237            0 :             // extract the domain
     238            0 :             .and_then(|h| {
     239            0 :                 let (host, _port) = h.to_str().ok()?.split_once(':')?;
     240            0 :                 Some(host)
     241            0 :             })
     242            0 :             // get the endpoint prefix
     243            0 :             .map(|h| h.split_once('.').map_or(h, |(prefix, _)| prefix));
     244              : 
     245            0 :         let kind = if host_endpoint == Some(&*endpoint) {
     246            0 :             SniKind::Sni
     247              :         } else {
     248            0 :             SniKind::NoSni
     249              :         };
     250              : 
     251            0 :         let protocol = ctx.protocol();
     252            0 :         Metrics::get()
     253            0 :             .proxy
     254            0 :             .accepted_connections_by_sni
     255            0 :             .inc(SniGroup { protocol, kind });
     256            0 :     }
     257            0 : 
     258            0 :     ctx.set_user_agent(
     259            0 :         headers
     260            0 :             .get(hyper::header::USER_AGENT)
     261            0 :             .and_then(|h| h.to_str().ok())
     262            0 :             .map(Into::into),
     263            0 :     );
     264            0 : 
     265            0 :     let user_info = ComputeUserInfo {
     266            0 :         endpoint,
     267            0 :         user: username,
     268            0 :         options: options.unwrap_or_default(),
     269            0 :     };
     270            0 : 
     271            0 :     let conn_info = ConnInfo { user_info, dbname };
     272            0 :     Ok(ConnInfoWithAuth { conn_info, auth })
     273            0 : }
     274              : 
     275            0 : pub(crate) async fn handle(
     276            0 :     config: &'static ProxyConfig,
     277            0 :     ctx: RequestContext,
     278            0 :     request: Request<Incoming>,
     279            0 :     backend: Arc<PoolingBackend>,
     280            0 :     cancel: CancellationToken,
     281            0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ApiError> {
     282            0 :     let result = handle_inner(cancel, config, &ctx, request, backend).await;
     283              : 
     284            0 :     let mut response = match result {
     285            0 :         Ok(r) => {
     286            0 :             ctx.set_success();
     287            0 : 
     288            0 :             // Handling the error response from local proxy here
     289            0 :             if config.authentication_config.is_auth_broker && r.status().is_server_error() {
     290            0 :                 let status = r.status();
     291              : 
     292            0 :                 let body_bytes = r
     293            0 :                     .collect()
     294            0 :                     .await
     295            0 :                     .map_err(|e| {
     296            0 :                         ApiError::InternalServerError(anyhow::Error::msg(format!(
     297            0 :                             "could not collect http body: {e}"
     298            0 :                         )))
     299            0 :                     })?
     300            0 :                     .to_bytes();
     301              : 
     302            0 :                 if let Ok(mut json_map) =
     303            0 :                     serde_json::from_slice::<IndexMap<&str, &RawValue>>(&body_bytes)
     304              :                 {
     305            0 :                     let message = json_map.get("message");
     306            0 :                     if let Some(message) = message {
     307            0 :                         let msg: String = match serde_json::from_str(message.get()) {
     308            0 :                             Ok(msg) => msg,
     309              :                             Err(_) => {
     310            0 :                                 "Unable to parse the response message from server".to_string()
     311              :                             }
     312              :                         };
     313              : 
     314            0 :                         error!("Error response from local_proxy: {status} {msg}");
     315              : 
     316            0 :                         json_map.retain(|key, _| !key.starts_with("neon:")); // remove all the neon-related keys
     317            0 : 
     318            0 :                         let resp_json = serde_json::to_string(&json_map)
     319            0 :                             .unwrap_or("failed to serialize the response message".to_string());
     320            0 : 
     321            0 :                         return json_response(status, resp_json);
     322            0 :                     }
     323            0 :                 }
     324              : 
     325            0 :                 error!("Unable to parse the response message from local_proxy");
     326            0 :                 return json_response(
     327            0 :                     status,
     328            0 :                     json!({ "message": "Unable to parse the response message from server".to_string() }),
     329            0 :                 );
     330            0 :             }
     331            0 :             r
     332              :         }
     333            0 :         Err(e @ SqlOverHttpError::Cancelled(_)) => {
     334            0 :             let error_kind = e.get_error_kind();
     335            0 :             ctx.set_error_kind(error_kind);
     336            0 : 
     337            0 :             let message = "Query cancelled, connection was terminated";
     338            0 : 
     339            0 :             tracing::info!(
     340            0 :                 kind=error_kind.to_metric_label(),
     341            0 :                 error=%e,
     342            0 :                 msg=message,
     343            0 :                 "forwarding error to user"
     344              :             );
     345              : 
     346            0 :             json_response(
     347            0 :                 StatusCode::BAD_REQUEST,
     348            0 :                 json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
     349            0 :             )?
     350              :         }
     351            0 :         Err(e) => {
     352            0 :             let error_kind = e.get_error_kind();
     353            0 :             ctx.set_error_kind(error_kind);
     354            0 : 
     355            0 :             let mut message = e.to_string_client();
     356            0 :             let db_error = match &e {
     357            0 :                 SqlOverHttpError::ConnectCompute(HttpConnError::PostgresConnectionError(e))
     358            0 :                 | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     359            0 :                 _ => None,
     360              :             };
     361            0 :             fn get<'a, T: Default>(db: Option<&'a DbError>, x: impl FnOnce(&'a DbError) -> T) -> T {
     362            0 :                 db.map(x).unwrap_or_default()
     363            0 :             }
     364              : 
     365            0 :             if let Some(db_error) = db_error {
     366            0 :                 db_error.message().clone_into(&mut message);
     367            0 :             }
     368              : 
     369            0 :             let position = db_error.and_then(|db| db.position());
     370            0 :             let (position, internal_position, internal_query) = match position {
     371            0 :                 Some(ErrorPosition::Original(position)) => (Some(position.to_string()), None, None),
     372            0 :                 Some(ErrorPosition::Internal { position, query }) => {
     373            0 :                     (None, Some(position.to_string()), Some(query.clone()))
     374              :                 }
     375            0 :                 None => (None, None, None),
     376              :             };
     377              : 
     378            0 :             let code = get(db_error, |db| db.code().code());
     379            0 :             let severity = get(db_error, |db| db.severity());
     380            0 :             let detail = get(db_error, |db| db.detail());
     381            0 :             let hint = get(db_error, |db| db.hint());
     382            0 :             let where_ = get(db_error, |db| db.where_());
     383            0 :             let table = get(db_error, |db| db.table());
     384            0 :             let column = get(db_error, |db| db.column());
     385            0 :             let schema = get(db_error, |db| db.schema());
     386            0 :             let datatype = get(db_error, |db| db.datatype());
     387            0 :             let constraint = get(db_error, |db| db.constraint());
     388            0 :             let file = get(db_error, |db| db.file());
     389            0 :             let line = get(db_error, |db| db.line().map(|l| l.to_string()));
     390            0 :             let routine = get(db_error, |db| db.routine());
     391            0 : 
     392            0 :             tracing::info!(
     393            0 :                 kind=error_kind.to_metric_label(),
     394            0 :                 error=%e,
     395            0 :                 msg=message,
     396            0 :                 "forwarding error to user"
     397              :             );
     398              : 
     399            0 :             json_response(
     400            0 :                 e.get_http_status_code(),
     401            0 :                 json!({
     402            0 :                     "message": message,
     403            0 :                     "code": code,
     404            0 :                     "detail": detail,
     405            0 :                     "hint": hint,
     406            0 :                     "position": position,
     407            0 :                     "internalPosition": internal_position,
     408            0 :                     "internalQuery": internal_query,
     409            0 :                     "severity": severity,
     410            0 :                     "where": where_,
     411            0 :                     "table": table,
     412            0 :                     "column": column,
     413            0 :                     "schema": schema,
     414            0 :                     "dataType": datatype,
     415            0 :                     "constraint": constraint,
     416            0 :                     "file": file,
     417            0 :                     "line": line,
     418            0 :                     "routine": routine,
     419            0 :                 }),
     420            0 :             )?
     421              :         }
     422              :     };
     423              : 
     424            0 :     response
     425            0 :         .headers_mut()
     426            0 :         .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
     427            0 :     Ok(response)
     428            0 : }
     429              : 
     430              : #[derive(Debug, thiserror::Error)]
     431              : pub(crate) enum SqlOverHttpError {
     432              :     #[error("{0}")]
     433              :     ReadPayload(#[from] ReadPayloadError),
     434              :     #[error("{0}")]
     435              :     ConnectCompute(#[from] HttpConnError),
     436              :     #[error("{0}")]
     437              :     ConnInfo(#[from] ConnInfoError),
     438              :     #[error("response is too large (max is {0} bytes)")]
     439              :     ResponseTooLarge(usize),
     440              :     #[error("invalid isolation level")]
     441              :     InvalidIsolationLevel,
     442              :     /// for queries our customers choose to run
     443              :     #[error("{0}")]
     444              :     Postgres(#[source] postgres_client::Error),
     445              :     /// for queries we choose to run
     446              :     #[error("{0}")]
     447              :     InternalPostgres(#[source] postgres_client::Error),
     448              :     #[error("{0}")]
     449              :     JsonConversion(#[from] JsonConversionError),
     450              :     #[error("{0}")]
     451              :     Cancelled(SqlOverHttpCancel),
     452              : }
     453              : 
     454              : impl ReportableError for SqlOverHttpError {
     455            0 :     fn get_error_kind(&self) -> ErrorKind {
     456            0 :         match self {
     457            0 :             SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
     458            0 :             SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
     459            0 :             SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
     460            0 :             SqlOverHttpError::ResponseTooLarge(_) => ErrorKind::User,
     461            0 :             SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
     462            0 :             SqlOverHttpError::Postgres(p) => p.get_error_kind(),
     463            0 :             SqlOverHttpError::InternalPostgres(p) => {
     464            0 :                 if p.as_db_error().is_some() {
     465            0 :                     ErrorKind::Service
     466              :                 } else {
     467            0 :                     ErrorKind::Compute
     468              :                 }
     469              :             }
     470            0 :             SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
     471            0 :             SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
     472              :         }
     473            0 :     }
     474              : }
     475              : 
     476              : impl UserFacingError for SqlOverHttpError {
     477            0 :     fn to_string_client(&self) -> String {
     478            0 :         match self {
     479            0 :             SqlOverHttpError::ReadPayload(p) => p.to_string(),
     480            0 :             SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
     481            0 :             SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
     482            0 :             SqlOverHttpError::ResponseTooLarge(_) => self.to_string(),
     483            0 :             SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
     484            0 :             SqlOverHttpError::Postgres(p) => p.to_string(),
     485            0 :             SqlOverHttpError::InternalPostgres(p) => p.to_string(),
     486            0 :             SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
     487            0 :             SqlOverHttpError::Cancelled(_) => self.to_string(),
     488              :         }
     489            0 :     }
     490              : }
     491              : 
     492              : impl HttpCodeError for SqlOverHttpError {
     493            0 :     fn get_http_status_code(&self) -> StatusCode {
     494            0 :         match self {
     495            0 :             SqlOverHttpError::ReadPayload(e) => e.get_http_status_code(),
     496            0 :             SqlOverHttpError::ConnectCompute(h) => match h.get_error_kind() {
     497            0 :                 ErrorKind::User => StatusCode::BAD_REQUEST,
     498            0 :                 _ => StatusCode::INTERNAL_SERVER_ERROR,
     499              :             },
     500            0 :             SqlOverHttpError::ConnInfo(_) => StatusCode::BAD_REQUEST,
     501            0 :             SqlOverHttpError::ResponseTooLarge(_) => StatusCode::INSUFFICIENT_STORAGE,
     502            0 :             SqlOverHttpError::InvalidIsolationLevel => StatusCode::BAD_REQUEST,
     503            0 :             SqlOverHttpError::Postgres(_) => StatusCode::BAD_REQUEST,
     504            0 :             SqlOverHttpError::InternalPostgres(_) => StatusCode::INTERNAL_SERVER_ERROR,
     505            0 :             SqlOverHttpError::JsonConversion(_) => StatusCode::INTERNAL_SERVER_ERROR,
     506            0 :             SqlOverHttpError::Cancelled(_) => StatusCode::INTERNAL_SERVER_ERROR,
     507              :         }
     508            0 :     }
     509              : }
     510              : 
     511              : #[derive(Debug, thiserror::Error)]
     512              : pub(crate) enum ReadPayloadError {
     513              :     #[error("could not read the HTTP request body: {0}")]
     514              :     Read(#[from] hyper::Error),
     515              :     #[error("request is too large (max is {limit} bytes)")]
     516              :     BodyTooLarge { limit: usize },
     517              :     #[error("could not parse the HTTP request body: {0}")]
     518              :     Parse(#[from] serde_json::Error),
     519              : }
     520              : 
     521              : impl From<ReadBodyError<hyper::Error>> for ReadPayloadError {
     522            0 :     fn from(value: ReadBodyError<hyper::Error>) -> Self {
     523            0 :         match value {
     524            0 :             ReadBodyError::BodyTooLarge { limit } => Self::BodyTooLarge { limit },
     525            0 :             ReadBodyError::Read(e) => Self::Read(e),
     526              :         }
     527            0 :     }
     528              : }
     529              : 
     530              : impl ReportableError for ReadPayloadError {
     531            0 :     fn get_error_kind(&self) -> ErrorKind {
     532            0 :         match self {
     533            0 :             ReadPayloadError::Read(_) => ErrorKind::ClientDisconnect,
     534            0 :             ReadPayloadError::BodyTooLarge { .. } => ErrorKind::User,
     535            0 :             ReadPayloadError::Parse(_) => ErrorKind::User,
     536              :         }
     537            0 :     }
     538              : }
     539              : 
     540              : impl HttpCodeError for ReadPayloadError {
     541            0 :     fn get_http_status_code(&self) -> StatusCode {
     542            0 :         match self {
     543            0 :             ReadPayloadError::Read(_) => StatusCode::BAD_REQUEST,
     544            0 :             ReadPayloadError::BodyTooLarge { .. } => StatusCode::PAYLOAD_TOO_LARGE,
     545            0 :             ReadPayloadError::Parse(_) => StatusCode::BAD_REQUEST,
     546              :         }
     547            0 :     }
     548              : }
     549              : 
     550              : #[derive(Debug, thiserror::Error)]
     551              : pub(crate) enum SqlOverHttpCancel {
     552              :     #[error("query was cancelled")]
     553              :     Postgres,
     554              :     #[error("query was cancelled while stuck trying to connect to the database")]
     555              :     Connect,
     556              : }
     557              : 
     558              : impl ReportableError for SqlOverHttpCancel {
     559            0 :     fn get_error_kind(&self) -> ErrorKind {
     560            0 :         match self {
     561            0 :             SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
     562            0 :             SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
     563              :         }
     564            0 :     }
     565              : }
     566              : 
     567              : #[derive(Clone, Copy, Debug)]
     568              : struct HttpHeaders {
     569              :     raw_output: bool,
     570              :     default_array_mode: bool,
     571              :     txn_isolation_level: Option<IsolationLevel>,
     572              :     txn_read_only: bool,
     573              :     txn_deferrable: bool,
     574              : }
     575              : 
     576              : impl HttpHeaders {
     577            0 :     fn try_parse(headers: &hyper::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
     578            0 :         // Determine the output options. Default behaviour is 'false'. Anything that is not
     579            0 :         // strictly 'true' assumed to be false.
     580            0 :         let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
     581            0 :         let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
     582              : 
     583              :         // isolation level, read only and deferrable
     584            0 :         let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
     585            0 :             Some(x) => Some(
     586            0 :                 map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
     587              :             ),
     588            0 :             None => None,
     589              :         };
     590              : 
     591            0 :         let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
     592            0 :         let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
     593            0 : 
     594            0 :         Ok(Self {
     595            0 :             raw_output,
     596            0 :             default_array_mode,
     597            0 :             txn_isolation_level,
     598            0 :             txn_read_only,
     599            0 :             txn_deferrable,
     600            0 :         })
     601            0 :     }
     602              : }
     603              : 
     604            0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
     605            0 :     match level.as_bytes() {
     606            0 :         b"Serializable" => Some(IsolationLevel::Serializable),
     607            0 :         b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
     608            0 :         b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
     609            0 :         b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
     610            0 :         _ => None,
     611              :     }
     612            0 : }
     613              : 
     614            0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
     615            0 :     match level {
     616            0 :         IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
     617            0 :         IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
     618            0 :         IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
     619            0 :         IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
     620            0 :         _ => None,
     621              :     }
     622            0 : }
     623              : 
     624            0 : async fn handle_inner(
     625            0 :     cancel: CancellationToken,
     626            0 :     config: &'static ProxyConfig,
     627            0 :     ctx: &RequestContext,
     628            0 :     request: Request<Incoming>,
     629            0 :     backend: Arc<PoolingBackend>,
     630            0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
     631            0 :     let _requeset_gauge = Metrics::get()
     632            0 :         .proxy
     633            0 :         .connection_requests
     634            0 :         .guard(ctx.protocol());
     635            0 :     info!(
     636            0 :         protocol = %ctx.protocol(),
     637            0 :         "handling interactive connection from client"
     638              :     );
     639              : 
     640            0 :     let conn_info = get_conn_info(
     641            0 :         &config.authentication_config,
     642            0 :         ctx,
     643            0 :         request.headers(),
     644            0 :         // todo: race condition?
     645            0 :         // we're unlikely to change the common names.
     646            0 :         config.tls_config.load().as_deref(),
     647            0 :     )?;
     648            0 :     info!(
     649            0 :         user = conn_info.conn_info.user_info.user.as_str(),
     650            0 :         "credentials"
     651              :     );
     652              : 
     653            0 :     match conn_info.auth {
     654            0 :         AuthData::Jwt(jwt) if config.authentication_config.is_auth_broker => {
     655            0 :             handle_auth_broker_inner(ctx, request, conn_info.conn_info, jwt, backend).await
     656              :         }
     657            0 :         auth => {
     658            0 :             handle_db_inner(
     659            0 :                 cancel,
     660            0 :                 config,
     661            0 :                 ctx,
     662            0 :                 request,
     663            0 :                 conn_info.conn_info,
     664            0 :                 auth,
     665            0 :                 backend,
     666            0 :             )
     667            0 :             .await
     668              :         }
     669              :     }
     670            0 : }
     671              : 
     672            0 : async fn handle_db_inner(
     673            0 :     cancel: CancellationToken,
     674            0 :     config: &'static ProxyConfig,
     675            0 :     ctx: &RequestContext,
     676            0 :     request: Request<Incoming>,
     677            0 :     conn_info: ConnInfo,
     678            0 :     auth: AuthData,
     679            0 :     backend: Arc<PoolingBackend>,
     680            0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
     681            0 :     //
     682            0 :     // Determine the destination and connection params
     683            0 :     //
     684            0 :     let headers = request.headers();
     685              : 
     686              :     // Allow connection pooling only if explicitly requested
     687              :     // or if we have decided that http pool is no longer opt-in
     688            0 :     let allow_pool = !config.http_config.pool_options.opt_in
     689            0 :         || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
     690              : 
     691            0 :     let parsed_headers = HttpHeaders::try_parse(headers)?;
     692              : 
     693            0 :     let mut request_len = 0;
     694            0 :     let fetch_and_process_request = Box::pin(
     695            0 :         async {
     696            0 :             let body = read_body_with_limit(
     697            0 :                 request.into_body(),
     698            0 :                 config.http_config.max_request_size_bytes,
     699            0 :             )
     700            0 :             .await?;
     701              : 
     702            0 :             request_len = body.len();
     703            0 : 
     704            0 :             Metrics::get()
     705            0 :                 .proxy
     706            0 :                 .http_conn_content_length_bytes
     707            0 :                 .observe(HttpDirection::Request, body.len() as f64);
     708            0 : 
     709            0 :             debug!(length = body.len(), "request payload read");
     710            0 :             let payload: Payload = serde_json::from_slice(&body)?;
     711            0 :             Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
     712            0 :         }
     713            0 :         .map_err(SqlOverHttpError::from),
     714            0 :     );
     715            0 : 
     716            0 :     let authenticate_and_connect = Box::pin(
     717            0 :         async {
     718            0 :             let keys = match auth {
     719            0 :                 AuthData::Password(pw) => backend
     720            0 :                     .authenticate_with_password(ctx, &conn_info.user_info, &pw)
     721            0 :                     .await
     722            0 :                     .map_err(HttpConnError::AuthError)?,
     723            0 :                 AuthData::Jwt(jwt) => backend
     724            0 :                     .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
     725            0 :                     .await
     726            0 :                     .map_err(HttpConnError::AuthError)?,
     727              :             };
     728              : 
     729            0 :             let client = match keys.keys {
     730            0 :                 ComputeCredentialKeys::JwtPayload(payload)
     731            0 :                     if backend.auth_backend.is_local_proxy() =>
     732              :                 {
     733            0 :                     let mut client = backend.connect_to_local_postgres(ctx, conn_info).await?;
     734            0 :                     let (cli_inner, _dsc) = client.client_inner();
     735            0 :                     cli_inner.set_jwt_session(&payload).await?;
     736            0 :                     Client::Local(client)
     737              :                 }
     738              :                 _ => {
     739            0 :                     let client = backend
     740            0 :                         .connect_to_compute(ctx, conn_info, keys, !allow_pool)
     741            0 :                         .await?;
     742            0 :                     Client::Remote(client)
     743              :                 }
     744              :             };
     745              : 
     746              :             // not strictly necessary to mark success here,
     747              :             // but it's just insurance for if we forget it somewhere else
     748            0 :             ctx.success();
     749            0 :             Ok::<_, SqlOverHttpError>(client)
     750            0 :         }
     751            0 :         .map_err(SqlOverHttpError::from),
     752            0 :     );
     753              : 
     754            0 :     let (payload, mut client) = match run_until_cancelled(
     755            0 :         // Run both operations in parallel
     756            0 :         try_join(
     757            0 :             pin!(fetch_and_process_request),
     758            0 :             pin!(authenticate_and_connect),
     759            0 :         ),
     760            0 :         &cancel,
     761            0 :     )
     762            0 :     .await
     763              :     {
     764            0 :         Some(result) => result?,
     765            0 :         None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
     766              :     };
     767              : 
     768            0 :     let mut response = Response::builder()
     769            0 :         .status(StatusCode::OK)
     770            0 :         .header(header::CONTENT_TYPE, "application/json");
     771              : 
     772              :     // Now execute the query and return the result.
     773            0 :     let json_output = match payload {
     774            0 :         Payload::Single(stmt) => {
     775            0 :             stmt.process(&config.http_config, cancel, &mut client, parsed_headers)
     776            0 :                 .await?
     777              :         }
     778            0 :         Payload::Batch(statements) => {
     779            0 :             if parsed_headers.txn_read_only {
     780            0 :                 response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
     781            0 :             }
     782            0 :             if parsed_headers.txn_deferrable {
     783            0 :                 response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
     784            0 :             }
     785            0 :             if let Some(txn_isolation_level) = parsed_headers
     786            0 :                 .txn_isolation_level
     787            0 :                 .and_then(map_isolation_level_to_headers)
     788            0 :             {
     789            0 :                 response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
     790            0 :             }
     791              : 
     792            0 :             statements
     793            0 :                 .process(&config.http_config, cancel, &mut client, parsed_headers)
     794            0 :                 .await?
     795              :         }
     796              :     };
     797              : 
     798            0 :     let metrics = client.metrics(ctx);
     799            0 : 
     800            0 :     let len = json_output.len();
     801            0 :     let response = response
     802            0 :         .body(
     803            0 :             Full::new(Bytes::from(json_output))
     804            0 :                 .map_err(|x| match x {})
     805            0 :                 .boxed(),
     806            0 :         )
     807            0 :         // only fails if invalid status code or invalid header/values are given.
     808            0 :         // these are not user configurable so it cannot fail dynamically
     809            0 :         .expect("building response payload should not fail");
     810            0 : 
     811            0 :     // count the egress bytes - we miss the TLS and header overhead but oh well...
     812            0 :     // moving this later in the stack is going to be a lot of effort and ehhhh
     813            0 :     metrics.record_egress(len as u64);
     814            0 :     metrics.record_ingress(request_len as u64);
     815            0 : 
     816            0 :     Metrics::get()
     817            0 :         .proxy
     818            0 :         .http_conn_content_length_bytes
     819            0 :         .observe(HttpDirection::Response, len as f64);
     820            0 : 
     821            0 :     Ok(response)
     822            0 : }
     823              : 
     824              : static HEADERS_TO_FORWARD: &[&HeaderName] = &[
     825              :     &AUTHORIZATION,
     826              :     &CONN_STRING,
     827              :     &RAW_TEXT_OUTPUT,
     828              :     &ARRAY_MODE,
     829              :     &TXN_ISOLATION_LEVEL,
     830              :     &TXN_READ_ONLY,
     831              :     &TXN_DEFERRABLE,
     832              : ];
     833              : 
     834            0 : pub(crate) fn uuid_to_header_value(id: Uuid) -> HeaderValue {
     835            0 :     let mut uuid = [0; uuid::fmt::Hyphenated::LENGTH];
     836            0 :     HeaderValue::from_str(id.as_hyphenated().encode_lower(&mut uuid[..]))
     837            0 :         .expect("uuid hyphenated format should be all valid header characters")
     838            0 : }
     839              : 
     840            0 : async fn handle_auth_broker_inner(
     841            0 :     ctx: &RequestContext,
     842            0 :     request: Request<Incoming>,
     843            0 :     conn_info: ConnInfo,
     844            0 :     jwt: String,
     845            0 :     backend: Arc<PoolingBackend>,
     846            0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
     847            0 :     backend
     848            0 :         .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
     849            0 :         .await
     850            0 :         .map_err(HttpConnError::from)?;
     851              : 
     852            0 :     let mut client = backend.connect_to_local_proxy(ctx, conn_info).await?;
     853              : 
     854            0 :     let local_proxy_uri = ::http::Uri::from_static("http://proxy.local/sql");
     855            0 : 
     856            0 :     let (mut parts, body) = request.into_parts();
     857            0 :     let mut req = Request::builder().method(Method::POST).uri(local_proxy_uri);
     858              : 
     859              :     // todo(conradludgate): maybe auth-broker should parse these and re-serialize
     860              :     // these instead just to ensure they remain normalised.
     861            0 :     for &h in HEADERS_TO_FORWARD {
     862            0 :         if let Some(hv) = parts.headers.remove(h) {
     863            0 :             req = req.header(h, hv);
     864            0 :         }
     865              :     }
     866            0 :     req = req.header(&NEON_REQUEST_ID, uuid_to_header_value(ctx.session_id()));
     867            0 : 
     868            0 :     let req = req
     869            0 :         .body(body)
     870            0 :         .expect("all headers and params received via hyper should be valid for request");
     871            0 : 
     872            0 :     // todo: map body to count egress
     873            0 :     let _metrics = client.metrics(ctx);
     874            0 : 
     875            0 :     Ok(client
     876            0 :         .inner
     877            0 :         .inner
     878            0 :         .send_request(req)
     879            0 :         .await
     880            0 :         .map_err(LocalProxyConnError::from)
     881            0 :         .map_err(HttpConnError::from)?
     882            0 :         .map(|b| b.boxed()))
     883            0 : }
     884              : 
     885              : impl QueryData {
     886            0 :     async fn process(
     887            0 :         self,
     888            0 :         config: &'static HttpConfig,
     889            0 :         cancel: CancellationToken,
     890            0 :         client: &mut Client,
     891            0 :         parsed_headers: HttpHeaders,
     892            0 :     ) -> Result<String, SqlOverHttpError> {
     893            0 :         let (inner, mut discard) = client.inner();
     894            0 :         let cancel_token = inner.cancel_token();
     895            0 : 
     896            0 :         match select(
     897            0 :             pin!(query_to_json(
     898            0 :                 config,
     899            0 :                 &mut *inner,
     900            0 :                 self,
     901            0 :                 &mut 0,
     902            0 :                 parsed_headers
     903            0 :             )),
     904            0 :             pin!(cancel.cancelled()),
     905            0 :         )
     906            0 :         .await
     907              :         {
     908              :             // The query successfully completed.
     909            0 :             Either::Left((Ok((status, results)), __not_yet_cancelled)) => {
     910            0 :                 discard.check_idle(status);
     911            0 : 
     912            0 :                 let json_output =
     913            0 :                     serde_json::to_string(&results).expect("json serialization should not fail");
     914            0 :                 Ok(json_output)
     915              :             }
     916              :             // The query failed with an error
     917            0 :             Either::Left((Err(e), __not_yet_cancelled)) => {
     918            0 :                 discard.discard();
     919            0 :                 Err(e)
     920              :             }
     921              :             // The query was cancelled.
     922            0 :             Either::Right((_cancelled, query)) => {
     923            0 :                 tracing::info!("cancelling query");
     924            0 :                 if let Err(err) = cancel_token.cancel_query(NoTls).await {
     925            0 :                     tracing::warn!(?err, "could not cancel query");
     926            0 :                 }
     927              :                 // wait for the query cancellation
     928            0 :                 match time::timeout(time::Duration::from_millis(100), query).await {
     929              :                     // query successed before it was cancelled.
     930            0 :                     Ok(Ok((status, results))) => {
     931            0 :                         discard.check_idle(status);
     932            0 : 
     933            0 :                         let json_output = serde_json::to_string(&results)
     934            0 :                             .expect("json serialization should not fail");
     935            0 :                         Ok(json_output)
     936              :                     }
     937              :                     // query failed or was cancelled.
     938            0 :                     Ok(Err(error)) => {
     939            0 :                         let db_error = match &error {
     940              :                             SqlOverHttpError::ConnectCompute(
     941            0 :                                 HttpConnError::PostgresConnectionError(e),
     942              :                             )
     943            0 :                             | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     944            0 :                             _ => None,
     945              :                         };
     946              : 
     947              :                         // if errored for some other reason, it might not be safe to return
     948            0 :                         if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
     949            0 :                             discard.discard();
     950            0 :                         }
     951              : 
     952            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     953              :                     }
     954            0 :                     Err(_timeout) => {
     955            0 :                         discard.discard();
     956            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     957              :                     }
     958              :                 }
     959              :             }
     960              :         }
     961            0 :     }
     962              : }
     963              : 
     964              : impl BatchQueryData {
     965            0 :     async fn process(
     966            0 :         self,
     967            0 :         config: &'static HttpConfig,
     968            0 :         cancel: CancellationToken,
     969            0 :         client: &mut Client,
     970            0 :         parsed_headers: HttpHeaders,
     971            0 :     ) -> Result<String, SqlOverHttpError> {
     972            0 :         info!("starting transaction");
     973            0 :         let (inner, mut discard) = client.inner();
     974            0 :         let cancel_token = inner.cancel_token();
     975            0 :         let mut builder = inner.build_transaction();
     976            0 :         if let Some(isolation_level) = parsed_headers.txn_isolation_level {
     977            0 :             builder = builder.isolation_level(isolation_level);
     978            0 :         }
     979            0 :         if parsed_headers.txn_read_only {
     980            0 :             builder = builder.read_only(true);
     981            0 :         }
     982            0 :         if parsed_headers.txn_deferrable {
     983            0 :             builder = builder.deferrable(true);
     984            0 :         }
     985              : 
     986            0 :         let mut transaction = builder
     987            0 :             .start()
     988            0 :             .await
     989            0 :             .inspect_err(|_| {
     990            0 :                 // if we cannot start a transaction, we should return immediately
     991            0 :                 // and not return to the pool. connection is clearly broken
     992            0 :                 discard.discard();
     993            0 :             })
     994            0 :             .map_err(SqlOverHttpError::Postgres)?;
     995              : 
     996            0 :         let json_output = match query_batch(
     997            0 :             config,
     998            0 :             cancel.child_token(),
     999            0 :             &mut transaction,
    1000            0 :             self,
    1001            0 :             parsed_headers,
    1002            0 :         )
    1003            0 :         .await
    1004              :         {
    1005            0 :             Ok(json_output) => {
    1006            0 :                 info!("commit");
    1007            0 :                 let status = transaction
    1008            0 :                     .commit()
    1009            0 :                     .await
    1010            0 :                     .inspect_err(|_| {
    1011            0 :                         // if we cannot commit - for now don't return connection to pool
    1012            0 :                         // TODO: get a query status from the error
    1013            0 :                         discard.discard();
    1014            0 :                     })
    1015            0 :                     .map_err(SqlOverHttpError::Postgres)?;
    1016            0 :                 discard.check_idle(status);
    1017            0 :                 json_output
    1018              :             }
    1019              :             Err(SqlOverHttpError::Cancelled(_)) => {
    1020            0 :                 if let Err(err) = cancel_token.cancel_query(NoTls).await {
    1021            0 :                     tracing::warn!(?err, "could not cancel query");
    1022            0 :                 }
    1023              :                 // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
    1024            0 :                 discard.discard();
    1025            0 : 
    1026            0 :                 return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
    1027              :             }
    1028            0 :             Err(err) => {
    1029            0 :                 info!("rollback");
    1030            0 :                 let status = transaction
    1031            0 :                     .rollback()
    1032            0 :                     .await
    1033            0 :                     .inspect_err(|_| {
    1034            0 :                         // if we cannot rollback - for now don't return connection to pool
    1035            0 :                         // TODO: get a query status from the error
    1036            0 :                         discard.discard();
    1037            0 :                     })
    1038            0 :                     .map_err(SqlOverHttpError::Postgres)?;
    1039            0 :                 discard.check_idle(status);
    1040            0 :                 return Err(err);
    1041              :             }
    1042              :         };
    1043              : 
    1044            0 :         Ok(json_output)
    1045            0 :     }
    1046              : }
    1047              : 
    1048            0 : async fn query_batch(
    1049            0 :     config: &'static HttpConfig,
    1050            0 :     cancel: CancellationToken,
    1051            0 :     transaction: &mut Transaction<'_>,
    1052            0 :     queries: BatchQueryData,
    1053            0 :     parsed_headers: HttpHeaders,
    1054            0 : ) -> Result<String, SqlOverHttpError> {
    1055            0 :     let mut results = Vec::with_capacity(queries.queries.len());
    1056            0 :     let mut current_size = 0;
    1057            0 :     for stmt in queries.queries {
    1058            0 :         let query = pin!(query_to_json(
    1059            0 :             config,
    1060            0 :             transaction,
    1061            0 :             stmt,
    1062            0 :             &mut current_size,
    1063            0 :             parsed_headers,
    1064            0 :         ));
    1065            0 :         let cancelled = pin!(cancel.cancelled());
    1066            0 :         let res = select(query, cancelled).await;
    1067            0 :         match res {
    1068              :             // TODO: maybe we should check that the transaction bit is set here
    1069            0 :             Either::Left((Ok((_, values)), _cancelled)) => {
    1070            0 :                 results.push(values);
    1071            0 :             }
    1072            0 :             Either::Left((Err(e), _cancelled)) => {
    1073            0 :                 return Err(e);
    1074              :             }
    1075            0 :             Either::Right((_cancelled, _)) => {
    1076            0 :                 return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
    1077              :             }
    1078              :         }
    1079              :     }
    1080              : 
    1081            0 :     let results = json!({ "results": results });
    1082            0 :     let json_output = serde_json::to_string(&results).expect("json serialization should not fail");
    1083            0 : 
    1084            0 :     Ok(json_output)
    1085            0 : }
    1086              : 
    1087            0 : async fn query_to_json<T: GenericClient>(
    1088            0 :     config: &'static HttpConfig,
    1089            0 :     client: &mut T,
    1090            0 :     data: QueryData,
    1091            0 :     current_size: &mut usize,
    1092            0 :     parsed_headers: HttpHeaders,
    1093            0 : ) -> Result<(ReadyForQueryStatus, impl Serialize + use<T>), SqlOverHttpError> {
    1094            0 :     let query_start = Instant::now();
    1095            0 : 
    1096            0 :     let query_params = data.params;
    1097            0 :     let mut row_stream = client
    1098            0 :         .query_raw_txt(&data.query, query_params)
    1099            0 :         .await
    1100            0 :         .map_err(SqlOverHttpError::Postgres)?;
    1101            0 :     let query_acknowledged = Instant::now();
    1102            0 : 
    1103            0 :     let columns_len = row_stream.statement.columns().len();
    1104            0 :     let mut fields = Vec::with_capacity(columns_len);
    1105            0 :     let mut types = Vec::with_capacity(columns_len);
    1106              : 
    1107            0 :     for c in row_stream.statement.columns() {
    1108            0 :         fields.push(json!({
    1109            0 :             "name": c.name().to_owned(),
    1110            0 :             "dataTypeID": c.type_().oid(),
    1111            0 :             "tableID": c.table_oid(),
    1112            0 :             "columnID": c.column_id(),
    1113            0 :             "dataTypeSize": c.type_size(),
    1114            0 :             "dataTypeModifier": c.type_modifier(),
    1115            0 :             "format": "text",
    1116            0 :         }));
    1117            0 : 
    1118            0 :         types.push(c.type_().clone());
    1119            0 :     }
    1120              : 
    1121            0 :     let raw_output = parsed_headers.raw_output;
    1122            0 :     let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
    1123            0 : 
    1124            0 :     // Manually drain the stream into a vector to leave row_stream hanging
    1125            0 :     // around to get a command tag. Also check that the response is not too
    1126            0 :     // big.
    1127            0 :     let mut rows = Vec::new();
    1128            0 :     while let Some(row) = row_stream.next().await {
    1129            0 :         let row = row.map_err(SqlOverHttpError::Postgres)?;
    1130            0 :         *current_size += row.body_len();
    1131            0 : 
    1132            0 :         // we don't have a streaming response support yet so this is to prevent OOM
    1133            0 :         // from a malicious query (eg a cross join)
    1134            0 :         if *current_size > config.max_response_size_bytes {
    1135            0 :             return Err(SqlOverHttpError::ResponseTooLarge(
    1136            0 :                 config.max_response_size_bytes,
    1137            0 :             ));
    1138            0 :         }
    1139              : 
    1140            0 :         let row = pg_text_row_to_json(&row, &types, raw_output, array_mode)?;
    1141            0 :         rows.push(row);
    1142            0 : 
    1143            0 :         // assumption: parsing pg text and converting to json takes CPU time.
    1144            0 :         // let's assume it is slightly expensive, so we should consume some cooperative budget.
    1145            0 :         // Especially considering that `RowStream::next` might be pulling from a batch
    1146            0 :         // of rows and never hit the tokio mpsc for a long time (although unlikely).
    1147            0 :         tokio::task::consume_budget().await;
    1148              :     }
    1149              : 
    1150            0 :     let query_resp_end = Instant::now();
    1151            0 :     let RowStream {
    1152            0 :         command_tag,
    1153            0 :         status: ready,
    1154            0 :         ..
    1155            0 :     } = row_stream;
    1156            0 : 
    1157            0 :     // grab the command tag and number of rows affected
    1158            0 :     let command_tag = command_tag.unwrap_or_default();
    1159            0 :     let mut command_tag_split = command_tag.split(' ');
    1160            0 :     let command_tag_name = command_tag_split.next().unwrap_or_default();
    1161            0 :     let command_tag_count = if command_tag_name == "INSERT" {
    1162              :         // INSERT returns OID first and then number of rows
    1163            0 :         command_tag_split.nth(1)
    1164              :     } else {
    1165              :         // other commands return number of rows (if any)
    1166            0 :         command_tag_split.next()
    1167              :     }
    1168            0 :     .and_then(|s| s.parse::<i64>().ok());
    1169            0 : 
    1170            0 :     info!(
    1171            0 :         rows = rows.len(),
    1172            0 :         ?ready,
    1173            0 :         command_tag,
    1174            0 :         acknowledgement = ?(query_acknowledged - query_start),
    1175            0 :         response = ?(query_resp_end - query_start),
    1176            0 :         "finished executing query"
    1177              :     );
    1178              : 
    1179              :     // Resulting JSON format is based on the format of node-postgres result.
    1180            0 :     let results = json!({
    1181            0 :         "command": command_tag_name.to_string(),
    1182            0 :         "rowCount": command_tag_count,
    1183            0 :         "rows": rows,
    1184            0 :         "fields": fields,
    1185            0 :         "rowAsArray": array_mode,
    1186            0 :     });
    1187            0 : 
    1188            0 :     Ok((ready, results))
    1189            0 : }
    1190              : 
    1191              : enum Client {
    1192              :     Remote(conn_pool_lib::Client<postgres_client::Client>),
    1193              :     Local(conn_pool_lib::Client<postgres_client::Client>),
    1194              : }
    1195              : 
    1196              : enum Discard<'a> {
    1197              :     Remote(conn_pool_lib::Discard<'a, postgres_client::Client>),
    1198              :     Local(conn_pool_lib::Discard<'a, postgres_client::Client>),
    1199              : }
    1200              : 
    1201              : impl Client {
    1202            0 :     fn metrics(&self, ctx: &RequestContext) -> Arc<MetricCounter> {
    1203            0 :         match self {
    1204            0 :             Client::Remote(client) => client.metrics(ctx),
    1205            0 :             Client::Local(local_client) => local_client.metrics(ctx),
    1206              :         }
    1207            0 :     }
    1208              : 
    1209            0 :     fn inner(&mut self) -> (&mut postgres_client::Client, Discard<'_>) {
    1210            0 :         match self {
    1211            0 :             Client::Remote(client) => {
    1212            0 :                 let (c, d) = client.inner();
    1213            0 :                 (c, Discard::Remote(d))
    1214              :             }
    1215            0 :             Client::Local(local_client) => {
    1216            0 :                 let (c, d) = local_client.inner();
    1217            0 :                 (c, Discard::Local(d))
    1218              :             }
    1219              :         }
    1220            0 :     }
    1221              : }
    1222              : 
    1223              : impl Discard<'_> {
    1224            0 :     fn check_idle(&mut self, status: ReadyForQueryStatus) {
    1225            0 :         match self {
    1226            0 :             Discard::Remote(discard) => discard.check_idle(status),
    1227            0 :             Discard::Local(discard) => discard.check_idle(status),
    1228              :         }
    1229            0 :     }
    1230            0 :     fn discard(&mut self) {
    1231            0 :         match self {
    1232            0 :             Discard::Remote(discard) => discard.discard(),
    1233            0 :             Discard::Local(discard) => discard.discard(),
    1234              :         }
    1235            0 :     }
    1236              : }
    1237              : 
    1238              : #[cfg(test)]
    1239              : mod tests {
    1240              :     use super::*;
    1241              : 
    1242              :     #[test]
    1243            1 :     fn test_payload() {
    1244            1 :         let payload = "{\"query\":\"SELECT * FROM users WHERE name = ?\",\"params\":[\"test\"],\"arrayMode\":true}";
    1245            1 :         let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
    1246            1 : 
    1247            1 :         match deserialized_payload {
    1248              :             Payload::Single(QueryData {
    1249            1 :                 query,
    1250            1 :                 params,
    1251            1 :                 array_mode,
    1252            1 :             }) => {
    1253            1 :                 assert_eq!(query, "SELECT * FROM users WHERE name = ?");
    1254            1 :                 assert_eq!(params, vec![Some(String::from("test"))]);
    1255            1 :                 assert!(array_mode.unwrap());
    1256              :             }
    1257              :             Payload::Batch(_) => {
    1258            0 :                 panic!("deserialization failed: case with single query, one param, and array mode")
    1259              :             }
    1260              :         }
    1261              : 
    1262            1 :         let payload = "{\"queries\":[{\"query\":\"SELECT * FROM users0 WHERE name = ?\",\"params\":[\"test0\"], \"arrayMode\":false},{\"query\":\"SELECT * FROM users1 WHERE name = ?\",\"params\":[\"test1\"],\"arrayMode\":true}]}";
    1263            1 :         let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
    1264            1 : 
    1265            1 :         match deserialized_payload {
    1266            1 :             Payload::Batch(BatchQueryData { queries }) => {
    1267            1 :                 assert_eq!(queries.len(), 2);
    1268            2 :                 for (i, query) in queries.into_iter().enumerate() {
    1269            2 :                     assert_eq!(
    1270            2 :                         query.query,
    1271            2 :                         format!("SELECT * FROM users{i} WHERE name = ?")
    1272            2 :                     );
    1273            2 :                     assert_eq!(query.params, vec![Some(format!("test{i}"))]);
    1274            2 :                     assert_eq!(query.array_mode.unwrap(), i > 0);
    1275              :                 }
    1276              :             }
    1277            0 :             Payload::Single(_) => panic!("deserialization failed: case with multiple queries"),
    1278              :         }
    1279              : 
    1280            1 :         let payload = "{\"query\":\"SELECT 1\"}";
    1281            1 :         let deserialized_payload: Payload = serde_json::from_str(payload).unwrap();
    1282            1 : 
    1283            1 :         match deserialized_payload {
    1284              :             Payload::Single(QueryData {
    1285            1 :                 query,
    1286            1 :                 params,
    1287            1 :                 array_mode,
    1288            1 :             }) => {
    1289            1 :                 assert_eq!(query, "SELECT 1");
    1290            1 :                 assert_eq!(params, vec![]);
    1291            1 :                 assert!(array_mode.is_none());
    1292              :             }
    1293            0 :             Payload::Batch(_) => panic!("deserialization failed: case with only one query"),
    1294              :         }
    1295            1 :     }
    1296              : }
        

Generated by: LCOV version 2.1-beta