LCOV - code coverage report
Current view: top level - proxy/src/serverless - sql_over_http.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 0.0 % 556 0
Test Date: 2024-06-25 13:20:00 Functions: 0.0 % 135 0

            Line data    Source code
       1              : use std::pin::pin;
       2              : use std::sync::Arc;
       3              : 
       4              : use bytes::Bytes;
       5              : use futures::future::select;
       6              : use futures::future::try_join;
       7              : use futures::future::Either;
       8              : use futures::StreamExt;
       9              : use futures::TryFutureExt;
      10              : use http_body_util::BodyExt;
      11              : use http_body_util::Full;
      12              : use hyper1::body::Body;
      13              : use hyper1::body::Incoming;
      14              : use hyper1::header;
      15              : use hyper1::http::HeaderName;
      16              : use hyper1::http::HeaderValue;
      17              : use hyper1::Response;
      18              : use hyper1::StatusCode;
      19              : use hyper1::{HeaderMap, Request};
      20              : use pq_proto::StartupMessageParamsBuilder;
      21              : use serde_json::json;
      22              : use serde_json::Value;
      23              : use tokio::time;
      24              : use tokio_postgres::error::DbError;
      25              : use tokio_postgres::error::ErrorPosition;
      26              : use tokio_postgres::error::SqlState;
      27              : use tokio_postgres::GenericClient;
      28              : use tokio_postgres::IsolationLevel;
      29              : use tokio_postgres::NoTls;
      30              : use tokio_postgres::ReadyForQueryStatus;
      31              : use tokio_postgres::Transaction;
      32              : use tokio_util::sync::CancellationToken;
      33              : use tracing::error;
      34              : use tracing::info;
      35              : use url::Url;
      36              : use utils::http::error::ApiError;
      37              : 
      38              : use crate::auth::backend::ComputeUserInfo;
      39              : use crate::auth::endpoint_sni;
      40              : use crate::auth::ComputeUserInfoParseError;
      41              : use crate::config::ProxyConfig;
      42              : use crate::config::TlsConfig;
      43              : use crate::context::RequestMonitoring;
      44              : use crate::error::ErrorKind;
      45              : use crate::error::ReportableError;
      46              : use crate::error::UserFacingError;
      47              : use crate::metrics::HttpDirection;
      48              : use crate::metrics::Metrics;
      49              : use crate::proxy::run_until_cancelled;
      50              : use crate::proxy::NeonOptions;
      51              : use crate::serverless::backend::HttpConnError;
      52              : use crate::usage_metrics::MetricCounterRecorder;
      53              : use crate::DbName;
      54              : use crate::RoleName;
      55              : 
      56              : use super::backend::PoolingBackend;
      57              : use super::conn_pool::Client;
      58              : use super::conn_pool::ConnInfo;
      59              : use super::http_util::json_response;
      60              : use super::json::json_to_pg_text;
      61              : use super::json::pg_text_row_to_json;
      62              : use super::json::JsonConversionError;
      63              : 
      64            0 : #[derive(serde::Deserialize)]
      65              : #[serde(rename_all = "camelCase")]
      66              : struct QueryData {
      67              :     query: String,
      68              :     #[serde(deserialize_with = "bytes_to_pg_text")]
      69              :     params: Vec<Option<String>>,
      70              :     #[serde(default)]
      71              :     array_mode: Option<bool>,
      72              : }
      73              : 
      74            0 : #[derive(serde::Deserialize)]
      75              : struct BatchQueryData {
      76              :     queries: Vec<QueryData>,
      77              : }
      78              : 
      79              : #[derive(serde::Deserialize)]
      80              : #[serde(untagged)]
      81              : enum Payload {
      82              :     Single(QueryData),
      83              :     Batch(BatchQueryData),
      84              : }
      85              : 
      86              : const MAX_RESPONSE_SIZE: usize = 10 * 1024 * 1024; // 10 MiB
      87              : const MAX_REQUEST_SIZE: u64 = 10 * 1024 * 1024; // 10 MiB
      88              : 
      89              : static RAW_TEXT_OUTPUT: HeaderName = HeaderName::from_static("neon-raw-text-output");
      90              : static ARRAY_MODE: HeaderName = HeaderName::from_static("neon-array-mode");
      91              : static ALLOW_POOL: HeaderName = HeaderName::from_static("neon-pool-opt-in");
      92              : static TXN_ISOLATION_LEVEL: HeaderName = HeaderName::from_static("neon-batch-isolation-level");
      93              : static TXN_READ_ONLY: HeaderName = HeaderName::from_static("neon-batch-read-only");
      94              : static TXN_DEFERRABLE: HeaderName = HeaderName::from_static("neon-batch-deferrable");
      95              : 
      96              : static HEADER_VALUE_TRUE: HeaderValue = HeaderValue::from_static("true");
      97              : 
      98            0 : fn bytes_to_pg_text<'de, D>(deserializer: D) -> Result<Vec<Option<String>>, D::Error>
      99            0 : where
     100            0 :     D: serde::de::Deserializer<'de>,
     101            0 : {
     102              :     // TODO: consider avoiding the allocation here.
     103            0 :     let json: Vec<Value> = serde::de::Deserialize::deserialize(deserializer)?;
     104            0 :     Ok(json_to_pg_text(json))
     105            0 : }
     106              : 
     107            0 : #[derive(Debug, thiserror::Error)]
     108              : pub enum ConnInfoError {
     109              :     #[error("invalid header: {0}")]
     110              :     InvalidHeader(&'static str),
     111              :     #[error("invalid connection string: {0}")]
     112              :     UrlParseError(#[from] url::ParseError),
     113              :     #[error("incorrect scheme")]
     114              :     IncorrectScheme,
     115              :     #[error("missing database name")]
     116              :     MissingDbName,
     117              :     #[error("invalid database name")]
     118              :     InvalidDbName,
     119              :     #[error("missing username")]
     120              :     MissingUsername,
     121              :     #[error("invalid username: {0}")]
     122              :     InvalidUsername(#[from] std::string::FromUtf8Error),
     123              :     #[error("missing password")]
     124              :     MissingPassword,
     125              :     #[error("missing hostname")]
     126              :     MissingHostname,
     127              :     #[error("invalid hostname: {0}")]
     128              :     InvalidEndpoint(#[from] ComputeUserInfoParseError),
     129              :     #[error("malformed endpoint")]
     130              :     MalformedEndpoint,
     131              : }
     132              : 
     133              : impl ReportableError for ConnInfoError {
     134            0 :     fn get_error_kind(&self) -> ErrorKind {
     135            0 :         ErrorKind::User
     136            0 :     }
     137              : }
     138              : 
     139              : impl UserFacingError for ConnInfoError {
     140            0 :     fn to_string_client(&self) -> String {
     141            0 :         self.to_string()
     142            0 :     }
     143              : }
     144              : 
     145            0 : fn get_conn_info(
     146            0 :     ctx: &mut RequestMonitoring,
     147            0 :     headers: &HeaderMap,
     148            0 :     tls: &TlsConfig,
     149            0 : ) -> Result<ConnInfo, ConnInfoError> {
     150            0 :     // HTTP only uses cleartext (for now and likely always)
     151            0 :     ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
     152              : 
     153            0 :     let connection_string = headers
     154            0 :         .get("Neon-Connection-String")
     155            0 :         .ok_or(ConnInfoError::InvalidHeader("Neon-Connection-String"))?
     156            0 :         .to_str()
     157            0 :         .map_err(|_| ConnInfoError::InvalidHeader("Neon-Connection-String"))?;
     158              : 
     159            0 :     let connection_url = Url::parse(connection_string)?;
     160              : 
     161            0 :     let protocol = connection_url.scheme();
     162            0 :     if protocol != "postgres" && protocol != "postgresql" {
     163            0 :         return Err(ConnInfoError::IncorrectScheme);
     164            0 :     }
     165              : 
     166            0 :     let mut url_path = connection_url
     167            0 :         .path_segments()
     168            0 :         .ok_or(ConnInfoError::MissingDbName)?;
     169              : 
     170            0 :     let dbname: DbName = url_path.next().ok_or(ConnInfoError::InvalidDbName)?.into();
     171            0 :     ctx.set_dbname(dbname.clone());
     172              : 
     173            0 :     let username = RoleName::from(urlencoding::decode(connection_url.username())?);
     174            0 :     if username.is_empty() {
     175            0 :         return Err(ConnInfoError::MissingUsername);
     176            0 :     }
     177            0 :     ctx.set_user(username.clone());
     178              : 
     179            0 :     let password = connection_url
     180            0 :         .password()
     181            0 :         .ok_or(ConnInfoError::MissingPassword)?;
     182            0 :     let password = urlencoding::decode_binary(password.as_bytes());
     183              : 
     184            0 :     let hostname = connection_url
     185            0 :         .host_str()
     186            0 :         .ok_or(ConnInfoError::MissingHostname)?;
     187              : 
     188            0 :     let endpoint =
     189            0 :         endpoint_sni(hostname, &tls.common_names)?.ok_or(ConnInfoError::MalformedEndpoint)?;
     190            0 :     ctx.set_endpoint_id(endpoint.clone());
     191            0 : 
     192            0 :     let pairs = connection_url.query_pairs();
     193            0 : 
     194            0 :     let mut options = Option::None;
     195            0 : 
     196            0 :     let mut params = StartupMessageParamsBuilder::default();
     197            0 :     params.insert("user", &username);
     198            0 :     params.insert("database", &dbname);
     199            0 :     for (key, value) in pairs {
     200            0 :         params.insert(&key, &value);
     201            0 :         if key == "options" {
     202            0 :             options = Some(NeonOptions::parse_options_raw(&value));
     203            0 :         }
     204              :     }
     205            0 :     ctx.set_db_options(params.freeze());
     206            0 : 
     207            0 :     let user_info = ComputeUserInfo {
     208            0 :         endpoint,
     209            0 :         user: username,
     210            0 :         options: options.unwrap_or_default(),
     211            0 :     };
     212            0 : 
     213            0 :     Ok(ConnInfo {
     214            0 :         user_info,
     215            0 :         dbname,
     216            0 :         password: match password {
     217            0 :             std::borrow::Cow::Borrowed(b) => b.into(),
     218            0 :             std::borrow::Cow::Owned(b) => b.into(),
     219              :         },
     220              :     })
     221            0 : }
     222              : 
     223              : // TODO: return different http error codes
     224            0 : pub async fn handle(
     225            0 :     config: &'static ProxyConfig,
     226            0 :     mut ctx: RequestMonitoring,
     227            0 :     request: Request<Incoming>,
     228            0 :     backend: Arc<PoolingBackend>,
     229            0 :     cancel: CancellationToken,
     230            0 : ) -> Result<Response<Full<Bytes>>, ApiError> {
     231            0 :     let result = handle_inner(cancel, config, &mut ctx, request, backend).await;
     232              : 
     233            0 :     let mut response = match result {
     234            0 :         Ok(r) => {
     235            0 :             ctx.set_success();
     236            0 :             r
     237              :         }
     238            0 :         Err(e @ SqlOverHttpError::Cancelled(_)) => {
     239            0 :             let error_kind = e.get_error_kind();
     240            0 :             ctx.set_error_kind(error_kind);
     241            0 : 
     242            0 :             let message = "Query cancelled, connection was terminated";
     243            0 : 
     244            0 :             tracing::info!(
     245            0 :                 kind=error_kind.to_metric_label(),
     246            0 :                 error=%e,
     247            0 :                 msg=message,
     248            0 :                 "forwarding error to user"
     249              :             );
     250              : 
     251            0 :             json_response(
     252            0 :                 StatusCode::BAD_REQUEST,
     253            0 :                 json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
     254            0 :             )?
     255              :         }
     256            0 :         Err(e) => {
     257            0 :             let error_kind = e.get_error_kind();
     258            0 :             ctx.set_error_kind(error_kind);
     259            0 : 
     260            0 :             let mut message = e.to_string_client();
     261            0 :             let db_error = match &e {
     262            0 :                 SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
     263            0 :                 | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     264            0 :                 _ => None,
     265              :             };
     266            0 :             fn get<'a, T: serde::Serialize>(
     267            0 :                 db: Option<&'a DbError>,
     268            0 :                 x: impl FnOnce(&'a DbError) -> T,
     269            0 :             ) -> Value {
     270            0 :                 db.map(x)
     271            0 :                     .and_then(|t| serde_json::to_value(t).ok())
     272            0 :                     .unwrap_or_default()
     273            0 :             }
     274              : 
     275            0 :             if let Some(db_error) = db_error {
     276            0 :                 db_error.message().clone_into(&mut message);
     277            0 :             }
     278              : 
     279            0 :             let position = db_error.and_then(|db| db.position());
     280            0 :             let (position, internal_position, internal_query) = match position {
     281            0 :                 Some(ErrorPosition::Original(position)) => (
     282            0 :                     Value::String(position.to_string()),
     283            0 :                     Value::Null,
     284            0 :                     Value::Null,
     285            0 :                 ),
     286            0 :                 Some(ErrorPosition::Internal { position, query }) => (
     287            0 :                     Value::Null,
     288            0 :                     Value::String(position.to_string()),
     289            0 :                     Value::String(query.clone()),
     290            0 :                 ),
     291            0 :                 None => (Value::Null, Value::Null, Value::Null),
     292              :             };
     293              : 
     294            0 :             let code = get(db_error, |db| db.code().code());
     295            0 :             let severity = get(db_error, |db| db.severity());
     296            0 :             let detail = get(db_error, |db| db.detail());
     297            0 :             let hint = get(db_error, |db| db.hint());
     298            0 :             let where_ = get(db_error, |db| db.where_());
     299            0 :             let table = get(db_error, |db| db.table());
     300            0 :             let column = get(db_error, |db| db.column());
     301            0 :             let schema = get(db_error, |db| db.schema());
     302            0 :             let datatype = get(db_error, |db| db.datatype());
     303            0 :             let constraint = get(db_error, |db| db.constraint());
     304            0 :             let file = get(db_error, |db| db.file());
     305            0 :             let line = get(db_error, |db| db.line().map(|l| l.to_string()));
     306            0 :             let routine = get(db_error, |db| db.routine());
     307            0 : 
     308            0 :             tracing::info!(
     309            0 :                 kind=error_kind.to_metric_label(),
     310            0 :                 error=%e,
     311            0 :                 msg=message,
     312            0 :                 "forwarding error to user"
     313              :             );
     314              : 
     315              :             // TODO: this shouldn't always be bad request.
     316            0 :             json_response(
     317            0 :                 StatusCode::BAD_REQUEST,
     318            0 :                 json!({
     319            0 :                     "message": message,
     320            0 :                     "code": code,
     321            0 :                     "detail": detail,
     322            0 :                     "hint": hint,
     323            0 :                     "position": position,
     324            0 :                     "internalPosition": internal_position,
     325            0 :                     "internalQuery": internal_query,
     326            0 :                     "severity": severity,
     327            0 :                     "where": where_,
     328            0 :                     "table": table,
     329            0 :                     "column": column,
     330            0 :                     "schema": schema,
     331            0 :                     "dataType": datatype,
     332            0 :                     "constraint": constraint,
     333            0 :                     "file": file,
     334            0 :                     "line": line,
     335            0 :                     "routine": routine,
     336            0 :                 }),
     337            0 :             )?
     338              :         }
     339              :     };
     340              : 
     341            0 :     response
     342            0 :         .headers_mut()
     343            0 :         .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
     344            0 :     Ok(response)
     345            0 : }
     346              : 
     347            0 : #[derive(Debug, thiserror::Error)]
     348              : pub enum SqlOverHttpError {
     349              :     #[error("{0}")]
     350              :     ReadPayload(#[from] ReadPayloadError),
     351              :     #[error("{0}")]
     352              :     ConnectCompute(#[from] HttpConnError),
     353              :     #[error("{0}")]
     354              :     ConnInfo(#[from] ConnInfoError),
     355              :     #[error("request is too large (max is {MAX_REQUEST_SIZE} bytes)")]
     356              :     RequestTooLarge,
     357              :     #[error("response is too large (max is {MAX_RESPONSE_SIZE} bytes)")]
     358              :     ResponseTooLarge,
     359              :     #[error("invalid isolation level")]
     360              :     InvalidIsolationLevel,
     361              :     #[error("{0}")]
     362              :     Postgres(#[from] tokio_postgres::Error),
     363              :     #[error("{0}")]
     364              :     JsonConversion(#[from] JsonConversionError),
     365              :     #[error("{0}")]
     366              :     Cancelled(SqlOverHttpCancel),
     367              : }
     368              : 
     369              : impl ReportableError for SqlOverHttpError {
     370            0 :     fn get_error_kind(&self) -> ErrorKind {
     371            0 :         match self {
     372            0 :             SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
     373            0 :             SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
     374            0 :             SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
     375            0 :             SqlOverHttpError::RequestTooLarge => ErrorKind::User,
     376            0 :             SqlOverHttpError::ResponseTooLarge => ErrorKind::User,
     377            0 :             SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
     378            0 :             SqlOverHttpError::Postgres(p) => p.get_error_kind(),
     379            0 :             SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
     380            0 :             SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
     381              :         }
     382            0 :     }
     383              : }
     384              : 
     385              : impl UserFacingError for SqlOverHttpError {
     386            0 :     fn to_string_client(&self) -> String {
     387            0 :         match self {
     388            0 :             SqlOverHttpError::ReadPayload(p) => p.to_string(),
     389            0 :             SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
     390            0 :             SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
     391            0 :             SqlOverHttpError::RequestTooLarge => self.to_string(),
     392            0 :             SqlOverHttpError::ResponseTooLarge => self.to_string(),
     393            0 :             SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
     394            0 :             SqlOverHttpError::Postgres(p) => p.to_string(),
     395            0 :             SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
     396            0 :             SqlOverHttpError::Cancelled(_) => self.to_string(),
     397              :         }
     398            0 :     }
     399              : }
     400              : 
     401            0 : #[derive(Debug, thiserror::Error)]
     402              : pub enum ReadPayloadError {
     403              :     #[error("could not read the HTTP request body: {0}")]
     404              :     Read(#[from] hyper1::Error),
     405              :     #[error("could not parse the HTTP request body: {0}")]
     406              :     Parse(#[from] serde_json::Error),
     407              : }
     408              : 
     409              : impl ReportableError for ReadPayloadError {
     410            0 :     fn get_error_kind(&self) -> ErrorKind {
     411            0 :         match self {
     412            0 :             ReadPayloadError::Read(_) => ErrorKind::ClientDisconnect,
     413            0 :             ReadPayloadError::Parse(_) => ErrorKind::User,
     414              :         }
     415            0 :     }
     416              : }
     417              : 
     418            0 : #[derive(Debug, thiserror::Error)]
     419              : pub enum SqlOverHttpCancel {
     420              :     #[error("query was cancelled")]
     421              :     Postgres,
     422              :     #[error("query was cancelled while stuck trying to connect to the database")]
     423              :     Connect,
     424              : }
     425              : 
     426              : impl ReportableError for SqlOverHttpCancel {
     427            0 :     fn get_error_kind(&self) -> ErrorKind {
     428            0 :         match self {
     429            0 :             SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
     430            0 :             SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
     431              :         }
     432            0 :     }
     433              : }
     434              : 
     435              : #[derive(Clone, Copy, Debug)]
     436              : struct HttpHeaders {
     437              :     raw_output: bool,
     438              :     default_array_mode: bool,
     439              :     txn_isolation_level: Option<IsolationLevel>,
     440              :     txn_read_only: bool,
     441              :     txn_deferrable: bool,
     442              : }
     443              : 
     444              : impl HttpHeaders {
     445            0 :     fn try_parse(headers: &hyper1::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
     446            0 :         // Determine the output options. Default behaviour is 'false'. Anything that is not
     447            0 :         // strictly 'true' assumed to be false.
     448            0 :         let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
     449            0 :         let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
     450              : 
     451              :         // isolation level, read only and deferrable
     452            0 :         let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
     453            0 :             Some(x) => Some(
     454            0 :                 map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
     455              :             ),
     456            0 :             None => None,
     457              :         };
     458              : 
     459            0 :         let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
     460            0 :         let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
     461            0 : 
     462            0 :         Ok(Self {
     463            0 :             raw_output,
     464            0 :             default_array_mode,
     465            0 :             txn_isolation_level,
     466            0 :             txn_read_only,
     467            0 :             txn_deferrable,
     468            0 :         })
     469            0 :     }
     470              : }
     471              : 
     472            0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
     473            0 :     match level.as_bytes() {
     474            0 :         b"Serializable" => Some(IsolationLevel::Serializable),
     475            0 :         b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
     476            0 :         b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
     477            0 :         b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
     478            0 :         _ => None,
     479              :     }
     480            0 : }
     481              : 
     482            0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
     483            0 :     match level {
     484            0 :         IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
     485            0 :         IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
     486            0 :         IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
     487            0 :         IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
     488            0 :         _ => None,
     489              :     }
     490            0 : }
     491              : 
     492            0 : async fn handle_inner(
     493            0 :     cancel: CancellationToken,
     494            0 :     config: &'static ProxyConfig,
     495            0 :     ctx: &mut RequestMonitoring,
     496            0 :     request: Request<Incoming>,
     497            0 :     backend: Arc<PoolingBackend>,
     498            0 : ) -> Result<Response<Full<Bytes>>, SqlOverHttpError> {
     499            0 :     let _requeset_gauge = Metrics::get().proxy.connection_requests.guard(ctx.protocol);
     500            0 :     info!(
     501              :         protocol = %ctx.protocol,
     502            0 :         "handling interactive connection from client"
     503              :     );
     504              : 
     505              :     //
     506              :     // Determine the destination and connection params
     507              :     //
     508            0 :     let headers = request.headers();
     509              : 
     510              :     // TLS config should be there.
     511            0 :     let conn_info = get_conn_info(ctx, headers, config.tls_config.as_ref().unwrap())?;
     512            0 :     info!(user = conn_info.user_info.user.as_str(), "credentials");
     513              : 
     514              :     // Allow connection pooling only if explicitly requested
     515              :     // or if we have decided that http pool is no longer opt-in
     516            0 :     let allow_pool = !config.http_config.pool_options.opt_in
     517            0 :         || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
     518              : 
     519            0 :     let parsed_headers = HttpHeaders::try_parse(headers)?;
     520              : 
     521            0 :     let request_content_length = match request.body().size_hint().upper() {
     522            0 :         Some(v) => v,
     523            0 :         None => MAX_REQUEST_SIZE + 1,
     524              :     };
     525            0 :     info!(request_content_length, "request size in bytes");
     526            0 :     Metrics::get()
     527            0 :         .proxy
     528            0 :         .http_conn_content_length_bytes
     529            0 :         .observe(HttpDirection::Request, request_content_length as f64);
     530            0 : 
     531            0 :     // we don't have a streaming request support yet so this is to prevent OOM
     532            0 :     // from a malicious user sending an extremely large request body
     533            0 :     if request_content_length > MAX_REQUEST_SIZE {
     534            0 :         return Err(SqlOverHttpError::RequestTooLarge);
     535            0 :     }
     536            0 : 
     537            0 :     let fetch_and_process_request = Box::pin(
     538            0 :         async {
     539            0 :             let body = request.into_body().collect().await?.to_bytes();
     540            0 :             info!(length = body.len(), "request payload read");
     541            0 :             let payload: Payload = serde_json::from_slice(&body)?;
     542            0 :             Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
     543            0 :         }
     544            0 :         .map_err(SqlOverHttpError::from),
     545            0 :     );
     546            0 : 
     547            0 :     let authenticate_and_connect = Box::pin(
     548            0 :         async {
     549            0 :             let keys = backend
     550            0 :                 .authenticate(ctx, &config.authentication_config, &conn_info)
     551            0 :                 .await?;
     552            0 :             let client = backend
     553            0 :                 .connect_to_compute(ctx, conn_info, keys, !allow_pool)
     554            0 :                 .await?;
     555              :             // not strictly necessary to mark success here,
     556              :             // but it's just insurance for if we forget it somewhere else
     557            0 :             ctx.latency_timer.success();
     558            0 :             Ok::<_, HttpConnError>(client)
     559            0 :         }
     560            0 :         .map_err(SqlOverHttpError::from),
     561            0 :     );
     562              : 
     563            0 :     let (payload, mut client) = match run_until_cancelled(
     564            0 :         // Run both operations in parallel
     565            0 :         try_join(
     566            0 :             pin!(fetch_and_process_request),
     567            0 :             pin!(authenticate_and_connect),
     568            0 :         ),
     569            0 :         &cancel,
     570            0 :     )
     571            0 :     .await
     572              :     {
     573            0 :         Some(result) => result?,
     574            0 :         None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
     575              :     };
     576              : 
     577            0 :     let mut response = Response::builder()
     578            0 :         .status(StatusCode::OK)
     579            0 :         .header(header::CONTENT_TYPE, "application/json");
     580              : 
     581              :     //
     582              :     // Now execute the query and return the result
     583              :     //
     584            0 :     let result = match payload {
     585            0 :         Payload::Single(stmt) => stmt.process(cancel, &mut client, parsed_headers).await?,
     586            0 :         Payload::Batch(statements) => {
     587            0 :             if parsed_headers.txn_read_only {
     588            0 :                 response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
     589            0 :             }
     590            0 :             if parsed_headers.txn_deferrable {
     591            0 :                 response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
     592            0 :             }
     593            0 :             if let Some(txn_isolation_level) = parsed_headers
     594            0 :                 .txn_isolation_level
     595            0 :                 .and_then(map_isolation_level_to_headers)
     596            0 :             {
     597            0 :                 response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
     598            0 :             }
     599              : 
     600            0 :             statements
     601            0 :                 .process(cancel, &mut client, parsed_headers)
     602            0 :                 .await?
     603              :         }
     604              :     };
     605              : 
     606            0 :     let metrics = client.metrics();
     607            0 : 
     608            0 :     // how could this possibly fail
     609            0 :     let body = serde_json::to_string(&result).expect("json serialization should not fail");
     610            0 :     let len = body.len();
     611            0 :     let response = response
     612            0 :         .body(Full::new(Bytes::from(body)))
     613            0 :         // only fails if invalid status code or invalid header/values are given.
     614            0 :         // these are not user configurable so it cannot fail dynamically
     615            0 :         .expect("building response payload should not fail");
     616            0 : 
     617            0 :     // count the egress bytes - we miss the TLS and header overhead but oh well...
     618            0 :     // moving this later in the stack is going to be a lot of effort and ehhhh
     619            0 :     metrics.record_egress(len as u64);
     620            0 :     Metrics::get()
     621            0 :         .proxy
     622            0 :         .http_conn_content_length_bytes
     623            0 :         .observe(HttpDirection::Response, len as f64);
     624            0 : 
     625            0 :     Ok(response)
     626            0 : }
     627              : 
     628              : impl QueryData {
     629            0 :     async fn process(
     630            0 :         self,
     631            0 :         cancel: CancellationToken,
     632            0 :         client: &mut Client<tokio_postgres::Client>,
     633            0 :         parsed_headers: HttpHeaders,
     634            0 :     ) -> Result<Value, SqlOverHttpError> {
     635            0 :         let (inner, mut discard) = client.inner();
     636            0 :         let cancel_token = inner.cancel_token();
     637              : 
     638            0 :         let res = match select(
     639            0 :             pin!(query_to_json(&*inner, self, &mut 0, parsed_headers)),
     640            0 :             pin!(cancel.cancelled()),
     641            0 :         )
     642            0 :         .await
     643              :         {
     644              :             // The query successfully completed.
     645            0 :             Either::Left((Ok((status, results)), __not_yet_cancelled)) => {
     646            0 :                 discard.check_idle(status);
     647            0 :                 Ok(results)
     648              :             }
     649              :             // The query failed with an error
     650            0 :             Either::Left((Err(e), __not_yet_cancelled)) => {
     651            0 :                 discard.discard();
     652            0 :                 return Err(e);
     653              :             }
     654              :             // The query was cancelled.
     655            0 :             Either::Right((_cancelled, query)) => {
     656            0 :                 tracing::info!("cancelling query");
     657            0 :                 if let Err(err) = cancel_token.cancel_query(NoTls).await {
     658            0 :                     tracing::error!(?err, "could not cancel query");
     659            0 :                 }
     660              :                 // wait for the query cancellation
     661            0 :                 match time::timeout(time::Duration::from_millis(100), query).await {
     662              :                     // query successed before it was cancelled.
     663            0 :                     Ok(Ok((status, results))) => {
     664            0 :                         discard.check_idle(status);
     665            0 :                         Ok(results)
     666              :                     }
     667              :                     // query failed or was cancelled.
     668            0 :                     Ok(Err(error)) => {
     669            0 :                         let db_error = match &error {
     670            0 :                             SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
     671            0 :                             | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     672            0 :                             _ => None,
     673              :                         };
     674              : 
     675              :                         // if errored for some other reason, it might not be safe to return
     676            0 :                         if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
     677            0 :                             discard.discard();
     678            0 :                         }
     679              : 
     680            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     681              :                     }
     682            0 :                     Err(_timeout) => {
     683            0 :                         discard.discard();
     684            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     685              :                     }
     686              :                 }
     687              :             }
     688              :         };
     689            0 :         res
     690            0 :     }
     691              : }
     692              : 
     693              : impl BatchQueryData {
     694            0 :     async fn process(
     695            0 :         self,
     696            0 :         cancel: CancellationToken,
     697            0 :         client: &mut Client<tokio_postgres::Client>,
     698            0 :         parsed_headers: HttpHeaders,
     699            0 :     ) -> Result<Value, SqlOverHttpError> {
     700            0 :         info!("starting transaction");
     701            0 :         let (inner, mut discard) = client.inner();
     702            0 :         let cancel_token = inner.cancel_token();
     703            0 :         let mut builder = inner.build_transaction();
     704            0 :         if let Some(isolation_level) = parsed_headers.txn_isolation_level {
     705            0 :             builder = builder.isolation_level(isolation_level);
     706            0 :         }
     707            0 :         if parsed_headers.txn_read_only {
     708            0 :             builder = builder.read_only(true);
     709            0 :         }
     710            0 :         if parsed_headers.txn_deferrable {
     711            0 :             builder = builder.deferrable(true);
     712            0 :         }
     713              : 
     714            0 :         let transaction = builder.start().await.map_err(|e| {
     715            0 :             // if we cannot start a transaction, we should return immediately
     716            0 :             // and not return to the pool. connection is clearly broken
     717            0 :             discard.discard();
     718            0 :             e
     719            0 :         })?;
     720              : 
     721            0 :         let results =
     722            0 :             match query_batch(cancel.child_token(), &transaction, self, parsed_headers).await {
     723            0 :                 Ok(results) => {
     724            0 :                     info!("commit");
     725            0 :                     let status = transaction.commit().await.map_err(|e| {
     726            0 :                         // if we cannot commit - for now don't return connection to pool
     727            0 :                         // TODO: get a query status from the error
     728            0 :                         discard.discard();
     729            0 :                         e
     730            0 :                     })?;
     731            0 :                     discard.check_idle(status);
     732            0 :                     results
     733              :                 }
     734              :                 Err(SqlOverHttpError::Cancelled(_)) => {
     735            0 :                     if let Err(err) = cancel_token.cancel_query(NoTls).await {
     736            0 :                         tracing::error!(?err, "could not cancel query");
     737            0 :                     }
     738              :                     // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
     739            0 :                     discard.discard();
     740            0 : 
     741            0 :                     return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
     742              :                 }
     743            0 :                 Err(err) => {
     744            0 :                     info!("rollback");
     745            0 :                     let status = transaction.rollback().await.map_err(|e| {
     746            0 :                         // if we cannot rollback - for now don't return connection to pool
     747            0 :                         // TODO: get a query status from the error
     748            0 :                         discard.discard();
     749            0 :                         e
     750            0 :                     })?;
     751            0 :                     discard.check_idle(status);
     752            0 :                     return Err(err);
     753              :                 }
     754              :             };
     755              : 
     756            0 :         Ok(json!({ "results": results }))
     757            0 :     }
     758              : }
     759              : 
     760            0 : async fn query_batch(
     761            0 :     cancel: CancellationToken,
     762            0 :     transaction: &Transaction<'_>,
     763            0 :     queries: BatchQueryData,
     764            0 :     parsed_headers: HttpHeaders,
     765            0 : ) -> Result<Vec<Value>, SqlOverHttpError> {
     766            0 :     let mut results = Vec::with_capacity(queries.queries.len());
     767            0 :     let mut current_size = 0;
     768            0 :     for stmt in queries.queries {
     769            0 :         let query = pin!(query_to_json(
     770            0 :             transaction,
     771            0 :             stmt,
     772            0 :             &mut current_size,
     773            0 :             parsed_headers,
     774            0 :         ));
     775            0 :         let cancelled = pin!(cancel.cancelled());
     776            0 :         let res = select(query, cancelled).await;
     777            0 :         match res {
     778              :             // TODO: maybe we should check that the transaction bit is set here
     779            0 :             Either::Left((Ok((_, values)), _cancelled)) => {
     780            0 :                 results.push(values);
     781            0 :             }
     782            0 :             Either::Left((Err(e), _cancelled)) => {
     783            0 :                 return Err(e);
     784              :             }
     785            0 :             Either::Right((_cancelled, _)) => {
     786            0 :                 return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
     787              :             }
     788              :         }
     789              :     }
     790            0 :     Ok(results)
     791            0 : }
     792              : 
     793            0 : async fn query_to_json<T: GenericClient>(
     794            0 :     client: &T,
     795            0 :     data: QueryData,
     796            0 :     current_size: &mut usize,
     797            0 :     parsed_headers: HttpHeaders,
     798            0 : ) -> Result<(ReadyForQueryStatus, Value), SqlOverHttpError> {
     799            0 :     info!("executing query");
     800            0 :     let query_params = data.params;
     801            0 :     let mut row_stream = std::pin::pin!(client.query_raw_txt(&data.query, query_params).await?);
     802            0 :     info!("finished executing query");
     803              : 
     804              :     // Manually drain the stream into a vector to leave row_stream hanging
     805              :     // around to get a command tag. Also check that the response is not too
     806              :     // big.
     807            0 :     let mut rows: Vec<tokio_postgres::Row> = Vec::new();
     808            0 :     while let Some(row) = row_stream.next().await {
     809            0 :         let row = row?;
     810            0 :         *current_size += row.body_len();
     811            0 :         rows.push(row);
     812            0 :         // we don't have a streaming response support yet so this is to prevent OOM
     813            0 :         // from a malicious query (eg a cross join)
     814            0 :         if *current_size > MAX_RESPONSE_SIZE {
     815            0 :             return Err(SqlOverHttpError::ResponseTooLarge);
     816            0 :         }
     817              :     }
     818              : 
     819            0 :     let ready = row_stream.ready_status();
     820            0 : 
     821            0 :     // grab the command tag and number of rows affected
     822            0 :     let command_tag = row_stream.command_tag().unwrap_or_default();
     823            0 :     let mut command_tag_split = command_tag.split(' ');
     824            0 :     let command_tag_name = command_tag_split.next().unwrap_or_default();
     825            0 :     let command_tag_count = if command_tag_name == "INSERT" {
     826              :         // INSERT returns OID first and then number of rows
     827            0 :         command_tag_split.nth(1)
     828              :     } else {
     829              :         // other commands return number of rows (if any)
     830            0 :         command_tag_split.next()
     831              :     }
     832            0 :     .and_then(|s| s.parse::<i64>().ok());
     833            0 : 
     834            0 :     info!(
     835            0 :         rows = rows.len(),
     836            0 :         ?ready,
     837            0 :         command_tag,
     838            0 :         "finished reading rows"
     839              :     );
     840              : 
     841            0 :     let mut fields = vec![];
     842            0 :     let mut columns = vec![];
     843              : 
     844            0 :     for c in row_stream.columns() {
     845            0 :         fields.push(json!({
     846            0 :             "name": Value::String(c.name().to_owned()),
     847            0 :             "dataTypeID": Value::Number(c.type_().oid().into()),
     848            0 :             "tableID": c.table_oid(),
     849            0 :             "columnID": c.column_id(),
     850            0 :             "dataTypeSize": c.type_size(),
     851            0 :             "dataTypeModifier": c.type_modifier(),
     852            0 :             "format": "text",
     853            0 :         }));
     854            0 :         columns.push(client.get_type(c.type_oid()).await?);
     855              :     }
     856              : 
     857            0 :     let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
     858              : 
     859              :     // convert rows to JSON
     860            0 :     let rows = rows
     861            0 :         .iter()
     862            0 :         .map(|row| pg_text_row_to_json(row, &columns, parsed_headers.raw_output, array_mode))
     863            0 :         .collect::<Result<Vec<_>, _>>()?;
     864              : 
     865              :     // resulting JSON format is based on the format of node-postgres result
     866            0 :     Ok((
     867            0 :         ready,
     868            0 :         json!({
     869            0 :             "command": command_tag_name,
     870            0 :             "rowCount": command_tag_count,
     871            0 :             "rows": rows,
     872            0 :             "fields": fields,
     873            0 :             "rowAsArray": array_mode,
     874            0 :         }),
     875            0 :     ))
     876            0 : }
        

Generated by: LCOV version 2.1-beta