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

Generated by: LCOV version 2.1-beta