LCOV - code coverage report
Current view: top level - proxy/src/bin - proxy.rs (source / functions) Coverage Total Hit
Test: 12c2fc96834f59604b8ade5b9add28f1dce41ec6.info Lines: 9.6 % 456 44
Test Date: 2024-07-03 15:33:13 Functions: 15.3 % 118 18

            Line data    Source code
       1              : use aws_config::environment::EnvironmentVariableCredentialsProvider;
       2              : use aws_config::imds::credentials::ImdsCredentialsProvider;
       3              : use aws_config::meta::credentials::CredentialsProviderChain;
       4              : use aws_config::meta::region::RegionProviderChain;
       5              : use aws_config::profile::ProfileFileCredentialsProvider;
       6              : use aws_config::provider_config::ProviderConfig;
       7              : use aws_config::web_identity_token::WebIdentityTokenCredentialsProvider;
       8              : use futures::future::Either;
       9              : use proxy::auth;
      10              : use proxy::auth::backend::AuthRateLimiter;
      11              : use proxy::auth::backend::MaybeOwned;
      12              : use proxy::cancellation::CancelMap;
      13              : use proxy::cancellation::CancellationHandler;
      14              : use proxy::config::remote_storage_from_toml;
      15              : use proxy::config::AuthenticationConfig;
      16              : use proxy::config::CacheOptions;
      17              : use proxy::config::HttpConfig;
      18              : use proxy::config::ProjectInfoCacheOptions;
      19              : use proxy::console;
      20              : use proxy::context::parquet::ParquetUploadArgs;
      21              : use proxy::http;
      22              : use proxy::http::health_server::AppMetrics;
      23              : use proxy::metrics::Metrics;
      24              : use proxy::rate_limiter::EndpointRateLimiter;
      25              : use proxy::rate_limiter::RateBucketInfo;
      26              : use proxy::redis::cancellation_publisher::RedisPublisherClient;
      27              : use proxy::redis::connection_with_credentials_provider::ConnectionWithCredentialsProvider;
      28              : use proxy::redis::elasticache;
      29              : use proxy::redis::notifications;
      30              : use proxy::scram::threadpool::ThreadPool;
      31              : use proxy::serverless::cancel_set::CancelSet;
      32              : use proxy::serverless::GlobalConnPoolOptions;
      33              : use proxy::usage_metrics;
      34              : 
      35              : use anyhow::bail;
      36              : use proxy::config::{self, ProxyConfig};
      37              : use proxy::serverless;
      38              : use remote_storage::RemoteStorageConfig;
      39              : use std::net::SocketAddr;
      40              : use std::pin::pin;
      41              : use std::sync::Arc;
      42              : use tokio::net::TcpListener;
      43              : use tokio::sync::Mutex;
      44              : use tokio::task::JoinSet;
      45              : use tokio_util::sync::CancellationToken;
      46              : use tracing::info;
      47              : use tracing::warn;
      48              : use tracing::Instrument;
      49              : use utils::{project_build_tag, project_git_version, sentry_init::init_sentry};
      50              : 
      51              : project_git_version!(GIT_VERSION);
      52              : project_build_tag!(BUILD_TAG);
      53              : 
      54              : use clap::{Parser, ValueEnum};
      55              : 
      56              : #[global_allocator]
      57              : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
      58              : 
      59           20 : #[derive(Clone, Debug, ValueEnum)]
      60              : enum AuthBackend {
      61              :     Console,
      62              :     #[cfg(feature = "testing")]
      63              :     Postgres,
      64              :     Link,
      65              : }
      66              : 
      67              : /// Neon proxy/router
      68            4 : #[derive(Parser)]
      69              : #[command(version = GIT_VERSION, about)]
      70              : struct ProxyCliArgs {
      71              :     /// Name of the region this proxy is deployed in
      72            2 :     #[clap(long, default_value_t = String::new())]
      73            0 :     region: String,
      74              :     /// listen for incoming client connections on ip:port
      75              :     #[clap(short, long, default_value = "127.0.0.1:4432")]
      76            0 :     proxy: String,
      77            2 :     #[clap(value_enum, long, default_value_t = AuthBackend::Link)]
      78            0 :     auth_backend: AuthBackend,
      79              :     /// listen for management callback connection on ip:port
      80              :     #[clap(short, long, default_value = "127.0.0.1:7000")]
      81            0 :     mgmt: String,
      82              :     /// listen for incoming http connections (metrics, etc) on ip:port
      83              :     #[clap(long, default_value = "127.0.0.1:7001")]
      84            0 :     http: String,
      85              :     /// listen for incoming wss connections on ip:port
      86              :     #[clap(long)]
      87              :     wss: Option<String>,
      88              :     /// redirect unauthenticated users to the given uri in case of link auth
      89              :     #[clap(short, long, default_value = "http://localhost:3000/psql_session/")]
      90            0 :     uri: String,
      91              :     /// cloud API endpoint for authenticating users
      92              :     #[clap(
      93              :         short,
      94              :         long,
      95              :         default_value = "http://localhost:3000/authenticate_proxy_request/"
      96              :     )]
      97            0 :     auth_endpoint: String,
      98              :     /// path to TLS key for client postgres connections
      99              :     ///
     100              :     /// tls-key and tls-cert are for backwards compatibility, we can put all certs in one dir
     101              :     #[clap(short = 'k', long, alias = "ssl-key")]
     102              :     tls_key: Option<String>,
     103              :     /// path to TLS cert for client postgres connections
     104              :     ///
     105              :     /// tls-key and tls-cert are for backwards compatibility, we can put all certs in one dir
     106              :     #[clap(short = 'c', long, alias = "ssl-cert")]
     107              :     tls_cert: Option<String>,
     108              :     /// path to directory with TLS certificates for client postgres connections
     109              :     #[clap(long)]
     110              :     certs_dir: Option<String>,
     111              :     /// timeout for the TLS handshake
     112              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     113            0 :     handshake_timeout: tokio::time::Duration,
     114              :     /// http endpoint to receive periodic metric updates
     115              :     #[clap(long)]
     116              :     metric_collection_endpoint: Option<String>,
     117              :     /// how often metrics should be sent to a collection endpoint
     118              :     #[clap(long)]
     119              :     metric_collection_interval: Option<String>,
     120              :     /// cache for `wake_compute` api method (use `size=0` to disable)
     121              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     122            0 :     wake_compute_cache: String,
     123              :     /// lock for `wake_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
     124              :     #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_WAKE_COMPUTE_LOCK)]
     125            0 :     wake_compute_lock: String,
     126              :     /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
     127              :     #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
     128            0 :     connect_compute_lock: String,
     129              :     /// Allow self-signed certificates for compute nodes (for testing)
     130            2 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     131            0 :     allow_self_signed_compute: bool,
     132              :     #[clap(flatten)]
     133              :     sql_over_http: SqlOverHttpArgs,
     134              :     /// timeout for scram authentication protocol
     135              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     136            0 :     scram_protocol_timeout: tokio::time::Duration,
     137              :     /// size of the threadpool for password hashing
     138            2 :     #[clap(long, default_value_t = 4)]
     139            0 :     scram_thread_pool_size: u8,
     140              :     /// Require that all incoming requests have a Proxy Protocol V2 packet **and** have an IP address associated.
     141            2 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     142            0 :     require_client_ip: bool,
     143              :     /// Disable dynamic rate limiter and store the metrics to ensure its production behaviour.
     144            2 :     #[clap(long, default_value_t = true, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     145            0 :     disable_dynamic_rate_limiter: bool,
     146              :     /// Endpoint rate limiter max number of requests per second.
     147              :     ///
     148              :     /// Provided in the form '<Requests Per Second>@<Bucket Duration Size>'.
     149              :     /// Can be given multiple times for different bucket sizes.
     150           12 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
     151            2 :     endpoint_rps_limit: Vec<RateBucketInfo>,
     152              :     /// Wake compute rate limiter max number of requests per second.
     153           12 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_SET)]
     154            2 :     wake_compute_limit: Vec<RateBucketInfo>,
     155              :     /// Whether the auth rate limiter actually takes effect (for testing)
     156            2 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     157            0 :     auth_rate_limit_enabled: bool,
     158              :     /// Authentication rate limiter max number of hashes per second.
     159           12 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_AUTH_SET)]
     160            2 :     auth_rate_limit: Vec<RateBucketInfo>,
     161              :     /// The IP subnet to use when considering whether two IP addresses are considered the same.
     162            2 :     #[clap(long, default_value_t = 64)]
     163            0 :     auth_rate_limit_ip_subnet: u8,
     164              :     /// Redis rate limiter max number of requests per second.
     165           12 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_SET)]
     166            2 :     redis_rps_limit: Vec<RateBucketInfo>,
     167              :     /// cache for `allowed_ips` (use `size=0` to disable)
     168              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     169            0 :     allowed_ips_cache: String,
     170              :     /// cache for `role_secret` (use `size=0` to disable)
     171              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     172            0 :     role_secret_cache: String,
     173              :     /// disable ip check for http requests. If it is too time consuming, it could be turned off.
     174            2 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     175            0 :     disable_ip_check_for_http: bool,
     176              :     /// redis url for notifications (if empty, redis_host:port will be used for both notifications and streaming connections)
     177              :     #[clap(long)]
     178              :     redis_notifications: Option<String>,
     179              :     /// redis host for streaming connections (might be different from the notifications host)
     180              :     #[clap(long)]
     181              :     redis_host: Option<String>,
     182              :     /// redis port for streaming connections (might be different from the notifications host)
     183              :     #[clap(long)]
     184              :     redis_port: Option<u16>,
     185              :     /// redis cluster name, used in aws elasticache
     186              :     #[clap(long)]
     187              :     redis_cluster_name: Option<String>,
     188              :     /// redis user_id, used in aws elasticache
     189              :     #[clap(long)]
     190              :     redis_user_id: Option<String>,
     191              :     /// aws region to retrieve credentials
     192            2 :     #[clap(long, default_value_t = String::new())]
     193            0 :     aws_region: String,
     194              :     /// cache for `project_info` (use `size=0` to disable)
     195              :     #[clap(long, default_value = config::ProjectInfoCacheOptions::CACHE_DEFAULT_OPTIONS)]
     196            0 :     project_info_cache: String,
     197              :     /// cache for all valid endpoints
     198              :     #[clap(long, default_value = config::EndpointCacheConfig::CACHE_DEFAULT_OPTIONS)]
     199            0 :     endpoint_cache_config: String,
     200              :     #[clap(flatten)]
     201              :     parquet_upload: ParquetUploadArgs,
     202              : 
     203              :     /// interval for backup metric collection
     204              :     #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
     205            0 :     metric_backup_collection_interval: std::time::Duration,
     206              :     /// remote storage configuration for backup metric collection
     207              :     /// Encoded as toml (same format as pageservers), eg
     208              :     /// `{bucket_name='the-bucket',bucket_region='us-east-1',prefix_in_bucket='proxy',endpoint='http://minio:9000'}`
     209              :     #[clap(long, value_parser = remote_storage_from_toml)]
     210              :     metric_backup_collection_remote_storage: Option<RemoteStorageConfig>,
     211              :     /// chunk size for backup metric collection
     212              :     /// Size of each event is no more than 400 bytes, so 2**22 is about 200MB before the compression.
     213              :     #[clap(long, default_value = "4194304")]
     214            0 :     metric_backup_collection_chunk_size: usize,
     215              :     /// Whether to retry the connection to the compute node
     216              :     #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
     217            0 :     connect_to_compute_retry: String,
     218              :     /// Whether to retry the wake_compute request
     219              :     #[clap(long, default_value = config::RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)]
     220            0 :     wake_compute_retry: String,
     221              : }
     222              : 
     223            4 : #[derive(clap::Args, Clone, Copy, Debug)]
     224              : struct SqlOverHttpArgs {
     225              :     /// timeout for http connection requests
     226              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     227            0 :     sql_over_http_timeout: tokio::time::Duration,
     228              : 
     229              :     /// Whether the SQL over http pool is opt-in
     230            2 :     #[clap(long, default_value_t = true, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     231            0 :     sql_over_http_pool_opt_in: bool,
     232              : 
     233              :     /// How many connections to pool for each endpoint. Excess connections are discarded
     234            2 :     #[clap(long, default_value_t = 20)]
     235            0 :     sql_over_http_pool_max_conns_per_endpoint: usize,
     236              : 
     237              :     /// How many connections to pool for each endpoint. Excess connections are discarded
     238            2 :     #[clap(long, default_value_t = 20000)]
     239            0 :     sql_over_http_pool_max_total_conns: usize,
     240              : 
     241              :     /// How long pooled connections should remain idle for before closing
     242              :     #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
     243            0 :     sql_over_http_idle_timeout: tokio::time::Duration,
     244              : 
     245              :     /// Duration each shard will wait on average before a GC sweep.
     246              :     /// A longer time will causes sweeps to take longer but will interfere less frequently.
     247              :     #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
     248            0 :     sql_over_http_pool_gc_epoch: tokio::time::Duration,
     249              : 
     250              :     /// How many shards should the global pool have. Must be a power of two.
     251              :     /// More shards will introduce less contention for pool operations, but can
     252              :     /// increase memory used by the pool
     253            2 :     #[clap(long, default_value_t = 128)]
     254            0 :     sql_over_http_pool_shards: usize,
     255              : 
     256            2 :     #[clap(long, default_value_t = 10000)]
     257            0 :     sql_over_http_client_conn_threshold: u64,
     258              : 
     259            2 :     #[clap(long, default_value_t = 64)]
     260            0 :     sql_over_http_cancel_set_shards: usize,
     261              : }
     262              : 
     263              : #[tokio::main]
     264            0 : async fn main() -> anyhow::Result<()> {
     265            0 :     let _logging_guard = proxy::logging::init().await?;
     266            0 :     let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
     267            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     268            0 : 
     269            0 :     info!("Version: {GIT_VERSION}");
     270            0 :     info!("Build_tag: {BUILD_TAG}");
     271            0 :     let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
     272            0 :         revision: GIT_VERSION,
     273            0 :         build_tag: BUILD_TAG,
     274            0 :     });
     275            0 : 
     276            0 :     let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
     277            0 :         Ok(t) => Some(t),
     278            0 :         Err(e) => {
     279            0 :             tracing::error!(error = ?e, "could not start jemalloc metrics loop");
     280            0 :             None
     281            0 :         }
     282            0 :     };
     283            0 : 
     284            0 :     let args = ProxyCliArgs::parse();
     285            0 :     let config = build_config(&args)?;
     286            0 : 
     287            0 :     info!("Authentication backend: {}", config.auth_backend);
     288            0 :     info!("Using region: {}", config.aws_region);
     289            0 : 
     290            0 :     let region_provider = RegionProviderChain::default_provider().or_else(&*config.aws_region); // Replace with your Redis region if needed
     291            0 :     let provider_conf =
     292            0 :         ProviderConfig::without_region().with_region(region_provider.region().await);
     293            0 :     let aws_credentials_provider = {
     294            0 :         // uses "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"
     295            0 :         CredentialsProviderChain::first_try("env", EnvironmentVariableCredentialsProvider::new())
     296            0 :             // uses "AWS_PROFILE" / `aws sso login --profile <profile>`
     297            0 :             .or_else(
     298            0 :                 "profile-sso",
     299            0 :                 ProfileFileCredentialsProvider::builder()
     300            0 :                     .configure(&provider_conf)
     301            0 :                     .build(),
     302            0 :             )
     303            0 :             // uses "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME"
     304            0 :             // needed to access remote extensions bucket
     305            0 :             .or_else(
     306            0 :                 "token",
     307            0 :                 WebIdentityTokenCredentialsProvider::builder()
     308            0 :                     .configure(&provider_conf)
     309            0 :                     .build(),
     310            0 :             )
     311            0 :             // uses imds v2
     312            0 :             .or_else("imds", ImdsCredentialsProvider::builder().build())
     313            0 :     };
     314            0 :     let elasticache_credentials_provider = Arc::new(elasticache::CredentialsProvider::new(
     315            0 :         elasticache::AWSIRSAConfig::new(
     316            0 :             config.aws_region.clone(),
     317            0 :             args.redis_cluster_name,
     318            0 :             args.redis_user_id,
     319            0 :         ),
     320            0 :         aws_credentials_provider,
     321            0 :     ));
     322            0 :     let regional_redis_client = match (args.redis_host, args.redis_port) {
     323            0 :         (Some(host), Some(port)) => Some(
     324            0 :             ConnectionWithCredentialsProvider::new_with_credentials_provider(
     325            0 :                 host,
     326            0 :                 port,
     327            0 :                 elasticache_credentials_provider.clone(),
     328            0 :             ),
     329            0 :         ),
     330            0 :         (None, None) => {
     331            0 :             warn!("Redis events from console are disabled");
     332            0 :             None
     333            0 :         }
     334            0 :         _ => {
     335            0 :             bail!("redis-host and redis-port must be specified together");
     336            0 :         }
     337            0 :     };
     338            0 :     let redis_notifications_client = if let Some(url) = args.redis_notifications {
     339            0 :         Some(ConnectionWithCredentialsProvider::new_with_static_credentials(url))
     340            0 :     } else {
     341            0 :         regional_redis_client.clone()
     342            0 :     };
     343            0 : 
     344            0 :     // Check that we can bind to address before further initialization
     345            0 :     let http_address: SocketAddr = args.http.parse()?;
     346            0 :     info!("Starting http on {http_address}");
     347            0 :     let http_listener = TcpListener::bind(http_address).await?.into_std()?;
     348            0 : 
     349            0 :     let mgmt_address: SocketAddr = args.mgmt.parse()?;
     350            0 :     info!("Starting mgmt on {mgmt_address}");
     351            0 :     let mgmt_listener = TcpListener::bind(mgmt_address).await?;
     352            0 : 
     353            0 :     let proxy_address: SocketAddr = args.proxy.parse()?;
     354            0 :     info!("Starting proxy on {proxy_address}");
     355            0 :     let proxy_listener = TcpListener::bind(proxy_address).await?;
     356            0 :     let cancellation_token = CancellationToken::new();
     357            0 : 
     358            0 :     let cancel_map = CancelMap::default();
     359            0 : 
     360            0 :     let redis_publisher = match &regional_redis_client {
     361            0 :         Some(redis_publisher) => Some(Arc::new(Mutex::new(RedisPublisherClient::new(
     362            0 :             redis_publisher.clone(),
     363            0 :             args.region.clone(),
     364            0 :             &config.redis_rps_limit,
     365            0 :         )?))),
     366            0 :         None => None,
     367            0 :     };
     368            0 :     let cancellation_handler = Arc::new(CancellationHandler::<
     369            0 :         Option<Arc<tokio::sync::Mutex<RedisPublisherClient>>>,
     370            0 :     >::new(
     371            0 :         cancel_map.clone(),
     372            0 :         redis_publisher,
     373            0 :         proxy::metrics::CancellationSource::FromClient,
     374            0 :     ));
     375            0 : 
     376            0 :     let mut endpoint_rps_limit = args.endpoint_rps_limit.clone();
     377            0 :     RateBucketInfo::validate(&mut endpoint_rps_limit)?;
     378            0 :     let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new(endpoint_rps_limit));
     379            0 : 
     380            0 :     // client facing tasks. these will exit on error or on cancellation
     381            0 :     // cancellation returns Ok(())
     382            0 :     let mut client_tasks = JoinSet::new();
     383            0 :     client_tasks.spawn(proxy::proxy::task_main(
     384            0 :         config,
     385            0 :         proxy_listener,
     386            0 :         cancellation_token.clone(),
     387            0 :         cancellation_handler.clone(),
     388            0 :         endpoint_rate_limiter.clone(),
     389            0 :     ));
     390            0 : 
     391            0 :     // TODO: rename the argument to something like serverless.
     392            0 :     // It now covers more than just websockets, it also covers SQL over HTTP.
     393            0 :     if let Some(serverless_address) = args.wss {
     394            0 :         let serverless_address: SocketAddr = serverless_address.parse()?;
     395            0 :         info!("Starting wss on {serverless_address}");
     396            0 :         let serverless_listener = TcpListener::bind(serverless_address).await?;
     397            0 : 
     398            0 :         client_tasks.spawn(serverless::task_main(
     399            0 :             config,
     400            0 :             serverless_listener,
     401            0 :             cancellation_token.clone(),
     402            0 :             cancellation_handler.clone(),
     403            0 :             endpoint_rate_limiter.clone(),
     404            0 :         ));
     405            0 :     }
     406            0 : 
     407            0 :     client_tasks.spawn(proxy::context::parquet::worker(
     408            0 :         cancellation_token.clone(),
     409            0 :         args.parquet_upload,
     410            0 :     ));
     411            0 : 
     412            0 :     // maintenance tasks. these never return unless there's an error
     413            0 :     let mut maintenance_tasks = JoinSet::new();
     414            0 :     maintenance_tasks.spawn(proxy::handle_signals(cancellation_token.clone()));
     415            0 :     maintenance_tasks.spawn(http::health_server::task_main(
     416            0 :         http_listener,
     417            0 :         AppMetrics {
     418            0 :             jemalloc,
     419            0 :             neon_metrics,
     420            0 :             proxy: proxy::metrics::Metrics::get(),
     421            0 :         },
     422            0 :     ));
     423            0 :     maintenance_tasks.spawn(console::mgmt::task_main(mgmt_listener));
     424            0 : 
     425            0 :     if let Some(metrics_config) = &config.metric_collection {
     426            0 :         // TODO: Add gc regardles of the metric collection being enabled.
     427            0 :         maintenance_tasks.spawn(usage_metrics::task_main(metrics_config));
     428            0 :         client_tasks.spawn(usage_metrics::task_backup(
     429            0 :             &metrics_config.backup_metric_collection_config,
     430            0 :             cancellation_token.clone(),
     431            0 :         ));
     432            0 :     }
     433            0 : 
     434            0 :     if let auth::BackendType::Console(api, _) = &config.auth_backend {
     435            0 :         if let proxy::console::provider::ConsoleBackend::Console(api) = &**api {
     436            0 :             match (redis_notifications_client, regional_redis_client.clone()) {
     437            0 :                 (None, None) => {}
     438            0 :                 (client1, client2) => {
     439            0 :                     let cache = api.caches.project_info.clone();
     440            0 :                     if let Some(client) = client1 {
     441            0 :                         maintenance_tasks.spawn(notifications::task_main(
     442            0 :                             client,
     443            0 :                             cache.clone(),
     444            0 :                             cancel_map.clone(),
     445            0 :                             args.region.clone(),
     446            0 :                         ));
     447            0 :                     }
     448            0 :                     if let Some(client) = client2 {
     449            0 :                         maintenance_tasks.spawn(notifications::task_main(
     450            0 :                             client,
     451            0 :                             cache.clone(),
     452            0 :                             cancel_map.clone(),
     453            0 :                             args.region.clone(),
     454            0 :                         ));
     455            0 :                     }
     456            0 :                     maintenance_tasks.spawn(async move { cache.clone().gc_worker().await });
     457            0 :                 }
     458            0 :             }
     459            0 :             if let Some(regional_redis_client) = regional_redis_client {
     460            0 :                 let cache = api.caches.endpoints_cache.clone();
     461            0 :                 let con = regional_redis_client;
     462            0 :                 let span = tracing::info_span!("endpoints_cache");
     463            0 :                 maintenance_tasks.spawn(
     464            0 :                     async move { cache.do_read(con, cancellation_token.clone()).await }
     465            0 :                         .instrument(span),
     466            0 :                 );
     467            0 :             }
     468            0 :         }
     469            0 :     }
     470            0 : 
     471            0 :     let maintenance = loop {
     472            0 :         // get one complete task
     473            0 :         match futures::future::select(
     474            0 :             pin!(maintenance_tasks.join_next()),
     475            0 :             pin!(client_tasks.join_next()),
     476            0 :         )
     477            0 :         .await
     478            0 :         {
     479            0 :             // exit immediately on maintenance task completion
     480            0 :             Either::Left((Some(res), _)) => break proxy::flatten_err(res)?,
     481            0 :             // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
     482            0 :             Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
     483            0 :             // exit immediately on client task error
     484            0 :             Either::Right((Some(res), _)) => proxy::flatten_err(res)?,
     485            0 :             // exit if all our client tasks have shutdown gracefully
     486            0 :             Either::Right((None, _)) => return Ok(()),
     487            0 :         }
     488            0 :     };
     489            0 : 
     490            0 :     // maintenance tasks return Infallible success values, this is an impossible value
     491            0 :     // so this match statically ensures that there are no possibilities for that value
     492            0 :     match maintenance {}
     493            0 : }
     494              : 
     495              : /// ProxyConfig is created at proxy startup, and lives forever.
     496            0 : fn build_config(args: &ProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
     497            0 :     let thread_pool = ThreadPool::new(args.scram_thread_pool_size);
     498            0 :     Metrics::install(thread_pool.metrics.clone());
     499              : 
     500            0 :     let tls_config = match (&args.tls_key, &args.tls_cert) {
     501            0 :         (Some(key_path), Some(cert_path)) => Some(config::configure_tls(
     502            0 :             key_path,
     503            0 :             cert_path,
     504            0 :             args.certs_dir.as_ref(),
     505            0 :         )?),
     506            0 :         (None, None) => None,
     507            0 :         _ => bail!("either both or neither tls-key and tls-cert must be specified"),
     508              :     };
     509              : 
     510            0 :     if args.allow_self_signed_compute {
     511            0 :         warn!("allowing self-signed compute certificates");
     512            0 :     }
     513            0 :     let backup_metric_collection_config = config::MetricBackupCollectionConfig {
     514            0 :         interval: args.metric_backup_collection_interval,
     515            0 :         remote_storage_config: args.metric_backup_collection_remote_storage.clone(),
     516            0 :         chunk_size: args.metric_backup_collection_chunk_size,
     517            0 :     };
     518              : 
     519            0 :     let metric_collection = match (
     520            0 :         &args.metric_collection_endpoint,
     521            0 :         &args.metric_collection_interval,
     522              :     ) {
     523            0 :         (Some(endpoint), Some(interval)) => Some(config::MetricCollectionConfig {
     524            0 :             endpoint: endpoint.parse()?,
     525            0 :             interval: humantime::parse_duration(interval)?,
     526            0 :             backup_metric_collection_config,
     527              :         }),
     528            0 :         (None, None) => None,
     529            0 :         _ => bail!(
     530            0 :             "either both or neither metric-collection-endpoint \
     531            0 :              and metric-collection-interval must be specified"
     532            0 :         ),
     533              :     };
     534            0 :     if !args.disable_dynamic_rate_limiter {
     535            0 :         bail!("dynamic rate limiter should be disabled");
     536            0 :     }
     537              : 
     538            0 :     let auth_backend = match &args.auth_backend {
     539              :         AuthBackend::Console => {
     540            0 :             let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
     541            0 :             let project_info_cache_config: ProjectInfoCacheOptions =
     542            0 :                 args.project_info_cache.parse()?;
     543            0 :             let endpoint_cache_config: config::EndpointCacheConfig =
     544            0 :                 args.endpoint_cache_config.parse()?;
     545              : 
     546            0 :             info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
     547            0 :             info!(
     548            0 :                 "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
     549              :             );
     550            0 :             info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
     551            0 :             let caches = Box::leak(Box::new(console::caches::ApiCaches::new(
     552            0 :                 wake_compute_cache_config,
     553            0 :                 project_info_cache_config,
     554            0 :                 endpoint_cache_config,
     555            0 :             )));
     556              : 
     557              :             let config::ConcurrencyLockOptions {
     558            0 :                 shards,
     559            0 :                 limiter,
     560            0 :                 epoch,
     561            0 :                 timeout,
     562            0 :             } = args.wake_compute_lock.parse()?;
     563            0 :             info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
     564            0 :             let locks = Box::leak(Box::new(console::locks::ApiLocks::new(
     565            0 :                 "wake_compute_lock",
     566            0 :                 limiter,
     567            0 :                 shards,
     568            0 :                 timeout,
     569            0 :                 epoch,
     570            0 :                 &Metrics::get().wake_compute_lock,
     571            0 :             )?));
     572            0 :             tokio::spawn(locks.garbage_collect_worker());
     573              : 
     574            0 :             let url = args.auth_endpoint.parse()?;
     575            0 :             let endpoint = http::Endpoint::new(url, http::new_client());
     576            0 : 
     577            0 :             let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
     578            0 :             RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
     579            0 :             let wake_compute_endpoint_rate_limiter =
     580            0 :                 Arc::new(EndpointRateLimiter::new(wake_compute_rps_limit));
     581            0 :             let api = console::provider::neon::Api::new(
     582            0 :                 endpoint,
     583            0 :                 caches,
     584            0 :                 locks,
     585            0 :                 wake_compute_endpoint_rate_limiter,
     586            0 :             );
     587            0 :             let api = console::provider::ConsoleBackend::Console(api);
     588            0 :             auth::BackendType::Console(MaybeOwned::Owned(api), ())
     589              :         }
     590              :         #[cfg(feature = "testing")]
     591              :         AuthBackend::Postgres => {
     592            0 :             let url = args.auth_endpoint.parse()?;
     593            0 :             let api = console::provider::mock::Api::new(url);
     594            0 :             let api = console::provider::ConsoleBackend::Postgres(api);
     595            0 :             auth::BackendType::Console(MaybeOwned::Owned(api), ())
     596              :         }
     597              :         AuthBackend::Link => {
     598            0 :             let url = args.uri.parse()?;
     599            0 :             auth::BackendType::Link(MaybeOwned::Owned(url), ())
     600              :         }
     601              :     };
     602              : 
     603              :     let config::ConcurrencyLockOptions {
     604            0 :         shards,
     605            0 :         limiter,
     606            0 :         epoch,
     607            0 :         timeout,
     608            0 :     } = args.connect_compute_lock.parse()?;
     609            0 :     info!(
     610              :         ?limiter,
     611              :         shards,
     612              :         ?epoch,
     613            0 :         "Using NodeLocks (connect_compute)"
     614              :     );
     615            0 :     let connect_compute_locks = console::locks::ApiLocks::new(
     616            0 :         "connect_compute_lock",
     617            0 :         limiter,
     618            0 :         shards,
     619            0 :         timeout,
     620            0 :         epoch,
     621            0 :         &Metrics::get().proxy.connect_compute_lock,
     622            0 :     )?;
     623              : 
     624            0 :     let http_config = HttpConfig {
     625            0 :         request_timeout: args.sql_over_http.sql_over_http_timeout,
     626            0 :         pool_options: GlobalConnPoolOptions {
     627            0 :             max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_conns_per_endpoint,
     628            0 :             gc_epoch: args.sql_over_http.sql_over_http_pool_gc_epoch,
     629            0 :             pool_shards: args.sql_over_http.sql_over_http_pool_shards,
     630            0 :             idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
     631            0 :             opt_in: args.sql_over_http.sql_over_http_pool_opt_in,
     632            0 :             max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
     633            0 :         },
     634            0 :         cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
     635            0 :         client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
     636            0 :     };
     637            0 :     let authentication_config = AuthenticationConfig {
     638            0 :         thread_pool,
     639            0 :         scram_protocol_timeout: args.scram_protocol_timeout,
     640            0 :         rate_limiter_enabled: args.auth_rate_limit_enabled,
     641            0 :         rate_limiter: AuthRateLimiter::new(args.auth_rate_limit.clone()),
     642            0 :         rate_limit_ip_subnet: args.auth_rate_limit_ip_subnet,
     643            0 :     };
     644            0 : 
     645            0 :     let mut redis_rps_limit = args.redis_rps_limit.clone();
     646            0 :     RateBucketInfo::validate(&mut redis_rps_limit)?;
     647              : 
     648            0 :     let config = Box::leak(Box::new(ProxyConfig {
     649            0 :         tls_config,
     650            0 :         auth_backend,
     651            0 :         metric_collection,
     652            0 :         allow_self_signed_compute: args.allow_self_signed_compute,
     653            0 :         http_config,
     654            0 :         authentication_config,
     655            0 :         require_client_ip: args.require_client_ip,
     656            0 :         disable_ip_check_for_http: args.disable_ip_check_for_http,
     657            0 :         redis_rps_limit,
     658            0 :         handshake_timeout: args.handshake_timeout,
     659            0 :         region: args.region.clone(),
     660            0 :         aws_region: args.aws_region.clone(),
     661            0 :         wake_compute_retry_config: config::RetryConfig::parse(&args.wake_compute_retry)?,
     662            0 :         connect_compute_locks,
     663            0 :         connect_to_compute_retry_config: config::RetryConfig::parse(
     664            0 :             &args.connect_to_compute_retry,
     665            0 :         )?,
     666              :     }));
     667              : 
     668            0 :     tokio::spawn(config.connect_compute_locks.garbage_collect_worker());
     669            0 : 
     670            0 :     Ok(config)
     671            0 : }
     672              : 
     673              : #[cfg(test)]
     674              : mod tests {
     675              :     use std::time::Duration;
     676              : 
     677              :     use clap::Parser;
     678              :     use proxy::rate_limiter::RateBucketInfo;
     679              : 
     680              :     #[test]
     681            2 :     fn parse_endpoint_rps_limit() {
     682            2 :         let config = super::ProxyCliArgs::parse_from([
     683            2 :             "proxy",
     684            2 :             "--endpoint-rps-limit",
     685            2 :             "100@1s",
     686            2 :             "--endpoint-rps-limit",
     687            2 :             "20@30s",
     688            2 :         ]);
     689            2 : 
     690            2 :         assert_eq!(
     691            2 :             config.endpoint_rps_limit,
     692            2 :             vec![
     693            2 :                 RateBucketInfo::new(100, Duration::from_secs(1)),
     694            2 :                 RateBucketInfo::new(20, Duration::from_secs(30)),
     695            2 :             ]
     696            2 :         );
     697            2 :     }
     698              : }
        

Generated by: LCOV version 2.1-beta