LCOV - code coverage report
Current view: top level - proxy/src/console - messages.rs (source / functions) Coverage Total Hit
Test: 40847ed574e0fcb4c245504ae69f84bc64a0e184.info Lines: 62.0 % 184 114
Test Date: 2024-06-26 19:30:22 Functions: 23.3 % 163 38

            Line data    Source code
       1              : use measured::FixedCardinalityLabel;
       2              : use serde::{Deserialize, Serialize};
       3              : use std::fmt::{self, Display};
       4              : 
       5              : use crate::auth::IpPattern;
       6              : 
       7              : use crate::intern::{BranchIdInt, EndpointIdInt, ProjectIdInt};
       8              : use crate::proxy::retry::CouldRetry;
       9              : 
      10              : /// Generic error response with human-readable description.
      11              : /// Note that we can't always present it to user as is.
      12            0 : #[derive(Debug, Deserialize)]
      13              : pub struct ConsoleError {
      14              :     pub error: Box<str>,
      15              :     #[serde(skip)]
      16              :     pub http_status_code: http::StatusCode,
      17              :     pub status: Option<Status>,
      18              : }
      19              : 
      20              : impl ConsoleError {
      21            6 :     pub fn get_reason(&self) -> Reason {
      22            6 :         self.status
      23            6 :             .as_ref()
      24            6 :             .and_then(|s| s.details.error_info.as_ref())
      25            6 :             .map(|e| e.reason)
      26            6 :             .unwrap_or(Reason::Unknown)
      27            6 :     }
      28            0 :     pub fn get_user_facing_message(&self) -> String {
      29            0 :         use super::provider::errors::REQUEST_FAILED;
      30            0 :         self.status
      31            0 :             .as_ref()
      32            0 :             .and_then(|s| s.details.user_facing_message.as_ref())
      33            0 :             .map(|m| m.message.clone().into())
      34            0 :             .unwrap_or_else(|| {
      35            0 :                 // Ask @neondatabase/control-plane for review before adding more.
      36            0 :                 match self.http_status_code {
      37              :                     http::StatusCode::NOT_FOUND => {
      38              :                         // Status 404: failed to get a project-related resource.
      39            0 :                         format!("{REQUEST_FAILED}: endpoint cannot be found")
      40              :                     }
      41              :                     http::StatusCode::NOT_ACCEPTABLE => {
      42              :                         // Status 406: endpoint is disabled (we don't allow connections).
      43            0 :                         format!("{REQUEST_FAILED}: endpoint is disabled")
      44              :                     }
      45              :                     http::StatusCode::LOCKED | http::StatusCode::UNPROCESSABLE_ENTITY => {
      46              :                         // Status 423: project might be in maintenance mode (or bad state), or quotas exceeded.
      47            0 :                         format!("{REQUEST_FAILED}: endpoint is temporarily unavailable. Check your quotas and/or contact our support.")
      48              :                     }
      49            0 :                     _ => REQUEST_FAILED.to_owned(),
      50              :                 }
      51            0 :             })
      52            0 :     }
      53              : }
      54              : 
      55              : impl Display for ConsoleError {
      56            0 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
      57            0 :         let msg = self
      58            0 :             .status
      59            0 :             .as_ref()
      60            0 :             .and_then(|s| s.details.user_facing_message.as_ref())
      61            0 :             .map(|m| m.message.as_ref())
      62            0 :             .unwrap_or_else(|| &self.error);
      63            0 :         write!(f, "{}", msg)
      64            0 :     }
      65              : }
      66              : 
      67              : impl CouldRetry for ConsoleError {
      68           12 :     fn could_retry(&self) -> bool {
      69              :         // If the error message does not have a status,
      70              :         // the error is unknown and probably should not retry automatically
      71           12 :         let Some(status) = &self.status else {
      72            4 :             return false;
      73              :         };
      74              : 
      75              :         // retry if the retry info is set.
      76            8 :         if status.details.retry_info.is_some() {
      77            8 :             return true;
      78            0 :         }
      79            0 : 
      80            0 :         // if no retry info set, attempt to use the error code to guess the retry state.
      81            0 :         let reason = status
      82            0 :             .details
      83            0 :             .error_info
      84            0 :             .map_or(Reason::Unknown, |e| e.reason);
      85            0 :         match reason {
      86              :             // not a transitive error
      87            0 :             Reason::RoleProtected => false,
      88              :             // on retry, it will still not be found
      89              :             Reason::ResourceNotFound
      90              :             | Reason::ProjectNotFound
      91              :             | Reason::EndpointNotFound
      92            0 :             | Reason::BranchNotFound => false,
      93              :             // we were asked to go away
      94              :             Reason::RateLimitExceeded
      95              :             | Reason::NonDefaultBranchComputeTimeExceeded
      96              :             | Reason::ActiveTimeQuotaExceeded
      97              :             | Reason::ComputeTimeQuotaExceeded
      98              :             | Reason::WrittenDataQuotaExceeded
      99              :             | Reason::DataTransferQuotaExceeded
     100            0 :             | Reason::LogicalSizeQuotaExceeded => false,
     101              :             // transitive error. control plane is currently busy
     102              :             // but might be ready soon
     103            0 :             Reason::RunningOperations => true,
     104            0 :             Reason::ConcurrencyLimitReached => true,
     105            0 :             Reason::LockAlreadyTaken => true,
     106              :             // unknown error. better not retry it.
     107            0 :             Reason::Unknown => false,
     108              :         }
     109           12 :     }
     110              : }
     111              : 
     112            0 : #[derive(Debug, Deserialize)]
     113              : pub struct Status {
     114              :     pub code: Box<str>,
     115              :     pub message: Box<str>,
     116              :     pub details: Details,
     117              : }
     118              : 
     119            0 : #[derive(Debug, Deserialize)]
     120              : pub struct Details {
     121              :     pub error_info: Option<ErrorInfo>,
     122              :     pub retry_info: Option<RetryInfo>,
     123              :     pub user_facing_message: Option<UserFacingMessage>,
     124              : }
     125              : 
     126            0 : #[derive(Copy, Clone, Debug, Deserialize)]
     127              : pub struct ErrorInfo {
     128              :     pub reason: Reason,
     129              :     // Schema could also have `metadata` field, but it's not structured. Skip it for now.
     130              : }
     131              : 
     132            0 : #[derive(Clone, Copy, Debug, Deserialize, Default)]
     133              : pub enum Reason {
     134              :     /// RoleProtected indicates that the role is protected and the attempted operation is not permitted on protected roles.
     135              :     #[serde(rename = "ROLE_PROTECTED")]
     136              :     RoleProtected,
     137              :     /// ResourceNotFound indicates that a resource (project, endpoint, branch, etc.) wasn't found,
     138              :     /// usually due to the provided ID not being correct or because the subject doesn't have enough permissions to
     139              :     /// access the requested resource.
     140              :     /// Prefer a more specific reason if possible, e.g., ProjectNotFound, EndpointNotFound, etc.
     141              :     #[serde(rename = "RESOURCE_NOT_FOUND")]
     142              :     ResourceNotFound,
     143              :     /// ProjectNotFound indicates that the project wasn't found, usually due to the provided ID not being correct,
     144              :     /// or that the subject doesn't have enough permissions to access the requested project.
     145              :     #[serde(rename = "PROJECT_NOT_FOUND")]
     146              :     ProjectNotFound,
     147              :     /// EndpointNotFound indicates that the endpoint wasn't found, usually due to the provided ID not being correct,
     148              :     /// or that the subject doesn't have enough permissions to access the requested endpoint.
     149              :     #[serde(rename = "ENDPOINT_NOT_FOUND")]
     150              :     EndpointNotFound,
     151              :     /// BranchNotFound indicates that the branch wasn't found, usually due to the provided ID not being correct,
     152              :     /// or that the subject doesn't have enough permissions to access the requested branch.
     153              :     #[serde(rename = "BRANCH_NOT_FOUND")]
     154              :     BranchNotFound,
     155              :     /// RateLimitExceeded indicates that the rate limit for the operation has been exceeded.
     156              :     #[serde(rename = "RATE_LIMIT_EXCEEDED")]
     157              :     RateLimitExceeded,
     158              :     /// NonDefaultBranchComputeTimeExceeded indicates that the compute time quota of non-default branches has been
     159              :     /// exceeded.
     160              :     #[serde(rename = "NON_PRIMARY_BRANCH_COMPUTE_TIME_EXCEEDED")]
     161              :     NonDefaultBranchComputeTimeExceeded,
     162              :     /// ActiveTimeQuotaExceeded indicates that the active time quota was exceeded.
     163              :     #[serde(rename = "ACTIVE_TIME_QUOTA_EXCEEDED")]
     164              :     ActiveTimeQuotaExceeded,
     165              :     /// ComputeTimeQuotaExceeded indicates that the compute time quota was exceeded.
     166              :     #[serde(rename = "COMPUTE_TIME_QUOTA_EXCEEDED")]
     167              :     ComputeTimeQuotaExceeded,
     168              :     /// WrittenDataQuotaExceeded indicates that the written data quota was exceeded.
     169              :     #[serde(rename = "WRITTEN_DATA_QUOTA_EXCEEDED")]
     170              :     WrittenDataQuotaExceeded,
     171              :     /// DataTransferQuotaExceeded indicates that the data transfer quota was exceeded.
     172              :     #[serde(rename = "DATA_TRANSFER_QUOTA_EXCEEDED")]
     173              :     DataTransferQuotaExceeded,
     174              :     /// LogicalSizeQuotaExceeded indicates that the logical size quota was exceeded.
     175              :     #[serde(rename = "LOGICAL_SIZE_QUOTA_EXCEEDED")]
     176              :     LogicalSizeQuotaExceeded,
     177              :     /// RunningOperations indicates that the project already has some running operations
     178              :     /// and scheduling of new ones is prohibited.
     179              :     #[serde(rename = "RUNNING_OPERATIONS")]
     180              :     RunningOperations,
     181              :     /// ConcurrencyLimitReached indicates that the concurrency limit for an action was reached.
     182              :     #[serde(rename = "CONCURRENCY_LIMIT_REACHED")]
     183              :     ConcurrencyLimitReached,
     184              :     /// LockAlreadyTaken indicates that the we attempted to take a lock that was already taken.
     185              :     #[serde(rename = "LOCK_ALREADY_TAKEN")]
     186              :     LockAlreadyTaken,
     187              :     #[default]
     188              :     #[serde(other)]
     189              :     Unknown,
     190              : }
     191              : 
     192              : impl Reason {
     193            0 :     pub fn is_not_found(&self) -> bool {
     194            0 :         matches!(
     195            0 :             self,
     196              :             Reason::ResourceNotFound
     197              :                 | Reason::ProjectNotFound
     198              :                 | Reason::EndpointNotFound
     199              :                 | Reason::BranchNotFound
     200              :         )
     201            0 :     }
     202              : }
     203              : 
     204            0 : #[derive(Copy, Clone, Debug, Deserialize)]
     205              : pub struct RetryInfo {
     206              :     pub retry_delay_ms: u64,
     207              : }
     208              : 
     209            0 : #[derive(Debug, Deserialize)]
     210              : pub struct UserFacingMessage {
     211              :     pub message: Box<str>,
     212              : }
     213              : 
     214              : /// Response which holds client's auth secret, e.g. [`crate::scram::ServerSecret`].
     215              : /// Returned by the `/proxy_get_role_secret` API method.
     216           18 : #[derive(Deserialize)]
     217              : pub struct GetRoleSecret {
     218              :     pub role_secret: Box<str>,
     219              :     pub allowed_ips: Option<Vec<IpPattern>>,
     220              :     pub project_id: Option<ProjectIdInt>,
     221              : }
     222              : 
     223              : // Manually implement debug to omit sensitive info.
     224              : impl fmt::Debug for GetRoleSecret {
     225            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     226            0 :         f.debug_struct("GetRoleSecret").finish_non_exhaustive()
     227            0 :     }
     228              : }
     229              : 
     230              : /// Response which holds compute node's `host:port` pair.
     231              : /// Returned by the `/proxy_wake_compute` API method.
     232            6 : #[derive(Debug, Deserialize)]
     233              : pub struct WakeCompute {
     234              :     pub address: Box<str>,
     235              :     pub aux: MetricsAuxInfo,
     236              : }
     237              : 
     238              : /// Async response which concludes the link auth flow.
     239              : /// Also known as `kickResponse` in the console.
     240            8 : #[derive(Debug, Deserialize)]
     241              : pub struct KickSession<'a> {
     242              :     /// Session ID is assigned by the proxy.
     243              :     pub session_id: &'a str,
     244              : 
     245              :     /// Compute node connection params.
     246              :     #[serde(deserialize_with = "KickSession::parse_db_info")]
     247              :     pub result: DatabaseInfo,
     248              : }
     249              : 
     250              : impl KickSession<'_> {
     251            2 :     fn parse_db_info<'de, D>(des: D) -> Result<DatabaseInfo, D::Error>
     252            2 :     where
     253            2 :         D: serde::Deserializer<'de>,
     254            2 :     {
     255            4 :         #[derive(Deserialize)]
     256            2 :         enum Wrapper {
     257            2 :             // Currently, console only reports `Success`.
     258            2 :             // `Failure(String)` used to be here... RIP.
     259            2 :             Success(DatabaseInfo),
     260            2 :         }
     261            2 : 
     262            2 :         Wrapper::deserialize(des).map(|x| match x {
     263            2 :             Wrapper::Success(info) => info,
     264            2 :         })
     265            2 :     }
     266              : }
     267              : 
     268              : /// Compute node connection params.
     269           56 : #[derive(Deserialize)]
     270              : pub struct DatabaseInfo {
     271              :     pub host: Box<str>,
     272              :     pub port: u16,
     273              :     pub dbname: Box<str>,
     274              :     pub user: Box<str>,
     275              :     /// Console always provides a password, but it might
     276              :     /// be inconvenient for debug with local PG instance.
     277              :     pub password: Option<Box<str>>,
     278              :     pub aux: MetricsAuxInfo,
     279              : }
     280              : 
     281              : // Manually implement debug to omit sensitive info.
     282              : impl fmt::Debug for DatabaseInfo {
     283            0 :     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     284            0 :         f.debug_struct("DatabaseInfo")
     285            0 :             .field("host", &self.host)
     286            0 :             .field("port", &self.port)
     287            0 :             .field("dbname", &self.dbname)
     288            0 :             .field("user", &self.user)
     289            0 :             .finish_non_exhaustive()
     290            0 :     }
     291              : }
     292              : 
     293              : /// Various labels for prometheus metrics.
     294              : /// Also known as `ProxyMetricsAuxInfo` in the console.
     295           50 : #[derive(Debug, Deserialize, Clone)]
     296              : pub struct MetricsAuxInfo {
     297              :     pub endpoint_id: EndpointIdInt,
     298              :     pub project_id: ProjectIdInt,
     299              :     pub branch_id: BranchIdInt,
     300              :     #[serde(default)]
     301              :     pub cold_start_info: ColdStartInfo,
     302              : }
     303              : 
     304           20 : #[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, FixedCardinalityLabel)]
     305              : #[serde(rename_all = "snake_case")]
     306              : pub enum ColdStartInfo {
     307              :     #[default]
     308              :     Unknown,
     309              :     /// Compute was already running
     310              :     Warm,
     311              :     #[serde(rename = "pool_hit")]
     312              :     #[label(rename = "pool_hit")]
     313              :     /// Compute was not running but there was an available VM
     314              :     VmPoolHit,
     315              :     #[serde(rename = "pool_miss")]
     316              :     #[label(rename = "pool_miss")]
     317              :     /// Compute was not running and there were no VMs available
     318              :     VmPoolMiss,
     319              : 
     320              :     // not provided by control plane
     321              :     /// Connection available from HTTP pool
     322              :     HttpPoolHit,
     323              :     /// Cached connection info
     324              :     WarmCached,
     325              : }
     326              : 
     327              : impl ColdStartInfo {
     328            0 :     pub fn as_str(&self) -> &'static str {
     329            0 :         match self {
     330            0 :             ColdStartInfo::Unknown => "unknown",
     331            0 :             ColdStartInfo::Warm => "warm",
     332            0 :             ColdStartInfo::VmPoolHit => "pool_hit",
     333            0 :             ColdStartInfo::VmPoolMiss => "pool_miss",
     334            0 :             ColdStartInfo::HttpPoolHit => "http_pool_hit",
     335            0 :             ColdStartInfo::WarmCached => "warm_cached",
     336              :         }
     337            0 :     }
     338              : }
     339              : 
     340              : #[cfg(test)]
     341              : mod tests {
     342              :     use super::*;
     343              :     use serde_json::json;
     344              : 
     345           10 :     fn dummy_aux() -> serde_json::Value {
     346           10 :         json!({
     347           10 :             "endpoint_id": "endpoint",
     348           10 :             "project_id": "project",
     349           10 :             "branch_id": "branch",
     350           10 :             "cold_start_info": "unknown",
     351           10 :         })
     352           10 :     }
     353              : 
     354              :     #[test]
     355            2 :     fn parse_kick_session() -> anyhow::Result<()> {
     356            2 :         // This is what the console's kickResponse looks like.
     357            2 :         let json = json!({
     358            2 :             "session_id": "deadbeef",
     359            2 :             "result": {
     360            2 :                 "Success": {
     361            2 :                     "host": "localhost",
     362            2 :                     "port": 5432,
     363            2 :                     "dbname": "postgres",
     364            2 :                     "user": "john_doe",
     365            2 :                     "password": "password",
     366            2 :                     "aux": dummy_aux(),
     367            2 :                 }
     368            2 :             }
     369            2 :         });
     370            2 :         let _: KickSession = serde_json::from_str(&json.to_string())?;
     371              : 
     372            2 :         Ok(())
     373            2 :     }
     374              : 
     375              :     #[test]
     376            2 :     fn parse_db_info() -> anyhow::Result<()> {
     377              :         // with password
     378            2 :         let _: DatabaseInfo = serde_json::from_value(json!({
     379            2 :             "host": "localhost",
     380            2 :             "port": 5432,
     381            2 :             "dbname": "postgres",
     382            2 :             "user": "john_doe",
     383            2 :             "password": "password",
     384            2 :             "aux": dummy_aux(),
     385            2 :         }))?;
     386              : 
     387              :         // without password
     388            2 :         let _: DatabaseInfo = serde_json::from_value(json!({
     389            2 :             "host": "localhost",
     390            2 :             "port": 5432,
     391            2 :             "dbname": "postgres",
     392            2 :             "user": "john_doe",
     393            2 :             "aux": dummy_aux(),
     394            2 :         }))?;
     395              : 
     396              :         // new field (forward compatibility)
     397            2 :         let _: DatabaseInfo = serde_json::from_value(json!({
     398            2 :             "host": "localhost",
     399            2 :             "port": 5432,
     400            2 :             "dbname": "postgres",
     401            2 :             "user": "john_doe",
     402            2 :             "project": "hello_world",
     403            2 :             "N.E.W": "forward compatibility check",
     404            2 :             "aux": dummy_aux(),
     405            2 :         }))?;
     406              : 
     407            2 :         Ok(())
     408            2 :     }
     409              : 
     410              :     #[test]
     411            2 :     fn parse_wake_compute() -> anyhow::Result<()> {
     412            2 :         let json = json!({
     413            2 :             "address": "0.0.0.0",
     414            2 :             "aux": dummy_aux(),
     415            2 :         });
     416            2 :         let _: WakeCompute = serde_json::from_str(&json.to_string())?;
     417            2 :         Ok(())
     418            2 :     }
     419              : 
     420              :     #[test]
     421            2 :     fn parse_get_role_secret() -> anyhow::Result<()> {
     422            2 :         // Empty `allowed_ips` field.
     423            2 :         let json = json!({
     424            2 :             "role_secret": "secret",
     425            2 :         });
     426            2 :         let _: GetRoleSecret = serde_json::from_str(&json.to_string())?;
     427            2 :         let json = json!({
     428            2 :             "role_secret": "secret",
     429            2 :             "allowed_ips": ["8.8.8.8"],
     430            2 :         });
     431            2 :         let _: GetRoleSecret = serde_json::from_str(&json.to_string())?;
     432            2 :         let json = json!({
     433            2 :             "role_secret": "secret",
     434            2 :             "allowed_ips": ["8.8.8.8"],
     435            2 :             "project_id": "project",
     436            2 :         });
     437            2 :         let _: GetRoleSecret = serde_json::from_str(&json.to_string())?;
     438              : 
     439            2 :         Ok(())
     440            2 :     }
     441              : }
        

Generated by: LCOV version 2.1-beta