LCOV - code coverage report
Current view: top level - proxy/src/serverless - backend.rs (source / functions) Coverage Total Hit
Test: 249f165943bd2c492f96a3f7d250276e4addca1a.info Lines: 0.0 % 269 0
Test Date: 2024-11-20 18:39:52 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::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<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: &RequestContext,
      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: &RequestContext,
     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: &RequestContext,
     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: &RequestContext,
     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!(
     219            0 :                     "{}{LOCAL_PROXY_SUFFIX}",
     220            0 :                     conn_info.user_info.endpoint.normalize()
     221            0 :                 )),
     222            0 :                 options: conn_info.user_info.options.clone(),
     223            0 :             },
     224            0 :             keys: crate::auth::backend::ComputeCredentialKeys::None,
     225            0 :         });
     226              :         crate::proxy::connect_compute::connect_to_compute(
     227              :             ctx,
     228              :             &HyperMechanism {
     229              :                 conn_id,
     230              :                 conn_info,
     231              :                 pool: self.http_conn_pool.clone(),
     232              :                 locks: &self.config.connect_compute_locks,
     233              :             },
     234              :             &backend,
     235              :             false, // do not allow self signed compute for http flow
     236              :             self.config.wake_compute_retry_config,
     237              :             self.config.connect_to_compute_retry_config,
     238              :         )
     239              :         .await
     240              :     }
     241              : 
     242              :     /// Connect to postgres over localhost.
     243              :     ///
     244              :     /// We expect postgres to be started here, so we won't do any retries.
     245              :     ///
     246              :     /// # Panics
     247              :     ///
     248              :     /// Panics if called with a non-local_proxy backend.
     249            0 :     #[tracing::instrument(fields(pid = tracing::field::Empty), skip_all)]
     250              :     pub(crate) async fn connect_to_local_postgres(
     251              :         &self,
     252              :         ctx: &RequestContext,
     253              :         conn_info: ConnInfo,
     254              :     ) -> Result<Client<tokio_postgres::Client>, HttpConnError> {
     255              :         if let Some(client) = self.local_pool.get(ctx, &conn_info)? {
     256              :             return Ok(client);
     257              :         }
     258              : 
     259              :         let local_backend = match &self.auth_backend {
     260              :             auth::Backend::ControlPlane(_, ()) => {
     261              :                 unreachable!("only local_proxy can connect to local postgres")
     262              :             }
     263              :             auth::Backend::Local(local) => local,
     264              :         };
     265              : 
     266              :         if !self.local_pool.initialized(&conn_info) {
     267              :             // only install and grant usage one at a time.
     268              :             let _permit = local_backend.initialize.acquire().await.unwrap();
     269              : 
     270              :             // check again for race
     271              :             if !self.local_pool.initialized(&conn_info) {
     272              :                 local_backend
     273              :                     .compute_ctl
     274              :                     .install_extension(&ExtensionInstallRequest {
     275              :                         extension: EXT_NAME,
     276              :                         database: conn_info.dbname.clone(),
     277              :                         version: EXT_VERSION,
     278              :                     })
     279              :                     .await?;
     280              : 
     281              :                 local_backend
     282              :                     .compute_ctl
     283              :                     .grant_role(&SetRoleGrantsRequest {
     284              :                         schema: EXT_SCHEMA,
     285              :                         privileges: vec![Privilege::Usage],
     286              :                         database: conn_info.dbname.clone(),
     287              :                         role: conn_info.user_info.user.clone(),
     288              :                     })
     289              :                     .await?;
     290              : 
     291              :                 self.local_pool.set_initialized(&conn_info);
     292              :             }
     293              :         }
     294              : 
     295              :         let conn_id = uuid::Uuid::new_v4();
     296              :         tracing::Span::current().record("conn_id", display(conn_id));
     297              :         info!(%conn_id, "local_pool: opening a new connection '{conn_info}'");
     298              : 
     299              :         let mut node_info = local_backend.node_info.clone();
     300              : 
     301              :         let (key, jwk) = create_random_jwk();
     302              : 
     303              :         let config = node_info
     304              :             .config
     305              :             .user(&conn_info.user_info.user)
     306              :             .dbname(&conn_info.dbname)
     307              :             .options(&format!(
     308              :                 "-c pg_session_jwt.jwk={}",
     309              :                 serde_json::to_string(&jwk).expect("serializing jwk to json should not fail")
     310              :             ));
     311              : 
     312              :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     313              :         let (client, connection) = config.connect(tokio_postgres::NoTls).await?;
     314              :         drop(pause);
     315              : 
     316              :         let pid = client.get_process_id();
     317              :         tracing::Span::current().record("pid", pid);
     318              : 
     319              :         let mut handle = local_conn_pool::poll_client(
     320              :             self.local_pool.clone(),
     321              :             ctx,
     322              :             conn_info,
     323              :             client,
     324              :             connection,
     325              :             key,
     326              :             conn_id,
     327              :             node_info.aux.clone(),
     328              :         );
     329              : 
     330              :         {
     331              :             let (client, mut discard) = handle.inner();
     332              :             debug!("setting up backend session state");
     333              : 
     334              :             // initiates the auth session
     335              :             if let Err(e) = client.query("select auth.init()", &[]).await {
     336              :                 discard.discard();
     337              :                 return Err(e.into());
     338              :             }
     339              : 
     340              :             info!("backend session state initialized");
     341              :         }
     342              : 
     343              :         Ok(handle)
     344              :     }
     345              : }
     346              : 
     347            0 : fn create_random_jwk() -> (SigningKey, JwkEcKey) {
     348            0 :     let key = SigningKey::random(&mut OsRng);
     349            0 :     let jwk = p256::PublicKey::from(key.verifying_key()).to_jwk();
     350            0 :     (key, jwk)
     351            0 : }
     352              : 
     353            0 : #[derive(Debug, thiserror::Error)]
     354              : pub(crate) enum HttpConnError {
     355              :     #[error("pooled connection closed at inconsistent state")]
     356              :     ConnectionClosedAbruptly(#[from] tokio::sync::watch::error::SendError<uuid::Uuid>),
     357              :     #[error("could not connection to postgres in compute")]
     358              :     PostgresConnectionError(#[from] tokio_postgres::Error),
     359              :     #[error("could not connection to local-proxy in compute")]
     360              :     LocalProxyConnectionError(#[from] LocalProxyConnError),
     361              :     #[error("could not parse JWT payload")]
     362              :     JwtPayloadError(serde_json::Error),
     363              : 
     364              :     #[error("could not install extension: {0}")]
     365              :     ComputeCtl(#[from] ComputeCtlError),
     366              :     #[error("could not get auth info")]
     367              :     GetAuthInfo(#[from] GetAuthInfoError),
     368              :     #[error("user not authenticated")]
     369              :     AuthError(#[from] AuthError),
     370              :     #[error("wake_compute returned error")]
     371              :     WakeCompute(#[from] WakeComputeError),
     372              :     #[error("error acquiring resource permit: {0}")]
     373              :     TooManyConnectionAttempts(#[from] ApiLockError),
     374              : }
     375              : 
     376            0 : #[derive(Debug, thiserror::Error)]
     377              : pub(crate) enum LocalProxyConnError {
     378              :     #[error("error with connection to local-proxy")]
     379              :     Io(#[source] std::io::Error),
     380              :     #[error("could not establish h2 connection")]
     381              :     H2(#[from] hyper::Error),
     382              : }
     383              : 
     384              : impl ReportableError for HttpConnError {
     385            0 :     fn get_error_kind(&self) -> ErrorKind {
     386            0 :         match self {
     387            0 :             HttpConnError::ConnectionClosedAbruptly(_) => ErrorKind::Compute,
     388            0 :             HttpConnError::PostgresConnectionError(p) => p.get_error_kind(),
     389            0 :             HttpConnError::LocalProxyConnectionError(_) => ErrorKind::Compute,
     390            0 :             HttpConnError::ComputeCtl(_) => ErrorKind::Service,
     391            0 :             HttpConnError::JwtPayloadError(_) => ErrorKind::User,
     392            0 :             HttpConnError::GetAuthInfo(a) => a.get_error_kind(),
     393            0 :             HttpConnError::AuthError(a) => a.get_error_kind(),
     394            0 :             HttpConnError::WakeCompute(w) => w.get_error_kind(),
     395            0 :             HttpConnError::TooManyConnectionAttempts(w) => w.get_error_kind(),
     396              :         }
     397            0 :     }
     398              : }
     399              : 
     400              : impl UserFacingError for HttpConnError {
     401            0 :     fn to_string_client(&self) -> String {
     402            0 :         match self {
     403            0 :             HttpConnError::ConnectionClosedAbruptly(_) => self.to_string(),
     404            0 :             HttpConnError::PostgresConnectionError(p) => p.to_string(),
     405            0 :             HttpConnError::LocalProxyConnectionError(p) => p.to_string(),
     406            0 :             HttpConnError::ComputeCtl(_) => "could not set up the JWT authorization database extension".to_string(),
     407            0 :             HttpConnError::JwtPayloadError(p) => p.to_string(),
     408            0 :             HttpConnError::GetAuthInfo(c) => c.to_string_client(),
     409            0 :             HttpConnError::AuthError(c) => c.to_string_client(),
     410            0 :             HttpConnError::WakeCompute(c) => c.to_string_client(),
     411              :             HttpConnError::TooManyConnectionAttempts(_) => {
     412            0 :                 "Failed to acquire permit to connect to the database. Too many database connection attempts are currently ongoing.".to_owned()
     413              :             }
     414              :         }
     415            0 :     }
     416              : }
     417              : 
     418              : impl CouldRetry for HttpConnError {
     419            0 :     fn could_retry(&self) -> bool {
     420            0 :         match self {
     421            0 :             HttpConnError::PostgresConnectionError(e) => e.could_retry(),
     422            0 :             HttpConnError::LocalProxyConnectionError(e) => e.could_retry(),
     423            0 :             HttpConnError::ComputeCtl(_) => false,
     424            0 :             HttpConnError::ConnectionClosedAbruptly(_) => false,
     425            0 :             HttpConnError::JwtPayloadError(_) => false,
     426            0 :             HttpConnError::GetAuthInfo(_) => false,
     427            0 :             HttpConnError::AuthError(_) => false,
     428            0 :             HttpConnError::WakeCompute(_) => false,
     429            0 :             HttpConnError::TooManyConnectionAttempts(_) => false,
     430              :         }
     431            0 :     }
     432              : }
     433              : impl ShouldRetryWakeCompute for HttpConnError {
     434            0 :     fn should_retry_wake_compute(&self) -> bool {
     435            0 :         match self {
     436            0 :             HttpConnError::PostgresConnectionError(e) => e.should_retry_wake_compute(),
     437              :             // we never checked cache validity
     438            0 :             HttpConnError::TooManyConnectionAttempts(_) => false,
     439            0 :             _ => true,
     440              :         }
     441            0 :     }
     442              : }
     443              : 
     444              : impl ReportableError for LocalProxyConnError {
     445            0 :     fn get_error_kind(&self) -> ErrorKind {
     446            0 :         match self {
     447            0 :             LocalProxyConnError::Io(_) => ErrorKind::Compute,
     448            0 :             LocalProxyConnError::H2(_) => ErrorKind::Compute,
     449              :         }
     450            0 :     }
     451              : }
     452              : 
     453              : impl UserFacingError for LocalProxyConnError {
     454            0 :     fn to_string_client(&self) -> String {
     455            0 :         "Could not establish HTTP connection to the database".to_string()
     456            0 :     }
     457              : }
     458              : 
     459              : impl CouldRetry for LocalProxyConnError {
     460            0 :     fn could_retry(&self) -> bool {
     461            0 :         match self {
     462            0 :             LocalProxyConnError::Io(_) => false,
     463            0 :             LocalProxyConnError::H2(_) => false,
     464              :         }
     465            0 :     }
     466              : }
     467              : impl ShouldRetryWakeCompute for LocalProxyConnError {
     468            0 :     fn should_retry_wake_compute(&self) -> bool {
     469            0 :         match self {
     470            0 :             LocalProxyConnError::Io(_) => false,
     471            0 :             LocalProxyConnError::H2(_) => false,
     472              :         }
     473            0 :     }
     474              : }
     475              : 
     476              : struct TokioMechanism {
     477              :     pool: Arc<GlobalConnPool<tokio_postgres::Client>>,
     478              :     conn_info: ConnInfo,
     479              :     conn_id: uuid::Uuid,
     480              : 
     481              :     /// connect_to_compute concurrency lock
     482              :     locks: &'static ApiLocks<Host>,
     483              : }
     484              : 
     485              : #[async_trait]
     486              : impl ConnectMechanism for TokioMechanism {
     487              :     type Connection = Client<tokio_postgres::Client>;
     488              :     type ConnectError = HttpConnError;
     489              :     type Error = HttpConnError;
     490              : 
     491            0 :     async fn connect_once(
     492            0 :         &self,
     493            0 :         ctx: &RequestContext,
     494            0 :         node_info: &CachedNodeInfo,
     495            0 :         timeout: Duration,
     496            0 :     ) -> Result<Self::Connection, Self::ConnectError> {
     497            0 :         let host = node_info.config.get_host()?;
     498            0 :         let permit = self.locks.get_permit(&host).await?;
     499              : 
     500            0 :         let mut config = (*node_info.config).clone();
     501            0 :         let config = config
     502            0 :             .user(&self.conn_info.user_info.user)
     503            0 :             .dbname(&self.conn_info.dbname)
     504            0 :             .connect_timeout(timeout);
     505            0 : 
     506            0 :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     507            0 :         let res = config.connect(tokio_postgres::NoTls).await;
     508            0 :         drop(pause);
     509            0 :         let (client, connection) = permit.release_result(res)?;
     510              : 
     511            0 :         tracing::Span::current().record("pid", tracing::field::display(client.get_process_id()));
     512            0 :         Ok(poll_client(
     513            0 :             self.pool.clone(),
     514            0 :             ctx,
     515            0 :             self.conn_info.clone(),
     516            0 :             client,
     517            0 :             connection,
     518            0 :             self.conn_id,
     519            0 :             node_info.aux.clone(),
     520            0 :         ))
     521            0 :     }
     522              : 
     523            0 :     fn update_connect_config(&self, _config: &mut compute::ConnCfg) {}
     524              : }
     525              : 
     526              : struct HyperMechanism {
     527              :     pool: Arc<http_conn_pool::GlobalConnPool<Send>>,
     528              :     conn_info: ConnInfo,
     529              :     conn_id: uuid::Uuid,
     530              : 
     531              :     /// connect_to_compute concurrency lock
     532              :     locks: &'static ApiLocks<Host>,
     533              : }
     534              : 
     535              : #[async_trait]
     536              : impl ConnectMechanism for HyperMechanism {
     537              :     type Connection = http_conn_pool::Client<Send>;
     538              :     type ConnectError = HttpConnError;
     539              :     type Error = HttpConnError;
     540              : 
     541            0 :     async fn connect_once(
     542            0 :         &self,
     543            0 :         ctx: &RequestContext,
     544            0 :         node_info: &CachedNodeInfo,
     545            0 :         timeout: Duration,
     546            0 :     ) -> Result<Self::Connection, Self::ConnectError> {
     547            0 :         let host = node_info.config.get_host()?;
     548            0 :         let permit = self.locks.get_permit(&host).await?;
     549              : 
     550            0 :         let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
     551              : 
     552            0 :         let port = *node_info.config.get_ports().first().ok_or_else(|| {
     553            0 :             HttpConnError::WakeCompute(WakeComputeError::BadComputeAddress(
     554            0 :                 "local-proxy port missing on compute address".into(),
     555            0 :             ))
     556            0 :         })?;
     557            0 :         let res = connect_http2(&host, port, timeout).await;
     558            0 :         drop(pause);
     559            0 :         let (client, connection) = permit.release_result(res)?;
     560              : 
     561            0 :         Ok(poll_http2_client(
     562            0 :             self.pool.clone(),
     563            0 :             ctx,
     564            0 :             &self.conn_info,
     565            0 :             client,
     566            0 :             connection,
     567            0 :             self.conn_id,
     568            0 :             node_info.aux.clone(),
     569            0 :         ))
     570            0 :     }
     571              : 
     572            0 :     fn update_connect_config(&self, _config: &mut compute::ConnCfg) {}
     573              : }
     574              : 
     575            0 : async fn connect_http2(
     576            0 :     host: &str,
     577            0 :     port: u16,
     578            0 :     timeout: Duration,
     579            0 : ) -> Result<(http_conn_pool::Send, http_conn_pool::Connect), LocalProxyConnError> {
     580              :     // assumption: host is an ip address so this should not actually perform any requests.
     581              :     // todo: add that assumption as a guarantee in the control-plane API.
     582            0 :     let mut addrs = lookup_host((host, port))
     583            0 :         .await
     584            0 :         .map_err(LocalProxyConnError::Io)?;
     585              : 
     586            0 :     let mut last_err = None;
     587              : 
     588            0 :     let stream = loop {
     589            0 :         let Some(addr) = addrs.next() else {
     590            0 :             return Err(last_err.unwrap_or_else(|| {
     591            0 :                 LocalProxyConnError::Io(io::Error::new(
     592            0 :                     io::ErrorKind::InvalidInput,
     593            0 :                     "could not resolve any addresses",
     594            0 :                 ))
     595            0 :             }));
     596              :         };
     597              : 
     598            0 :         match tokio::time::timeout(timeout, TcpStream::connect(addr)).await {
     599            0 :             Ok(Ok(stream)) => {
     600            0 :                 stream.set_nodelay(true).map_err(LocalProxyConnError::Io)?;
     601            0 :                 break stream;
     602              :             }
     603            0 :             Ok(Err(e)) => {
     604            0 :                 last_err = Some(LocalProxyConnError::Io(e));
     605            0 :             }
     606            0 :             Err(e) => {
     607            0 :                 last_err = Some(LocalProxyConnError::Io(io::Error::new(
     608            0 :                     io::ErrorKind::TimedOut,
     609            0 :                     e,
     610            0 :                 )));
     611            0 :             }
     612              :         };
     613              :     };
     614              : 
     615            0 :     let (client, connection) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
     616            0 :         .timer(TokioTimer::new())
     617            0 :         .keep_alive_interval(Duration::from_secs(20))
     618            0 :         .keep_alive_while_idle(true)
     619            0 :         .keep_alive_timeout(Duration::from_secs(5))
     620            0 :         .handshake(TokioIo::new(stream))
     621            0 :         .await?;
     622              : 
     623            0 :     Ok((client, connection))
     624            0 : }
        

Generated by: LCOV version 2.1-beta