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

Generated by: LCOV version 2.1-beta