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

Generated by: LCOV version 2.1-beta