LCOV - code coverage report
Current view: top level - proxy/src/serverless - sql_over_http.rs (source / functions) Coverage Total Hit
Test: 75747cdbffeb0b6d2a2a311584368de68cd9aadc.info Lines: 0.0 % 554 0
Test Date: 2024-06-24 06:52:57 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              : 
     206            0 :     let user_info = ComputeUserInfo {
     207            0 :         endpoint,
     208            0 :         user: username,
     209            0 :         options: options.unwrap_or_default(),
     210            0 :     };
     211            0 : 
     212            0 :     Ok(ConnInfo {
     213            0 :         user_info,
     214            0 :         dbname,
     215            0 :         password: match password {
     216            0 :             std::borrow::Cow::Borrowed(b) => b.into(),
     217            0 :             std::borrow::Cow::Owned(b) => b.into(),
     218              :         },
     219              :     })
     220            0 : }
     221              : 
     222              : // TODO: return different http error codes
     223            0 : pub async fn handle(
     224            0 :     config: &'static ProxyConfig,
     225            0 :     mut ctx: RequestMonitoring,
     226            0 :     request: Request<Incoming>,
     227            0 :     backend: Arc<PoolingBackend>,
     228            0 :     cancel: CancellationToken,
     229            0 : ) -> Result<Response<Full<Bytes>>, ApiError> {
     230            0 :     let result = handle_inner(cancel, config, &mut ctx, request, backend).await;
     231              : 
     232            0 :     let mut response = match result {
     233            0 :         Ok(r) => {
     234            0 :             ctx.set_success();
     235            0 :             r
     236              :         }
     237            0 :         Err(e @ SqlOverHttpError::Cancelled(_)) => {
     238            0 :             let error_kind = e.get_error_kind();
     239            0 :             ctx.set_error_kind(error_kind);
     240            0 : 
     241            0 :             let message = "Query cancelled, connection was terminated";
     242            0 : 
     243            0 :             tracing::info!(
     244            0 :                 kind=error_kind.to_metric_label(),
     245            0 :                 error=%e,
     246            0 :                 msg=message,
     247            0 :                 "forwarding error to user"
     248              :             );
     249              : 
     250            0 :             json_response(
     251            0 :                 StatusCode::BAD_REQUEST,
     252            0 :                 json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
     253            0 :             )?
     254              :         }
     255            0 :         Err(e) => {
     256            0 :             let error_kind = e.get_error_kind();
     257            0 :             ctx.set_error_kind(error_kind);
     258            0 : 
     259            0 :             let mut message = e.to_string_client();
     260            0 :             let db_error = match &e {
     261            0 :                 SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
     262            0 :                 | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     263            0 :                 _ => None,
     264              :             };
     265            0 :             fn get<'a, T: serde::Serialize>(
     266            0 :                 db: Option<&'a DbError>,
     267            0 :                 x: impl FnOnce(&'a DbError) -> T,
     268            0 :             ) -> Value {
     269            0 :                 db.map(x)
     270            0 :                     .and_then(|t| serde_json::to_value(t).ok())
     271            0 :                     .unwrap_or_default()
     272            0 :             }
     273              : 
     274            0 :             if let Some(db_error) = db_error {
     275            0 :                 db_error.message().clone_into(&mut message);
     276            0 :             }
     277              : 
     278            0 :             let position = db_error.and_then(|db| db.position());
     279            0 :             let (position, internal_position, internal_query) = match position {
     280            0 :                 Some(ErrorPosition::Original(position)) => (
     281            0 :                     Value::String(position.to_string()),
     282            0 :                     Value::Null,
     283            0 :                     Value::Null,
     284            0 :                 ),
     285            0 :                 Some(ErrorPosition::Internal { position, query }) => (
     286            0 :                     Value::Null,
     287            0 :                     Value::String(position.to_string()),
     288            0 :                     Value::String(query.clone()),
     289            0 :                 ),
     290            0 :                 None => (Value::Null, Value::Null, Value::Null),
     291              :             };
     292              : 
     293            0 :             let code = get(db_error, |db| db.code().code());
     294            0 :             let severity = get(db_error, |db| db.severity());
     295            0 :             let detail = get(db_error, |db| db.detail());
     296            0 :             let hint = get(db_error, |db| db.hint());
     297            0 :             let where_ = get(db_error, |db| db.where_());
     298            0 :             let table = get(db_error, |db| db.table());
     299            0 :             let column = get(db_error, |db| db.column());
     300            0 :             let schema = get(db_error, |db| db.schema());
     301            0 :             let datatype = get(db_error, |db| db.datatype());
     302            0 :             let constraint = get(db_error, |db| db.constraint());
     303            0 :             let file = get(db_error, |db| db.file());
     304            0 :             let line = get(db_error, |db| db.line().map(|l| l.to_string()));
     305            0 :             let routine = get(db_error, |db| db.routine());
     306            0 : 
     307            0 :             tracing::info!(
     308            0 :                 kind=error_kind.to_metric_label(),
     309            0 :                 error=%e,
     310            0 :                 msg=message,
     311            0 :                 "forwarding error to user"
     312              :             );
     313              : 
     314              :             // TODO: this shouldn't always be bad request.
     315            0 :             json_response(
     316            0 :                 StatusCode::BAD_REQUEST,
     317            0 :                 json!({
     318            0 :                     "message": message,
     319            0 :                     "code": code,
     320            0 :                     "detail": detail,
     321            0 :                     "hint": hint,
     322            0 :                     "position": position,
     323            0 :                     "internalPosition": internal_position,
     324            0 :                     "internalQuery": internal_query,
     325            0 :                     "severity": severity,
     326            0 :                     "where": where_,
     327            0 :                     "table": table,
     328            0 :                     "column": column,
     329            0 :                     "schema": schema,
     330            0 :                     "dataType": datatype,
     331            0 :                     "constraint": constraint,
     332            0 :                     "file": file,
     333            0 :                     "line": line,
     334            0 :                     "routine": routine,
     335            0 :                 }),
     336            0 :             )?
     337              :         }
     338              :     };
     339              : 
     340            0 :     response
     341            0 :         .headers_mut()
     342            0 :         .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
     343            0 :     Ok(response)
     344            0 : }
     345              : 
     346            0 : #[derive(Debug, thiserror::Error)]
     347              : pub enum SqlOverHttpError {
     348              :     #[error("{0}")]
     349              :     ReadPayload(#[from] ReadPayloadError),
     350              :     #[error("{0}")]
     351              :     ConnectCompute(#[from] HttpConnError),
     352              :     #[error("{0}")]
     353              :     ConnInfo(#[from] ConnInfoError),
     354              :     #[error("request is too large (max is {MAX_REQUEST_SIZE} bytes)")]
     355              :     RequestTooLarge,
     356              :     #[error("response is too large (max is {MAX_RESPONSE_SIZE} bytes)")]
     357              :     ResponseTooLarge,
     358              :     #[error("invalid isolation level")]
     359              :     InvalidIsolationLevel,
     360              :     #[error("{0}")]
     361              :     Postgres(#[from] tokio_postgres::Error),
     362              :     #[error("{0}")]
     363              :     JsonConversion(#[from] JsonConversionError),
     364              :     #[error("{0}")]
     365              :     Cancelled(SqlOverHttpCancel),
     366              : }
     367              : 
     368              : impl ReportableError for SqlOverHttpError {
     369            0 :     fn get_error_kind(&self) -> ErrorKind {
     370            0 :         match self {
     371            0 :             SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
     372            0 :             SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
     373            0 :             SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
     374            0 :             SqlOverHttpError::RequestTooLarge => ErrorKind::User,
     375            0 :             SqlOverHttpError::ResponseTooLarge => ErrorKind::User,
     376            0 :             SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
     377            0 :             SqlOverHttpError::Postgres(p) => p.get_error_kind(),
     378            0 :             SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
     379            0 :             SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
     380              :         }
     381            0 :     }
     382              : }
     383              : 
     384              : impl UserFacingError for SqlOverHttpError {
     385            0 :     fn to_string_client(&self) -> String {
     386            0 :         match self {
     387            0 :             SqlOverHttpError::ReadPayload(p) => p.to_string(),
     388            0 :             SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
     389            0 :             SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
     390            0 :             SqlOverHttpError::RequestTooLarge => self.to_string(),
     391            0 :             SqlOverHttpError::ResponseTooLarge => self.to_string(),
     392            0 :             SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
     393            0 :             SqlOverHttpError::Postgres(p) => p.to_string(),
     394            0 :             SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
     395            0 :             SqlOverHttpError::Cancelled(_) => self.to_string(),
     396              :         }
     397            0 :     }
     398              : }
     399              : 
     400            0 : #[derive(Debug, thiserror::Error)]
     401              : pub enum ReadPayloadError {
     402              :     #[error("could not read the HTTP request body: {0}")]
     403              :     Read(#[from] hyper1::Error),
     404              :     #[error("could not parse the HTTP request body: {0}")]
     405              :     Parse(#[from] serde_json::Error),
     406              : }
     407              : 
     408              : impl ReportableError for ReadPayloadError {
     409            0 :     fn get_error_kind(&self) -> ErrorKind {
     410            0 :         match self {
     411            0 :             ReadPayloadError::Read(_) => ErrorKind::ClientDisconnect,
     412            0 :             ReadPayloadError::Parse(_) => ErrorKind::User,
     413              :         }
     414            0 :     }
     415              : }
     416              : 
     417            0 : #[derive(Debug, thiserror::Error)]
     418              : pub enum SqlOverHttpCancel {
     419              :     #[error("query was cancelled")]
     420              :     Postgres,
     421              :     #[error("query was cancelled while stuck trying to connect to the database")]
     422              :     Connect,
     423              : }
     424              : 
     425              : impl ReportableError for SqlOverHttpCancel {
     426            0 :     fn get_error_kind(&self) -> ErrorKind {
     427            0 :         match self {
     428            0 :             SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
     429            0 :             SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
     430              :         }
     431            0 :     }
     432              : }
     433              : 
     434              : #[derive(Clone, Copy, Debug)]
     435              : struct HttpHeaders {
     436              :     raw_output: bool,
     437              :     default_array_mode: bool,
     438              :     txn_isolation_level: Option<IsolationLevel>,
     439              :     txn_read_only: bool,
     440              :     txn_deferrable: bool,
     441              : }
     442              : 
     443              : impl HttpHeaders {
     444            0 :     fn try_parse(headers: &hyper1::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
     445            0 :         // Determine the output options. Default behaviour is 'false'. Anything that is not
     446            0 :         // strictly 'true' assumed to be false.
     447            0 :         let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
     448            0 :         let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
     449              : 
     450              :         // isolation level, read only and deferrable
     451            0 :         let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
     452            0 :             Some(x) => Some(
     453            0 :                 map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
     454              :             ),
     455            0 :             None => None,
     456              :         };
     457              : 
     458            0 :         let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
     459            0 :         let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
     460            0 : 
     461            0 :         Ok(Self {
     462            0 :             raw_output,
     463            0 :             default_array_mode,
     464            0 :             txn_isolation_level,
     465            0 :             txn_read_only,
     466            0 :             txn_deferrable,
     467            0 :         })
     468            0 :     }
     469              : }
     470              : 
     471            0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
     472            0 :     match level.as_bytes() {
     473            0 :         b"Serializable" => Some(IsolationLevel::Serializable),
     474            0 :         b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
     475            0 :         b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
     476            0 :         b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
     477            0 :         _ => None,
     478              :     }
     479            0 : }
     480              : 
     481            0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
     482            0 :     match level {
     483            0 :         IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
     484            0 :         IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
     485            0 :         IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
     486            0 :         IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
     487            0 :         _ => None,
     488              :     }
     489            0 : }
     490              : 
     491            0 : async fn handle_inner(
     492            0 :     cancel: CancellationToken,
     493            0 :     config: &'static ProxyConfig,
     494            0 :     ctx: &mut RequestMonitoring,
     495            0 :     request: Request<Incoming>,
     496            0 :     backend: Arc<PoolingBackend>,
     497            0 : ) -> Result<Response<Full<Bytes>>, SqlOverHttpError> {
     498            0 :     let _requeset_gauge = Metrics::get().proxy.connection_requests.guard(ctx.protocol);
     499            0 :     info!(
     500              :         protocol = %ctx.protocol,
     501            0 :         "handling interactive connection from client"
     502              :     );
     503              : 
     504              :     //
     505              :     // Determine the destination and connection params
     506              :     //
     507            0 :     let headers = request.headers();
     508              : 
     509              :     // TLS config should be there.
     510            0 :     let conn_info = get_conn_info(ctx, headers, config.tls_config.as_ref().unwrap())?;
     511            0 :     info!(user = conn_info.user_info.user.as_str(), "credentials");
     512              : 
     513              :     // Allow connection pooling only if explicitly requested
     514              :     // or if we have decided that http pool is no longer opt-in
     515            0 :     let allow_pool = !config.http_config.pool_options.opt_in
     516            0 :         || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
     517              : 
     518            0 :     let parsed_headers = HttpHeaders::try_parse(headers)?;
     519              : 
     520            0 :     let request_content_length = match request.body().size_hint().upper() {
     521            0 :         Some(v) => v,
     522            0 :         None => MAX_REQUEST_SIZE + 1,
     523              :     };
     524            0 :     info!(request_content_length, "request size in bytes");
     525            0 :     Metrics::get()
     526            0 :         .proxy
     527            0 :         .http_conn_content_length_bytes
     528            0 :         .observe(HttpDirection::Request, request_content_length as f64);
     529            0 : 
     530            0 :     // we don't have a streaming request support yet so this is to prevent OOM
     531            0 :     // from a malicious user sending an extremely large request body
     532            0 :     if request_content_length > MAX_REQUEST_SIZE {
     533            0 :         return Err(SqlOverHttpError::RequestTooLarge);
     534            0 :     }
     535            0 : 
     536            0 :     let fetch_and_process_request = Box::pin(
     537            0 :         async {
     538            0 :             let body = request.into_body().collect().await?.to_bytes();
     539            0 :             info!(length = body.len(), "request payload read");
     540            0 :             let payload: Payload = serde_json::from_slice(&body)?;
     541            0 :             Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
     542            0 :         }
     543            0 :         .map_err(SqlOverHttpError::from),
     544            0 :     );
     545            0 : 
     546            0 :     let authenticate_and_connect = Box::pin(
     547            0 :         async {
     548            0 :             let keys = backend
     549            0 :                 .authenticate(ctx, &config.authentication_config, &conn_info)
     550            0 :                 .await?;
     551            0 :             let client = backend
     552            0 :                 .connect_to_compute(ctx, conn_info, keys, !allow_pool)
     553            0 :                 .await?;
     554              :             // not strictly necessary to mark success here,
     555              :             // but it's just insurance for if we forget it somewhere else
     556            0 :             ctx.latency_timer.success();
     557            0 :             Ok::<_, HttpConnError>(client)
     558            0 :         }
     559            0 :         .map_err(SqlOverHttpError::from),
     560            0 :     );
     561              : 
     562            0 :     let (payload, mut client) = match run_until_cancelled(
     563            0 :         // Run both operations in parallel
     564            0 :         try_join(
     565            0 :             pin!(fetch_and_process_request),
     566            0 :             pin!(authenticate_and_connect),
     567            0 :         ),
     568            0 :         &cancel,
     569            0 :     )
     570            0 :     .await
     571              :     {
     572            0 :         Some(result) => result?,
     573            0 :         None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
     574              :     };
     575              : 
     576            0 :     let mut response = Response::builder()
     577            0 :         .status(StatusCode::OK)
     578            0 :         .header(header::CONTENT_TYPE, "application/json");
     579              : 
     580              :     //
     581              :     // Now execute the query and return the result
     582              :     //
     583            0 :     let result = match payload {
     584            0 :         Payload::Single(stmt) => stmt.process(cancel, &mut client, parsed_headers).await?,
     585            0 :         Payload::Batch(statements) => {
     586            0 :             if parsed_headers.txn_read_only {
     587            0 :                 response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
     588            0 :             }
     589            0 :             if parsed_headers.txn_deferrable {
     590            0 :                 response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
     591            0 :             }
     592            0 :             if let Some(txn_isolation_level) = parsed_headers
     593            0 :                 .txn_isolation_level
     594            0 :                 .and_then(map_isolation_level_to_headers)
     595            0 :             {
     596            0 :                 response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
     597            0 :             }
     598              : 
     599            0 :             statements
     600            0 :                 .process(cancel, &mut client, parsed_headers)
     601            0 :                 .await?
     602              :         }
     603              :     };
     604              : 
     605            0 :     let metrics = client.metrics();
     606            0 : 
     607            0 :     // how could this possibly fail
     608            0 :     let body = serde_json::to_string(&result).expect("json serialization should not fail");
     609            0 :     let len = body.len();
     610            0 :     let response = response
     611            0 :         .body(Full::new(Bytes::from(body)))
     612            0 :         // only fails if invalid status code or invalid header/values are given.
     613            0 :         // these are not user configurable so it cannot fail dynamically
     614            0 :         .expect("building response payload should not fail");
     615            0 : 
     616            0 :     // count the egress bytes - we miss the TLS and header overhead but oh well...
     617            0 :     // moving this later in the stack is going to be a lot of effort and ehhhh
     618            0 :     metrics.record_egress(len as u64);
     619            0 :     Metrics::get()
     620            0 :         .proxy
     621            0 :         .http_conn_content_length_bytes
     622            0 :         .observe(HttpDirection::Response, len as f64);
     623            0 : 
     624            0 :     Ok(response)
     625            0 : }
     626              : 
     627              : impl QueryData {
     628            0 :     async fn process(
     629            0 :         self,
     630            0 :         cancel: CancellationToken,
     631            0 :         client: &mut Client<tokio_postgres::Client>,
     632            0 :         parsed_headers: HttpHeaders,
     633            0 :     ) -> Result<Value, SqlOverHttpError> {
     634            0 :         let (inner, mut discard) = client.inner();
     635            0 :         let cancel_token = inner.cancel_token();
     636              : 
     637            0 :         let res = match select(
     638            0 :             pin!(query_to_json(&*inner, self, &mut 0, parsed_headers)),
     639            0 :             pin!(cancel.cancelled()),
     640            0 :         )
     641            0 :         .await
     642              :         {
     643              :             // The query successfully completed.
     644            0 :             Either::Left((Ok((status, results)), __not_yet_cancelled)) => {
     645            0 :                 discard.check_idle(status);
     646            0 :                 Ok(results)
     647              :             }
     648              :             // The query failed with an error
     649            0 :             Either::Left((Err(e), __not_yet_cancelled)) => {
     650            0 :                 discard.discard();
     651            0 :                 return Err(e);
     652              :             }
     653              :             // The query was cancelled.
     654            0 :             Either::Right((_cancelled, query)) => {
     655            0 :                 tracing::info!("cancelling query");
     656            0 :                 if let Err(err) = cancel_token.cancel_query(NoTls).await {
     657            0 :                     tracing::error!(?err, "could not cancel query");
     658            0 :                 }
     659              :                 // wait for the query cancellation
     660            0 :                 match time::timeout(time::Duration::from_millis(100), query).await {
     661              :                     // query successed before it was cancelled.
     662            0 :                     Ok(Ok((status, results))) => {
     663            0 :                         discard.check_idle(status);
     664            0 :                         Ok(results)
     665              :                     }
     666              :                     // query failed or was cancelled.
     667            0 :                     Ok(Err(error)) => {
     668            0 :                         let db_error = match &error {
     669            0 :                             SqlOverHttpError::ConnectCompute(HttpConnError::ConnectionError(e))
     670            0 :                             | SqlOverHttpError::Postgres(e) => e.as_db_error(),
     671            0 :                             _ => None,
     672              :                         };
     673              : 
     674              :                         // if errored for some other reason, it might not be safe to return
     675            0 :                         if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
     676            0 :                             discard.discard();
     677            0 :                         }
     678              : 
     679            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     680              :                     }
     681            0 :                     Err(_timeout) => {
     682            0 :                         discard.discard();
     683            0 :                         Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
     684              :                     }
     685              :                 }
     686              :             }
     687              :         };
     688            0 :         res
     689            0 :     }
     690              : }
     691              : 
     692              : impl BatchQueryData {
     693            0 :     async fn process(
     694            0 :         self,
     695            0 :         cancel: CancellationToken,
     696            0 :         client: &mut Client<tokio_postgres::Client>,
     697            0 :         parsed_headers: HttpHeaders,
     698            0 :     ) -> Result<Value, SqlOverHttpError> {
     699            0 :         info!("starting transaction");
     700            0 :         let (inner, mut discard) = client.inner();
     701            0 :         let cancel_token = inner.cancel_token();
     702            0 :         let mut builder = inner.build_transaction();
     703            0 :         if let Some(isolation_level) = parsed_headers.txn_isolation_level {
     704            0 :             builder = builder.isolation_level(isolation_level);
     705            0 :         }
     706            0 :         if parsed_headers.txn_read_only {
     707            0 :             builder = builder.read_only(true);
     708            0 :         }
     709            0 :         if parsed_headers.txn_deferrable {
     710            0 :             builder = builder.deferrable(true);
     711            0 :         }
     712              : 
     713            0 :         let transaction = builder.start().await.map_err(|e| {
     714            0 :             // if we cannot start a transaction, we should return immediately
     715            0 :             // and not return to the pool. connection is clearly broken
     716            0 :             discard.discard();
     717            0 :             e
     718            0 :         })?;
     719              : 
     720            0 :         let results =
     721            0 :             match query_batch(cancel.child_token(), &transaction, self, parsed_headers).await {
     722            0 :                 Ok(results) => {
     723            0 :                     info!("commit");
     724            0 :                     let status = transaction.commit().await.map_err(|e| {
     725            0 :                         // if we cannot commit - for now don't return connection to pool
     726            0 :                         // TODO: get a query status from the error
     727            0 :                         discard.discard();
     728            0 :                         e
     729            0 :                     })?;
     730            0 :                     discard.check_idle(status);
     731            0 :                     results
     732              :                 }
     733              :                 Err(SqlOverHttpError::Cancelled(_)) => {
     734            0 :                     if let Err(err) = cancel_token.cancel_query(NoTls).await {
     735            0 :                         tracing::error!(?err, "could not cancel query");
     736            0 :                     }
     737              :                     // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
     738            0 :                     discard.discard();
     739            0 : 
     740            0 :                     return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
     741              :                 }
     742            0 :                 Err(err) => {
     743            0 :                     info!("rollback");
     744            0 :                     let status = transaction.rollback().await.map_err(|e| {
     745            0 :                         // if we cannot rollback - for now don't return connection to pool
     746            0 :                         // TODO: get a query status from the error
     747            0 :                         discard.discard();
     748            0 :                         e
     749            0 :                     })?;
     750            0 :                     discard.check_idle(status);
     751            0 :                     return Err(err);
     752              :                 }
     753              :             };
     754              : 
     755            0 :         Ok(json!({ "results": results }))
     756            0 :     }
     757              : }
     758              : 
     759            0 : async fn query_batch(
     760            0 :     cancel: CancellationToken,
     761            0 :     transaction: &Transaction<'_>,
     762            0 :     queries: BatchQueryData,
     763            0 :     parsed_headers: HttpHeaders,
     764            0 : ) -> Result<Vec<Value>, SqlOverHttpError> {
     765            0 :     let mut results = Vec::with_capacity(queries.queries.len());
     766            0 :     let mut current_size = 0;
     767            0 :     for stmt in queries.queries {
     768            0 :         let query = pin!(query_to_json(
     769            0 :             transaction,
     770            0 :             stmt,
     771            0 :             &mut current_size,
     772            0 :             parsed_headers,
     773            0 :         ));
     774            0 :         let cancelled = pin!(cancel.cancelled());
     775            0 :         let res = select(query, cancelled).await;
     776            0 :         match res {
     777              :             // TODO: maybe we should check that the transaction bit is set here
     778            0 :             Either::Left((Ok((_, values)), _cancelled)) => {
     779            0 :                 results.push(values);
     780            0 :             }
     781            0 :             Either::Left((Err(e), _cancelled)) => {
     782            0 :                 return Err(e);
     783              :             }
     784            0 :             Either::Right((_cancelled, _)) => {
     785            0 :                 return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
     786              :             }
     787              :         }
     788              :     }
     789            0 :     Ok(results)
     790            0 : }
     791              : 
     792            0 : async fn query_to_json<T: GenericClient>(
     793            0 :     client: &T,
     794            0 :     data: QueryData,
     795            0 :     current_size: &mut usize,
     796            0 :     parsed_headers: HttpHeaders,
     797            0 : ) -> Result<(ReadyForQueryStatus, Value), SqlOverHttpError> {
     798            0 :     info!("executing query");
     799            0 :     let query_params = data.params;
     800            0 :     let mut row_stream = std::pin::pin!(client.query_raw_txt(&data.query, query_params).await?);
     801            0 :     info!("finished executing query");
     802              : 
     803              :     // Manually drain the stream into a vector to leave row_stream hanging
     804              :     // around to get a command tag. Also check that the response is not too
     805              :     // big.
     806            0 :     let mut rows: Vec<tokio_postgres::Row> = Vec::new();
     807            0 :     while let Some(row) = row_stream.next().await {
     808            0 :         let row = row?;
     809            0 :         *current_size += row.body_len();
     810            0 :         rows.push(row);
     811            0 :         // we don't have a streaming response support yet so this is to prevent OOM
     812            0 :         // from a malicious query (eg a cross join)
     813            0 :         if *current_size > MAX_RESPONSE_SIZE {
     814            0 :             return Err(SqlOverHttpError::ResponseTooLarge);
     815            0 :         }
     816              :     }
     817              : 
     818            0 :     let ready = row_stream.ready_status();
     819            0 : 
     820            0 :     // grab the command tag and number of rows affected
     821            0 :     let command_tag = row_stream.command_tag().unwrap_or_default();
     822            0 :     let mut command_tag_split = command_tag.split(' ');
     823            0 :     let command_tag_name = command_tag_split.next().unwrap_or_default();
     824            0 :     let command_tag_count = if command_tag_name == "INSERT" {
     825              :         // INSERT returns OID first and then number of rows
     826            0 :         command_tag_split.nth(1)
     827              :     } else {
     828              :         // other commands return number of rows (if any)
     829            0 :         command_tag_split.next()
     830              :     }
     831            0 :     .and_then(|s| s.parse::<i64>().ok());
     832            0 : 
     833            0 :     info!(
     834            0 :         rows = rows.len(),
     835            0 :         ?ready,
     836            0 :         command_tag,
     837            0 :         "finished reading rows"
     838              :     );
     839              : 
     840            0 :     let mut fields = vec![];
     841            0 :     let mut columns = vec![];
     842              : 
     843            0 :     for c in row_stream.columns() {
     844            0 :         fields.push(json!({
     845            0 :             "name": Value::String(c.name().to_owned()),
     846            0 :             "dataTypeID": Value::Number(c.type_().oid().into()),
     847            0 :             "tableID": c.table_oid(),
     848            0 :             "columnID": c.column_id(),
     849            0 :             "dataTypeSize": c.type_size(),
     850            0 :             "dataTypeModifier": c.type_modifier(),
     851            0 :             "format": "text",
     852            0 :         }));
     853            0 :         columns.push(client.get_type(c.type_oid()).await?);
     854              :     }
     855              : 
     856            0 :     let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
     857              : 
     858              :     // convert rows to JSON
     859            0 :     let rows = rows
     860            0 :         .iter()
     861            0 :         .map(|row| pg_text_row_to_json(row, &columns, parsed_headers.raw_output, array_mode))
     862            0 :         .collect::<Result<Vec<_>, _>>()?;
     863              : 
     864              :     // resulting JSON format is based on the format of node-postgres result
     865            0 :     Ok((
     866            0 :         ready,
     867            0 :         json!({
     868            0 :             "command": command_tag_name,
     869            0 :             "rowCount": command_tag_count,
     870            0 :             "rows": rows,
     871            0 :             "fields": fields,
     872            0 :             "rowAsArray": array_mode,
     873            0 :         }),
     874            0 :     ))
     875            0 : }
        

Generated by: LCOV version 2.1-beta