LCOV - code coverage report
Current view: top level - proxy/src/serverless - backend.rs (source / functions) Coverage Total Hit
Test: bb45db3982713bfd5bec075773079136e362195e.info Lines: 0.0 % 268 0
Test Date: 2024-12-11 15:53:32 Functions: 0.0 % 29 0

            Line data    Source code
       1              : use std::io;
       2              : use std::sync::Arc;
       3              : use std::time::Duration;
       4              : 
       5              : use async_trait::async_trait;
       6              : use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
       7              : use p256::ecdsa::SigningKey;
       8              : use p256::elliptic_curve::JwkEcKey;
       9              : use rand::rngs::OsRng;
      10              : use tokio::net::{lookup_host, TcpStream};
      11              : use tracing::field::display;
      12              : use tracing::{debug, info};
      13              : 
      14              : use super::conn_pool::poll_client;
      15              : use super::conn_pool_lib::{Client, ConnInfo, EndpointConnPool, GlobalConnPool};
      16              : use super::http_conn_pool::{self, poll_http2_client, HttpConnPool, Send};
      17              : use super::local_conn_pool::{self, LocalConnPool, EXT_NAME, EXT_SCHEMA, EXT_VERSION};
      18              : use crate::auth::backend::local::StaticAuthRules;
      19              : use crate::auth::backend::{ComputeCredentials, ComputeUserInfo};
      20              : use crate::auth::{self, check_peer_addr_is_in_list, AuthError};
      21              : use crate::compute;
      22              : use crate::compute_ctl::{
      23              :     ComputeCtlError, ExtensionInstallRequest, Privilege, SetRoleGrantsRequest,
      24              : };
      25              : use crate::config::ProxyConfig;
      26              : use crate::context::RequestContext;
      27              : use crate::control_plane::client::ApiLockError;
      28              : use crate::control_plane::errors::{GetAuthInfoError, WakeComputeError};
      29              : use crate::control_plane::locks::ApiLocks;
      30              : use crate::control_plane::CachedNodeInfo;
      31              : use crate::error::{ErrorKind, ReportableError, UserFacingError};
      32              : use crate::intern::EndpointIdInt;
      33              : use crate::proxy::connect_compute::ConnectMechanism;
      34              : use crate::proxy::retry::{CouldRetry, ShouldRetryWakeCompute};
      35              : use crate::rate_limiter::EndpointRateLimiter;
      36              : use crate::types::{EndpointId, Host, LOCAL_PROXY_SUFFIX};
      37              : 
      38              : pub(crate) struct PoolingBackend {
      39              :     pub(crate) http_conn_pool: Arc<GlobalConnPool<Send, HttpConnPool<Send>>>,
      40              :     pub(crate) local_pool: Arc<LocalConnPool<postgres_client::Client>>,
      41              :     pub(crate) pool:
      42              :         Arc<GlobalConnPool<postgres_client::Client, EndpointConnPool<postgres_client::Client>>>,
      43              : 
      44              :     pub(crate) config: &'static ProxyConfig,
      45              :     pub(crate) auth_backend: &'static crate::auth::Backend<'static, ()>,
      46              :     pub(crate) endpoint_rate_limiter: Arc<EndpointRateLimiter>,
      47              : }
      48              : 
      49              : impl PoolingBackend {
      50            0 :     pub(crate) async fn authenticate_with_password(
      51            0 :         &self,
      52            0 :         ctx: &RequestContext,
      53            0 :         user_info: &ComputeUserInfo,
      54            0 :         password: &[u8],
      55            0 :     ) -> Result<ComputeCredentials, AuthError> {
      56            0 :         ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
      57            0 : 
      58            0 :         let user_info = user_info.clone();
      59            0 :         let backend = self.auth_backend.as_ref().map(|()| user_info.clone());
      60            0 :         let (allowed_ips, maybe_secret) = backend.get_allowed_ips_and_secret(ctx).await?;
      61            0 :         if self.config.authentication_config.ip_allowlist_check_enabled
      62            0 :             && !check_peer_addr_is_in_list(&ctx.peer_addr(), &allowed_ips)
      63              :         {
      64            0 :             return Err(AuthError::ip_address_not_allowed(ctx.peer_addr()));
      65            0 :         }
      66            0 :         if !self
      67            0 :             .endpoint_rate_limiter
      68            0 :             .check(user_info.endpoint.clone().into(), 1)
      69              :         {
      70            0 :             return Err(AuthError::too_many_connections());
      71            0 :         }
      72            0 :         let cached_secret = match maybe_secret {
      73            0 :             Some(secret) => secret,
      74            0 :             None => backend.get_role_secret(ctx).await?,
      75              :         };
      76              : 
      77            0 :         let secret = match cached_secret.value.clone() {
      78            0 :             Some(secret) => self.config.authentication_config.check_rate_limit(
      79            0 :                 ctx,
      80            0 :                 secret,
      81            0 :                 &user_info.endpoint,
      82            0 :                 true,
      83            0 :             )?,
      84              :             None => {
      85              :                 // If we don't have an authentication secret, for the http flow we can just return an error.
      86            0 :                 info!("authentication info not found");
      87            0 :                 return Err(AuthError::password_failed(&*user_info.user));
      88              :             }
      89              :         };
      90            0 :         let ep = EndpointIdInt::from(&user_info.endpoint);
      91            0 :         let auth_outcome = crate::auth::validate_password_and_exchange(
      92            0 :             &self.config.authentication_config.thread_pool,
      93            0 :             ep,
      94            0 :             password,
      95            0 :             secret,
      96            0 :         )
      97            0 :         .await?;
      98            0 :         let res = match auth_outcome {
      99            0 :             crate::sasl::Outcome::Success(key) => {
     100            0 :                 info!("user successfully authenticated");
     101            0 :                 Ok(key)
     102              :             }
     103            0 :             crate::sasl::Outcome::Failure(reason) => {
     104            0 :                 info!("auth backend failed with an error: {reason}");
     105            0 :                 Err(AuthError::password_failed(&*user_info.user))
     106              :             }
     107              :         };
     108            0 :         res.map(|key| ComputeCredentials {
     109            0 :             info: user_info,
     110            0 :             keys: key,
     111            0 :         })
     112            0 :     }
     113              : 
     114            0 :     pub(crate) async fn authenticate_with_jwt(
     115            0 :         &self,
     116            0 :         ctx: &RequestContext,
     117            0 :         user_info: &ComputeUserInfo,
     118            0 :         jwt: String,
     119            0 :     ) -> Result<ComputeCredentials, AuthError> {
     120            0 :         ctx.set_auth_method(crate::context::AuthMethod::Jwt);
     121            0 : 
     122            0 :         match &self.auth_backend {
     123            0 :             crate::auth::Backend::ControlPlane(console, ()) => {
     124            0 :                 self.config
     125            0 :                     .authentication_config
     126            0 :                     .jwks_cache
     127            0 :                     .check_jwt(
     128            0 :                         ctx,
     129            0 :                         user_info.endpoint.clone(),
     130            0 :                         &user_info.user,
     131            0 :                         &**console,
     132            0 :                         &jwt,
     133            0 :                     )
     134            0 :                     .await?;
     135              : 
     136            0 :                 Ok(ComputeCredentials {
     137            0 :                     info: user_info.clone(),
     138            0 :                     keys: crate::auth::backend::ComputeCredentialKeys::None,
     139            0 :                 })
     140              :             }
     141              :             crate::auth::Backend::Local(_) => {
     142            0 :                 let keys = self
     143            0 :                     .config
     144            0 :                     .authentication_config
     145            0 :                     .jwks_cache
     146            0 :                     .check_jwt(
     147            0 :                         ctx,
     148            0 :                         user_info.endpoint.clone(),
     149            0 :                         &user_info.user,
     150            0 :                         &StaticAuthRules,
     151            0 :                         &jwt,
     152            0 :                     )
     153            0 :                     .await?;
     154              : 
     155            0 :                 Ok(ComputeCredentials {
     156            0 :                     info: user_info.clone(),
     157            0 :                     keys,
     158            0 :                 })
     159              :             }
     160              :         }
     161            0 :     }
     162              : 
     163              :     // Wake up the destination if needed. Code here is a bit involved because
     164              :     // we reuse the code from the usual proxy and we need to prepare few structures
     165              :     // that this code expects.
     166            0 :     #[tracing::instrument(fields(pid = tracing::field::Empty), skip_all)]
     167              :     pub(crate) async fn connect_to_compute(
     168              :         &self,
     169              :         ctx: &RequestContext,
     170              :         conn_info: ConnInfo,
     171              :         keys: ComputeCredentials,
     172              :         force_new: bool,
     173              :     ) -> Result<Client<postgres_client::Client>, HttpConnError> {
     174              :         let maybe_client = if force_new {
     175              :             debug!("pool: pool is disabled");
     176              :             None
     177              :         } else {
     178              :             debug!("pool: looking for an existing connection");
     179              :             self.pool.get(ctx, &conn_info)?
     180              :         };
     181              : 
     182              :         if let Some(client) = maybe_client {
     183              :             return Ok(client);
     184              :         }
     185              :         let conn_id = uuid::Uuid::new_v4();
     186              :         tracing::Span::current().record("conn_id", display(conn_id));
     187              :         info!(%conn_id, "pool: opening a new connection '{conn_info}'");
     188            0 :         let backend = self.auth_backend.as_ref().map(|()| keys);
     189              :         crate::proxy::connect_compute::connect_to_compute(
     190              :             ctx,
     191              :             &TokioMechanism {
     192              :                 conn_id,
     193              :                 conn_info,
     194              :                 pool: self.pool.clone(),
     195              :                 locks: &self.config.connect_compute_locks,
     196              :             },
     197              :             &backend,
     198              :             false, // do not allow self signed compute for http flow
     199              :             self.config.wake_compute_retry_config,
     200              :             self.config.connect_to_compute_retry_config,
     201              :         )
     202              :         .await
     203              :     }
     204              : 
     205              :     // Wake up the destination if needed
     206            0 :     #[tracing::instrument(fields(pid = tracing::field::Empty), skip_all)]
     207              :     pub(crate) async fn connect_to_local_proxy(
     208              :         &self,
     209              :         ctx: &RequestContext,
     210              :         conn_info: ConnInfo,
     211              :     ) -> Result<http_conn_pool::Client<Send>, HttpConnError> {
     212              :         debug!("pool: looking for an existing connection");
     213              :         if let Ok(Some(client)) = self.http_conn_pool.get(ctx, &conn_info) {
     214              :             return Ok(client);
     215              :         }
     216              : 
     217              :         let conn_id = uuid::Uuid::new_v4();
     218              :         tracing::Span::current().record("conn_id", display(conn_id));
     219              :         debug!(%conn_id, "pool: opening a new connection '{conn_info}'");
     220            0 :         let backend = self.auth_backend.as_ref().map(|()| ComputeCredentials {
     221            0 :             info: ComputeUserInfo {
     222            0 :                 user: conn_info.user_info.user.clone(),
     223            0 :                 endpoint: EndpointId::from(format!(
     224            0 :                     "{}{LOCAL_PROXY_SUFFIX}",
     225            0 :                     conn_info.user_info.endpoint.normalize()
     226            0 :                 )),
     227            0 :                 options: conn_info.user_info.options.clone(),
     228            0 :             },
     229            0 :             keys: crate::auth::backend::ComputeCredentialKeys::None,
     230            0 :         });
     231              :         crate::proxy::connect_compute::connect_to_compute(
     232              :             ctx,
     233              :             &HyperMechanism {
     234              :                 conn_id,
     235              :                 conn_info,
     236              :                 pool: self.http_conn_pool.clone(),
     237              :                 locks: &self.config.connect_compute_locks,
     238              :             },
     239              :             &backend,
     240              :             false, // do not allow self signed compute for http flow
     241              :             self.config.wake_compute_retry_config,
     242              :             self.config.connect_to_compute_retry_config,
     243              :         )
     244              :         .await
     245              :     }
     246              : 
     247              :     /// Connect to postgres over localhost.
     248              :     ///
     249              :     /// We expect postgres to be started here, so we won't do any retries.
     250              :     ///
     251              :     /// # Panics
     252              :     ///
     253              :     /// Panics if called with a non-local_proxy backend.
     254            0 :     #[tracing::instrument(fields(pid = tracing::field::Empty), skip_all)]
     255              :     pub(crate) async fn connect_to_local_postgres(
     256              :         &self,
     257              :         ctx: &RequestContext,
     258              :         conn_info: ConnInfo,
     259              :     ) -> Result<Client<postgres_client::Client>, HttpConnError> {
     260              :         if let Some(client) = self.local_pool.get(ctx, &conn_info)? {
     261              :             return Ok(client);
     262              :         }
     263              : 
     264              :         let local_backend = match &self.auth_backend {
     265              :             auth::Backend::ControlPlane(_, ()) => {
     266              :                 unreachable!("only local_proxy can connect to local postgres")
     267              :             }
     268              :             auth::Backend::Local(local) => local,
     269              :         };
     270              : 
     271              :         if !self.local_pool.initialized(&conn_info) {
     272              :             // only install and grant usage one at a time.
     273              :             let _permit = local_backend.initialize.acquire().await.unwrap();
     274              : 
     275              :             // check again for race
     276              :             if !self.local_pool.initialized(&conn_info) {
     277              :                 local_backend
     278              :                     .compute_ctl
     279              :                     .install_extension(&ExtensionInstallRequest {
     280              :                         extension: EXT_NAME,
     281              :                         database: conn_info.dbname.clone(),
     282              :                         version: EXT_VERSION,
     283              :                     })
     284              :                     .await?;
     285              : 
     286              :                 local_backend
     287              :                     .compute_ctl
     288              :                     .grant_role(&SetRoleGrantsRequest {
     289              :                         schema: EXT_SCHEMA,
     290              :                         privileges: vec![Privilege::Usage],
     291              :                         database: conn_info.dbname.clone(),
     292              :                         role: conn_info.user_info.user.clone(),
     293              :                     })
     294              :                     .await?;
     295              : 
     296              :                 self.local_pool.set_initialized(&conn_info);
     297              :             }
     298              :         }
     299              : 
     300              :         let conn_id = uuid::Uuid::new_v4();
     301              :         tracing::Span::current().record("conn_id", display(conn_id));
     302              :         info!(%conn_id, "local_pool: opening a new connection '{conn_info}'");
     303              : 
     304              :         let mut node_info = local_backend.node_info.clone();
     305              : 
     306              :         let (key, jwk) = create_random_jwk();
     307              : 
     308              :         let config = node_info
     309              :             .config
     310              :             .user(&conn_info.user_info.user)
     311              :             .dbname(&conn_info.dbname)
     312              :             .set_param(
     313              :                 "options",
     314              :                 &format!(
     315              :                     "-c pg_session_jwt.jwk={}",
     316              :                     serde_json::to_string(&jwk).expect("serializing jwk to json should not fail")
     317              :                 ),
     318              :             );
     319              : 
     320              :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     321              :         let (client, connection) = config.connect(postgres_client::NoTls).await?;
     322              :         drop(pause);
     323              : 
     324              :         let pid = client.get_process_id();
     325              :         tracing::Span::current().record("pid", pid);
     326              : 
     327              :         let mut handle = local_conn_pool::poll_client(
     328              :             self.local_pool.clone(),
     329              :             ctx,
     330              :             conn_info,
     331              :             client,
     332              :             connection,
     333              :             key,
     334              :             conn_id,
     335              :             node_info.aux.clone(),
     336              :         );
     337              : 
     338              :         {
     339              :             let (client, mut discard) = handle.inner();
     340              :             debug!("setting up backend session state");
     341              : 
     342              :             // initiates the auth session
     343              :             if let Err(e) = client.execute("select auth.init()", &[]).await {
     344              :                 discard.discard();
     345              :                 return Err(e.into());
     346              :             }
     347              : 
     348              :             info!("backend session state initialized");
     349              :         }
     350              : 
     351              :         Ok(handle)
     352              :     }
     353              : }
     354              : 
     355            0 : fn create_random_jwk() -> (SigningKey, JwkEcKey) {
     356            0 :     let key = SigningKey::random(&mut OsRng);
     357            0 :     let jwk = p256::PublicKey::from(key.verifying_key()).to_jwk();
     358            0 :     (key, jwk)
     359            0 : }
     360              : 
     361              : #[derive(Debug, thiserror::Error)]
     362              : pub(crate) enum HttpConnError {
     363              :     #[error("pooled connection closed at inconsistent state")]
     364              :     ConnectionClosedAbruptly(#[from] tokio::sync::watch::error::SendError<uuid::Uuid>),
     365              :     #[error("could not connection to postgres in compute")]
     366              :     PostgresConnectionError(#[from] postgres_client::Error),
     367              :     #[error("could not connection to local-proxy in compute")]
     368              :     LocalProxyConnectionError(#[from] LocalProxyConnError),
     369              :     #[error("could not parse JWT payload")]
     370              :     JwtPayloadError(serde_json::Error),
     371              : 
     372              :     #[error("could not install extension: {0}")]
     373              :     ComputeCtl(#[from] ComputeCtlError),
     374              :     #[error("could not get auth info")]
     375              :     GetAuthInfo(#[from] GetAuthInfoError),
     376              :     #[error("user not authenticated")]
     377              :     AuthError(#[from] AuthError),
     378              :     #[error("wake_compute returned error")]
     379              :     WakeCompute(#[from] WakeComputeError),
     380              :     #[error("error acquiring resource permit: {0}")]
     381              :     TooManyConnectionAttempts(#[from] ApiLockError),
     382              : }
     383              : 
     384              : #[derive(Debug, thiserror::Error)]
     385              : pub(crate) enum LocalProxyConnError {
     386              :     #[error("error with connection to local-proxy")]
     387              :     Io(#[source] std::io::Error),
     388              :     #[error("could not establish h2 connection")]
     389              :     H2(#[from] hyper::Error),
     390              : }
     391              : 
     392              : impl ReportableError for HttpConnError {
     393            0 :     fn get_error_kind(&self) -> ErrorKind {
     394            0 :         match self {
     395            0 :             HttpConnError::ConnectionClosedAbruptly(_) => ErrorKind::Compute,
     396            0 :             HttpConnError::PostgresConnectionError(p) => p.get_error_kind(),
     397            0 :             HttpConnError::LocalProxyConnectionError(_) => ErrorKind::Compute,
     398            0 :             HttpConnError::ComputeCtl(_) => ErrorKind::Service,
     399            0 :             HttpConnError::JwtPayloadError(_) => ErrorKind::User,
     400            0 :             HttpConnError::GetAuthInfo(a) => a.get_error_kind(),
     401            0 :             HttpConnError::AuthError(a) => a.get_error_kind(),
     402            0 :             HttpConnError::WakeCompute(w) => w.get_error_kind(),
     403            0 :             HttpConnError::TooManyConnectionAttempts(w) => w.get_error_kind(),
     404              :         }
     405            0 :     }
     406              : }
     407              : 
     408              : impl UserFacingError for HttpConnError {
     409            0 :     fn to_string_client(&self) -> String {
     410            0 :         match self {
     411            0 :             HttpConnError::ConnectionClosedAbruptly(_) => self.to_string(),
     412            0 :             HttpConnError::PostgresConnectionError(p) => p.to_string(),
     413            0 :             HttpConnError::LocalProxyConnectionError(p) => p.to_string(),
     414            0 :             HttpConnError::ComputeCtl(_) => "could not set up the JWT authorization database extension".to_string(),
     415            0 :             HttpConnError::JwtPayloadError(p) => p.to_string(),
     416            0 :             HttpConnError::GetAuthInfo(c) => c.to_string_client(),
     417            0 :             HttpConnError::AuthError(c) => c.to_string_client(),
     418            0 :             HttpConnError::WakeCompute(c) => c.to_string_client(),
     419              :             HttpConnError::TooManyConnectionAttempts(_) => {
     420            0 :                 "Failed to acquire permit to connect to the database. Too many database connection attempts are currently ongoing.".to_owned()
     421              :             }
     422              :         }
     423            0 :     }
     424              : }
     425              : 
     426              : impl CouldRetry for HttpConnError {
     427            0 :     fn could_retry(&self) -> bool {
     428            0 :         match self {
     429            0 :             HttpConnError::PostgresConnectionError(e) => e.could_retry(),
     430            0 :             HttpConnError::LocalProxyConnectionError(e) => e.could_retry(),
     431            0 :             HttpConnError::ComputeCtl(_) => false,
     432            0 :             HttpConnError::ConnectionClosedAbruptly(_) => false,
     433            0 :             HttpConnError::JwtPayloadError(_) => false,
     434            0 :             HttpConnError::GetAuthInfo(_) => false,
     435            0 :             HttpConnError::AuthError(_) => false,
     436            0 :             HttpConnError::WakeCompute(_) => false,
     437            0 :             HttpConnError::TooManyConnectionAttempts(_) => false,
     438              :         }
     439            0 :     }
     440              : }
     441              : impl ShouldRetryWakeCompute for HttpConnError {
     442            0 :     fn should_retry_wake_compute(&self) -> bool {
     443            0 :         match self {
     444            0 :             HttpConnError::PostgresConnectionError(e) => e.should_retry_wake_compute(),
     445              :             // we never checked cache validity
     446            0 :             HttpConnError::TooManyConnectionAttempts(_) => false,
     447            0 :             _ => true,
     448              :         }
     449            0 :     }
     450              : }
     451              : 
     452              : impl ReportableError for LocalProxyConnError {
     453            0 :     fn get_error_kind(&self) -> ErrorKind {
     454            0 :         match self {
     455            0 :             LocalProxyConnError::Io(_) => ErrorKind::Compute,
     456            0 :             LocalProxyConnError::H2(_) => ErrorKind::Compute,
     457              :         }
     458            0 :     }
     459              : }
     460              : 
     461              : impl UserFacingError for LocalProxyConnError {
     462            0 :     fn to_string_client(&self) -> String {
     463            0 :         "Could not establish HTTP connection to the database".to_string()
     464            0 :     }
     465              : }
     466              : 
     467              : impl CouldRetry for LocalProxyConnError {
     468            0 :     fn could_retry(&self) -> bool {
     469            0 :         match self {
     470            0 :             LocalProxyConnError::Io(_) => false,
     471            0 :             LocalProxyConnError::H2(_) => false,
     472              :         }
     473            0 :     }
     474              : }
     475              : impl ShouldRetryWakeCompute for LocalProxyConnError {
     476            0 :     fn should_retry_wake_compute(&self) -> bool {
     477            0 :         match self {
     478            0 :             LocalProxyConnError::Io(_) => false,
     479            0 :             LocalProxyConnError::H2(_) => false,
     480              :         }
     481            0 :     }
     482              : }
     483              : 
     484              : struct TokioMechanism {
     485              :     pool: Arc<GlobalConnPool<postgres_client::Client, EndpointConnPool<postgres_client::Client>>>,
     486              :     conn_info: ConnInfo,
     487              :     conn_id: uuid::Uuid,
     488              : 
     489              :     /// connect_to_compute concurrency lock
     490              :     locks: &'static ApiLocks<Host>,
     491              : }
     492              : 
     493              : #[async_trait]
     494              : impl ConnectMechanism for TokioMechanism {
     495              :     type Connection = Client<postgres_client::Client>;
     496              :     type ConnectError = HttpConnError;
     497              :     type Error = HttpConnError;
     498              : 
     499            0 :     async fn connect_once(
     500            0 :         &self,
     501            0 :         ctx: &RequestContext,
     502            0 :         node_info: &CachedNodeInfo,
     503            0 :         timeout: Duration,
     504            0 :     ) -> Result<Self::Connection, Self::ConnectError> {
     505            0 :         let host = node_info.config.get_host();
     506            0 :         let permit = self.locks.get_permit(&host).await?;
     507              : 
     508            0 :         let mut config = (*node_info.config).clone();
     509            0 :         let config = config
     510            0 :             .user(&self.conn_info.user_info.user)
     511            0 :             .dbname(&self.conn_info.dbname)
     512            0 :             .connect_timeout(timeout);
     513            0 : 
     514            0 :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     515            0 :         let res = config.connect(postgres_client::NoTls).await;
     516            0 :         drop(pause);
     517            0 :         let (client, connection) = permit.release_result(res)?;
     518              : 
     519            0 :         tracing::Span::current().record("pid", tracing::field::display(client.get_process_id()));
     520            0 :         Ok(poll_client(
     521            0 :             self.pool.clone(),
     522            0 :             ctx,
     523            0 :             self.conn_info.clone(),
     524            0 :             client,
     525            0 :             connection,
     526            0 :             self.conn_id,
     527            0 :             node_info.aux.clone(),
     528            0 :         ))
     529            0 :     }
     530              : 
     531            0 :     fn update_connect_config(&self, _config: &mut compute::ConnCfg) {}
     532              : }
     533              : 
     534              : struct HyperMechanism {
     535              :     pool: Arc<GlobalConnPool<Send, HttpConnPool<Send>>>,
     536              :     conn_info: ConnInfo,
     537              :     conn_id: uuid::Uuid,
     538              : 
     539              :     /// connect_to_compute concurrency lock
     540              :     locks: &'static ApiLocks<Host>,
     541              : }
     542              : 
     543              : #[async_trait]
     544              : impl ConnectMechanism for HyperMechanism {
     545              :     type Connection = http_conn_pool::Client<Send>;
     546              :     type ConnectError = HttpConnError;
     547              :     type Error = HttpConnError;
     548              : 
     549            0 :     async fn connect_once(
     550            0 :         &self,
     551            0 :         ctx: &RequestContext,
     552            0 :         node_info: &CachedNodeInfo,
     553            0 :         timeout: Duration,
     554            0 :     ) -> Result<Self::Connection, Self::ConnectError> {
     555            0 :         let host = node_info.config.get_host();
     556            0 :         let permit = self.locks.get_permit(&host).await?;
     557              : 
     558            0 :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     559            0 : 
     560            0 :         let port = node_info.config.get_port();
     561            0 :         let res = connect_http2(&host, port, timeout).await;
     562            0 :         drop(pause);
     563            0 :         let (client, connection) = permit.release_result(res)?;
     564              : 
     565            0 :         Ok(poll_http2_client(
     566            0 :             self.pool.clone(),
     567            0 :             ctx,
     568            0 :             &self.conn_info,
     569            0 :             client,
     570            0 :             connection,
     571            0 :             self.conn_id,
     572            0 :             node_info.aux.clone(),
     573            0 :         ))
     574            0 :     }
     575              : 
     576            0 :     fn update_connect_config(&self, _config: &mut compute::ConnCfg) {}
     577              : }
     578              : 
     579            0 : async fn connect_http2(
     580            0 :     host: &str,
     581            0 :     port: u16,
     582            0 :     timeout: Duration,
     583            0 : ) -> Result<(http_conn_pool::Send, http_conn_pool::Connect), LocalProxyConnError> {
     584              :     // assumption: host is an ip address so this should not actually perform any requests.
     585              :     // todo: add that assumption as a guarantee in the control-plane API.
     586            0 :     let mut addrs = lookup_host((host, port))
     587            0 :         .await
     588            0 :         .map_err(LocalProxyConnError::Io)?;
     589              : 
     590            0 :     let mut last_err = None;
     591              : 
     592            0 :     let stream = loop {
     593            0 :         let Some(addr) = addrs.next() else {
     594            0 :             return Err(last_err.unwrap_or_else(|| {
     595            0 :                 LocalProxyConnError::Io(io::Error::new(
     596            0 :                     io::ErrorKind::InvalidInput,
     597            0 :                     "could not resolve any addresses",
     598            0 :                 ))
     599            0 :             }));
     600              :         };
     601              : 
     602            0 :         match tokio::time::timeout(timeout, TcpStream::connect(addr)).await {
     603            0 :             Ok(Ok(stream)) => {
     604            0 :                 stream.set_nodelay(true).map_err(LocalProxyConnError::Io)?;
     605            0 :                 break stream;
     606              :             }
     607            0 :             Ok(Err(e)) => {
     608            0 :                 last_err = Some(LocalProxyConnError::Io(e));
     609            0 :             }
     610            0 :             Err(e) => {
     611            0 :                 last_err = Some(LocalProxyConnError::Io(io::Error::new(
     612            0 :                     io::ErrorKind::TimedOut,
     613            0 :                     e,
     614            0 :                 )));
     615            0 :             }
     616              :         };
     617              :     };
     618              : 
     619            0 :     let (client, connection) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
     620            0 :         .timer(TokioTimer::new())
     621            0 :         .keep_alive_interval(Duration::from_secs(20))
     622            0 :         .keep_alive_while_idle(true)
     623            0 :         .keep_alive_timeout(Duration::from_secs(5))
     624            0 :         .handshake(TokioIo::new(stream))
     625            0 :         .await?;
     626              : 
     627            0 :     Ok((client, connection))
     628            0 : }
        

Generated by: LCOV version 2.1-beta