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