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