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

Generated by: LCOV version 2.1-beta