Line data Source code
1 : #[cfg(any(test, feature = "testing"))]
2 : pub mod mock;
3 : pub mod neon;
4 :
5 : use super::messages::MetricsAuxInfo;
6 : use crate::{
7 : auth::{
8 : backend::{ComputeCredentialKeys, ComputeUserInfo},
9 : IpPattern,
10 : },
11 : cache::{endpoints::EndpointsCache, project_info::ProjectInfoCacheImpl, Cached, TimedLru},
12 : compute,
13 : config::{CacheOptions, EndpointCacheConfig, ProjectInfoCacheOptions},
14 : context::RequestMonitoring,
15 : error::ReportableError,
16 : intern::ProjectIdInt,
17 : metrics::ApiLockMetrics,
18 : rate_limiter::{DynamicLimiter, Outcome, RateLimiterConfig, Token},
19 : scram, EndpointCacheKey,
20 : };
21 : use dashmap::DashMap;
22 : use std::{hash::Hash, sync::Arc, time::Duration};
23 : use tokio::time::Instant;
24 : use tracing::info;
25 :
26 : pub mod errors {
27 : use crate::{
28 : console::messages::{self, ConsoleError},
29 : error::{io_error, ReportableError, UserFacingError},
30 : proxy::retry::ShouldRetry,
31 : };
32 : use thiserror::Error;
33 :
34 : use super::ApiLockError;
35 :
36 : /// A go-to error message which doesn't leak any detail.
37 : pub const REQUEST_FAILED: &str = "Console request failed";
38 :
39 : /// Common console API error.
40 0 : #[derive(Debug, Error)]
41 : pub enum ApiError {
42 : /// Error returned by the console itself.
43 : #[error("{REQUEST_FAILED} with {0}")]
44 : Console(ConsoleError),
45 :
46 : /// Various IO errors like broken pipe or malformed payload.
47 : #[error("{REQUEST_FAILED}: {0}")]
48 : Transport(#[from] std::io::Error),
49 : }
50 :
51 : impl ApiError {
52 : /// Returns HTTP status code if it's the reason for failure.
53 0 : pub fn get_reason(&self) -> messages::Reason {
54 0 : use ApiError::*;
55 0 : match self {
56 0 : Console(e) => e.get_reason(),
57 0 : _ => messages::Reason::Unknown,
58 : }
59 0 : }
60 : }
61 :
62 : impl UserFacingError for ApiError {
63 0 : fn to_string_client(&self) -> String {
64 0 : use ApiError::*;
65 0 : match self {
66 : // To minimize risks, only select errors are forwarded to users.
67 0 : Console(c) => c.get_user_facing_message(),
68 0 : _ => REQUEST_FAILED.to_owned(),
69 : }
70 0 : }
71 : }
72 :
73 : impl ReportableError for ApiError {
74 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
75 0 : match self {
76 0 : ApiError::Console(e) => {
77 0 : use crate::error::ErrorKind::*;
78 0 : match e.get_reason() {
79 0 : crate::console::messages::Reason::RoleProtected => User,
80 0 : crate::console::messages::Reason::ResourceNotFound => User,
81 0 : crate::console::messages::Reason::ProjectNotFound => User,
82 0 : crate::console::messages::Reason::EndpointNotFound => User,
83 0 : crate::console::messages::Reason::BranchNotFound => User,
84 0 : crate::console::messages::Reason::RateLimitExceeded => ServiceRateLimit,
85 : crate::console::messages::Reason::NonPrimaryBranchComputeTimeExceeded => {
86 0 : User
87 : }
88 0 : crate::console::messages::Reason::ActiveTimeQuotaExceeded => User,
89 0 : crate::console::messages::Reason::ComputeTimeQuotaExceeded => User,
90 0 : crate::console::messages::Reason::WrittenDataQuotaExceeded => User,
91 0 : crate::console::messages::Reason::DataTransferQuotaExceeded => User,
92 0 : crate::console::messages::Reason::LogicalSizeQuotaExceeded => User,
93 0 : crate::console::messages::Reason::Unknown => match &e {
94 : ConsoleError {
95 : http_status_code:
96 : http::StatusCode::NOT_FOUND | http::StatusCode::NOT_ACCEPTABLE,
97 : ..
98 0 : } => crate::error::ErrorKind::User,
99 : ConsoleError {
100 : http_status_code: http::StatusCode::UNPROCESSABLE_ENTITY,
101 0 : error,
102 0 : ..
103 0 : } if error.contains(
104 : "compute time quota of non-primary branches is exceeded",
105 0 : ) =>
106 0 : {
107 0 : crate::error::ErrorKind::User
108 : }
109 : ConsoleError {
110 : http_status_code: http::StatusCode::LOCKED,
111 0 : error,
112 0 : ..
113 0 : } if error.contains("quota exceeded")
114 0 : || error.contains("the limit for current plan reached") =>
115 0 : {
116 0 : crate::error::ErrorKind::User
117 : }
118 : ConsoleError {
119 : http_status_code: http::StatusCode::TOO_MANY_REQUESTS,
120 : ..
121 0 : } => crate::error::ErrorKind::ServiceRateLimit,
122 0 : ConsoleError { .. } => crate::error::ErrorKind::ControlPlane,
123 : },
124 : }
125 : }
126 0 : ApiError::Transport(_) => crate::error::ErrorKind::ControlPlane,
127 : }
128 0 : }
129 : }
130 :
131 : impl ShouldRetry for ApiError {
132 12 : fn could_retry(&self) -> bool {
133 12 : match self {
134 : // retry some transport errors
135 0 : Self::Transport(io) => io.could_retry(),
136 12 : Self::Console(e) => e.could_retry(),
137 : }
138 12 : }
139 : }
140 :
141 : impl From<reqwest::Error> for ApiError {
142 0 : fn from(e: reqwest::Error) -> Self {
143 0 : io_error(e).into()
144 0 : }
145 : }
146 :
147 : impl From<reqwest_middleware::Error> for ApiError {
148 0 : fn from(e: reqwest_middleware::Error) -> Self {
149 0 : io_error(e).into()
150 0 : }
151 : }
152 :
153 0 : #[derive(Debug, Error)]
154 : pub enum GetAuthInfoError {
155 : // We shouldn't include the actual secret here.
156 : #[error("Console responded with a malformed auth secret")]
157 : BadSecret,
158 :
159 : #[error(transparent)]
160 : ApiError(ApiError),
161 : }
162 :
163 : // This allows more useful interactions than `#[from]`.
164 : impl<E: Into<ApiError>> From<E> for GetAuthInfoError {
165 0 : fn from(e: E) -> Self {
166 0 : Self::ApiError(e.into())
167 0 : }
168 : }
169 :
170 : impl UserFacingError for GetAuthInfoError {
171 0 : fn to_string_client(&self) -> String {
172 0 : use GetAuthInfoError::*;
173 0 : match self {
174 : // We absolutely should not leak any secrets!
175 0 : BadSecret => REQUEST_FAILED.to_owned(),
176 : // However, API might return a meaningful error.
177 0 : ApiError(e) => e.to_string_client(),
178 : }
179 0 : }
180 : }
181 :
182 : impl ReportableError for GetAuthInfoError {
183 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
184 0 : match self {
185 0 : GetAuthInfoError::BadSecret => crate::error::ErrorKind::ControlPlane,
186 0 : GetAuthInfoError::ApiError(_) => crate::error::ErrorKind::ControlPlane,
187 : }
188 0 : }
189 : }
190 :
191 0 : #[derive(Debug, Error)]
192 : pub enum WakeComputeError {
193 : #[error("Console responded with a malformed compute address: {0}")]
194 : BadComputeAddress(Box<str>),
195 :
196 : #[error(transparent)]
197 : ApiError(ApiError),
198 :
199 : #[error("Too many connections attempts")]
200 : TooManyConnections,
201 :
202 : #[error("error acquiring resource permit: {0}")]
203 : TooManyConnectionAttempts(#[from] ApiLockError),
204 : }
205 :
206 : // This allows more useful interactions than `#[from]`.
207 : impl<E: Into<ApiError>> From<E> for WakeComputeError {
208 0 : fn from(e: E) -> Self {
209 0 : Self::ApiError(e.into())
210 0 : }
211 : }
212 :
213 : impl UserFacingError for WakeComputeError {
214 0 : fn to_string_client(&self) -> String {
215 0 : use WakeComputeError::*;
216 0 : match self {
217 : // We shouldn't show user the address even if it's broken.
218 : // Besides, user is unlikely to care about this detail.
219 0 : BadComputeAddress(_) => REQUEST_FAILED.to_owned(),
220 : // However, API might return a meaningful error.
221 0 : ApiError(e) => e.to_string_client(),
222 :
223 0 : TooManyConnections => self.to_string(),
224 :
225 : TooManyConnectionAttempts(_) => {
226 0 : "Failed to acquire permit to connect to the database. Too many database connection attempts are currently ongoing.".to_owned()
227 : }
228 : }
229 0 : }
230 : }
231 :
232 : impl ReportableError for WakeComputeError {
233 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
234 0 : match self {
235 0 : WakeComputeError::BadComputeAddress(_) => crate::error::ErrorKind::ControlPlane,
236 0 : WakeComputeError::ApiError(e) => e.get_error_kind(),
237 0 : WakeComputeError::TooManyConnections => crate::error::ErrorKind::RateLimit,
238 0 : WakeComputeError::TooManyConnectionAttempts(e) => e.get_error_kind(),
239 : }
240 0 : }
241 : }
242 : }
243 :
244 : /// Auth secret which is managed by the cloud.
245 : #[derive(Clone, Eq, PartialEq, Debug)]
246 : pub enum AuthSecret {
247 : #[cfg(any(test, feature = "testing"))]
248 : /// Md5 hash of user's password.
249 : Md5([u8; 16]),
250 :
251 : /// [SCRAM](crate::scram) authentication info.
252 : Scram(scram::ServerSecret),
253 : }
254 :
255 : #[derive(Default)]
256 : pub struct AuthInfo {
257 : pub secret: Option<AuthSecret>,
258 : /// List of IP addresses allowed for the autorization.
259 : pub allowed_ips: Vec<IpPattern>,
260 : /// Project ID. This is used for cache invalidation.
261 : pub project_id: Option<ProjectIdInt>,
262 : }
263 :
264 : /// Info for establishing a connection to a compute node.
265 : /// This is what we get after auth succeeded, but not before!
266 : #[derive(Clone)]
267 : pub struct NodeInfo {
268 : /// Compute node connection params.
269 : /// It's sad that we have to clone this, but this will improve
270 : /// once we migrate to a bespoke connection logic.
271 : pub config: compute::ConnCfg,
272 :
273 : /// Labels for proxy's metrics.
274 : pub aux: MetricsAuxInfo,
275 :
276 : /// Whether we should accept self-signed certificates (for testing)
277 : pub allow_self_signed_compute: bool,
278 : }
279 :
280 : impl NodeInfo {
281 0 : pub async fn connect(
282 0 : &self,
283 0 : ctx: &mut RequestMonitoring,
284 0 : timeout: Duration,
285 0 : ) -> Result<compute::PostgresConnection, compute::ConnectionError> {
286 0 : self.config
287 0 : .connect(
288 0 : ctx,
289 0 : self.allow_self_signed_compute,
290 0 : self.aux.clone(),
291 0 : timeout,
292 0 : )
293 0 : .await
294 0 : }
295 8 : pub fn reuse_settings(&mut self, other: Self) {
296 8 : self.allow_self_signed_compute = other.allow_self_signed_compute;
297 8 : self.config.reuse_password(other.config);
298 8 : }
299 :
300 12 : pub fn set_keys(&mut self, keys: &ComputeCredentialKeys) {
301 12 : match keys {
302 12 : ComputeCredentialKeys::Password(password) => self.config.password(password),
303 0 : ComputeCredentialKeys::AuthKeys(auth_keys) => self.config.auth_keys(*auth_keys),
304 : };
305 12 : }
306 : }
307 :
308 : pub type NodeInfoCache = TimedLru<EndpointCacheKey, NodeInfo>;
309 : pub type CachedNodeInfo = Cached<&'static NodeInfoCache>;
310 : pub type CachedRoleSecret = Cached<&'static ProjectInfoCacheImpl, Option<AuthSecret>>;
311 : pub type CachedAllowedIps = Cached<&'static ProjectInfoCacheImpl, Arc<Vec<IpPattern>>>;
312 :
313 : /// This will allocate per each call, but the http requests alone
314 : /// already require a few allocations, so it should be fine.
315 : pub(crate) trait Api {
316 : /// Get the client's auth secret for authentication.
317 : /// Returns option because user not found situation is special.
318 : /// We still have to mock the scram to avoid leaking information that user doesn't exist.
319 : async fn get_role_secret(
320 : &self,
321 : ctx: &mut RequestMonitoring,
322 : user_info: &ComputeUserInfo,
323 : ) -> Result<CachedRoleSecret, errors::GetAuthInfoError>;
324 :
325 : async fn get_allowed_ips_and_secret(
326 : &self,
327 : ctx: &mut RequestMonitoring,
328 : user_info: &ComputeUserInfo,
329 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), errors::GetAuthInfoError>;
330 :
331 : /// Wake up the compute node and return the corresponding connection info.
332 : async fn wake_compute(
333 : &self,
334 : ctx: &mut RequestMonitoring,
335 : user_info: &ComputeUserInfo,
336 : ) -> Result<CachedNodeInfo, errors::WakeComputeError>;
337 : }
338 :
339 : #[non_exhaustive]
340 : pub enum ConsoleBackend {
341 : /// Current Cloud API (V2).
342 : Console(neon::Api),
343 : /// Local mock of Cloud API (V2).
344 : #[cfg(any(test, feature = "testing"))]
345 : Postgres(mock::Api),
346 : /// Internal testing
347 : #[cfg(test)]
348 : Test(Box<dyn crate::auth::backend::TestBackend>),
349 : }
350 :
351 : impl Api for ConsoleBackend {
352 0 : async fn get_role_secret(
353 0 : &self,
354 0 : ctx: &mut RequestMonitoring,
355 0 : user_info: &ComputeUserInfo,
356 0 : ) -> Result<CachedRoleSecret, errors::GetAuthInfoError> {
357 0 : use ConsoleBackend::*;
358 0 : match self {
359 0 : Console(api) => api.get_role_secret(ctx, user_info).await,
360 : #[cfg(any(test, feature = "testing"))]
361 0 : Postgres(api) => api.get_role_secret(ctx, user_info).await,
362 : #[cfg(test)]
363 0 : Test(_) => unreachable!("this function should never be called in the test backend"),
364 : }
365 0 : }
366 :
367 0 : async fn get_allowed_ips_and_secret(
368 0 : &self,
369 0 : ctx: &mut RequestMonitoring,
370 0 : user_info: &ComputeUserInfo,
371 0 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), errors::GetAuthInfoError> {
372 0 : use ConsoleBackend::*;
373 0 : match self {
374 0 : Console(api) => api.get_allowed_ips_and_secret(ctx, user_info).await,
375 : #[cfg(any(test, feature = "testing"))]
376 0 : Postgres(api) => api.get_allowed_ips_and_secret(ctx, user_info).await,
377 : #[cfg(test)]
378 0 : Test(api) => api.get_allowed_ips_and_secret(),
379 : }
380 0 : }
381 :
382 26 : async fn wake_compute(
383 26 : &self,
384 26 : ctx: &mut RequestMonitoring,
385 26 : user_info: &ComputeUserInfo,
386 26 : ) -> Result<CachedNodeInfo, errors::WakeComputeError> {
387 26 : use ConsoleBackend::*;
388 26 :
389 26 : match self {
390 0 : Console(api) => api.wake_compute(ctx, user_info).await,
391 : #[cfg(any(test, feature = "testing"))]
392 0 : Postgres(api) => api.wake_compute(ctx, user_info).await,
393 : #[cfg(test)]
394 26 : Test(api) => api.wake_compute(),
395 : }
396 26 : }
397 : }
398 :
399 : /// Various caches for [`console`](super).
400 : pub struct ApiCaches {
401 : /// Cache for the `wake_compute` API method.
402 : pub node_info: NodeInfoCache,
403 : /// Cache which stores project_id -> endpoint_ids mapping.
404 : pub project_info: Arc<ProjectInfoCacheImpl>,
405 : /// List of all valid endpoints.
406 : pub endpoints_cache: Arc<EndpointsCache>,
407 : }
408 :
409 : impl ApiCaches {
410 0 : pub fn new(
411 0 : wake_compute_cache_config: CacheOptions,
412 0 : project_info_cache_config: ProjectInfoCacheOptions,
413 0 : endpoint_cache_config: EndpointCacheConfig,
414 0 : ) -> Self {
415 0 : Self {
416 0 : node_info: NodeInfoCache::new(
417 0 : "node_info_cache",
418 0 : wake_compute_cache_config.size,
419 0 : wake_compute_cache_config.ttl,
420 0 : true,
421 0 : ),
422 0 : project_info: Arc::new(ProjectInfoCacheImpl::new(project_info_cache_config)),
423 0 : endpoints_cache: Arc::new(EndpointsCache::new(endpoint_cache_config)),
424 0 : }
425 0 : }
426 : }
427 :
428 : /// Various caches for [`console`](super).
429 : pub struct ApiLocks<K> {
430 : name: &'static str,
431 : node_locks: DashMap<K, Arc<DynamicLimiter>>,
432 : config: RateLimiterConfig,
433 : timeout: Duration,
434 : epoch: std::time::Duration,
435 : metrics: &'static ApiLockMetrics,
436 : }
437 :
438 0 : #[derive(Debug, thiserror::Error)]
439 : pub enum ApiLockError {
440 : #[error("timeout acquiring resource permit")]
441 : TimeoutError(#[from] tokio::time::error::Elapsed),
442 : }
443 :
444 : impl ReportableError for ApiLockError {
445 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
446 0 : match self {
447 0 : ApiLockError::TimeoutError(_) => crate::error::ErrorKind::RateLimit,
448 0 : }
449 0 : }
450 : }
451 :
452 : impl<K: Hash + Eq + Clone> ApiLocks<K> {
453 0 : pub fn new(
454 0 : name: &'static str,
455 0 : config: RateLimiterConfig,
456 0 : shards: usize,
457 0 : timeout: Duration,
458 0 : epoch: std::time::Duration,
459 0 : metrics: &'static ApiLockMetrics,
460 0 : ) -> prometheus::Result<Self> {
461 0 : Ok(Self {
462 0 : name,
463 0 : node_locks: DashMap::with_shard_amount(shards),
464 0 : config,
465 0 : timeout,
466 0 : epoch,
467 0 : metrics,
468 0 : })
469 0 : }
470 :
471 0 : pub async fn get_permit(&self, key: &K) -> Result<WakeComputePermit, ApiLockError> {
472 0 : if self.config.initial_limit == 0 {
473 0 : return Ok(WakeComputePermit {
474 0 : permit: Token::disabled(),
475 0 : });
476 0 : }
477 0 : let now = Instant::now();
478 0 : let semaphore = {
479 : // get fast path
480 0 : if let Some(semaphore) = self.node_locks.get(key) {
481 0 : semaphore.clone()
482 : } else {
483 0 : self.node_locks
484 0 : .entry(key.clone())
485 0 : .or_insert_with(|| {
486 0 : self.metrics.semaphores_registered.inc();
487 0 : DynamicLimiter::new(self.config)
488 0 : })
489 0 : .clone()
490 : }
491 : };
492 0 : let permit = semaphore.acquire_timeout(self.timeout).await;
493 :
494 0 : self.metrics
495 0 : .semaphore_acquire_seconds
496 0 : .observe(now.elapsed().as_secs_f64());
497 0 : info!("acquired permit {:?}", now.elapsed().as_secs_f64());
498 0 : Ok(WakeComputePermit { permit: permit? })
499 0 : }
500 :
501 0 : pub async fn garbage_collect_worker(&self) {
502 0 : if self.config.initial_limit == 0 {
503 0 : return;
504 0 : }
505 0 : let mut interval =
506 0 : tokio::time::interval(self.epoch / (self.node_locks.shards().len()) as u32);
507 : loop {
508 0 : for (i, shard) in self.node_locks.shards().iter().enumerate() {
509 0 : interval.tick().await;
510 : // temporary lock a single shard and then clear any semaphores that aren't currently checked out
511 : // race conditions: if strong_count == 1, there's no way that it can increase while the shard is locked
512 : // therefore releasing it is safe from race conditions
513 0 : info!(
514 : name = self.name,
515 : shard = i,
516 0 : "performing epoch reclamation on api lock"
517 : );
518 0 : let mut lock = shard.write();
519 0 : let timer = self.metrics.reclamation_lag_seconds.start_timer();
520 0 : let count = lock
521 0 : .extract_if(|_, semaphore| Arc::strong_count(semaphore.get_mut()) == 1)
522 0 : .count();
523 0 : drop(lock);
524 0 : self.metrics.semaphores_unregistered.inc_by(count as u64);
525 0 : timer.observe();
526 : }
527 : }
528 0 : }
529 : }
530 :
531 : pub struct WakeComputePermit {
532 : permit: Token,
533 : }
534 :
535 : impl WakeComputePermit {
536 0 : pub fn should_check_cache(&self) -> bool {
537 0 : !self.permit.is_disabled()
538 0 : }
539 0 : pub fn release(self, outcome: Outcome) {
540 0 : self.permit.release(outcome)
541 0 : }
542 0 : pub fn release_result<T, E>(self, res: Result<T, E>) -> Result<T, E> {
543 0 : match res {
544 0 : Ok(_) => self.release(Outcome::Success),
545 0 : Err(_) => self.release(Outcome::Overload),
546 : }
547 0 : res
548 0 : }
549 : }
|