Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 109 additions & 24 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ use serde::de::DeserializeOwned;
use serde_json::Value;
use std::cell::RefCell;
use std::io::Write;
use std::sync::Arc;
use std::time::Duration;

const RAWTREE_CLIENT_HEADER: &str = "x-rawtree-client";
const RAWTREE_CLIENT_VALUE: &str = "cli";
const RAWTREE_CLIENT_VERSION_HEADER: &str = "x-rawtree-client-version";
const RAWTREE_CLIENT_VERSION_VALUE: &str = env!("CARGO_PKG_VERSION");
const ORGANIZATION_ID_HEADER: &str = "x-rawtree-organization-id";
const CLUSTER_ID_HEADER: &str = "x-rawtree-cluster-id";
const RAWTREE_USER_AGENT: &str = concat!("rawtree-cli/", env!("CARGO_PKG_VERSION"));

#[derive(Clone)]
Expand All @@ -34,12 +37,52 @@ struct SavedCredential {
oauth_client_id: Option<String>,
}

/// How a request names an organization or cluster.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Selector {
Id(String),
Name(String),
}

impl Selector {
/// UUIDs select by ID; anything else is a name.
pub fn parse(value: &str) -> Self {
if routing::is_uuid(value) {
Self::Id(value.to_owned())
} else {
Self::Name(value.to_owned())
}
}
}

/// The organization and cluster a request acts on. The client resolves them
/// to the ID headers the API expects.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Scope {
pub organization: Option<Selector>,
pub cluster: Option<Selector>,
}

impl Scope {
pub fn new(organization: Option<&str>, cluster: Option<&str>) -> Self {
Self {
organization: organization.map(Selector::parse),
cluster: cluster.map(Selector::parse),
}
}

pub fn organization(organization: Option<&str>) -> Self {
Self::new(organization, None)
}
}

pub struct ApiClient {
pub base_url: String,
credentials: CredentialSource,
client: Client,
routing: routing::RoutingCache,
routing: Arc<routing::RoutingCache>,
deployment: Option<(String, String)>,
scope: Scope,
}

impl ApiClient {
Expand All @@ -48,8 +91,31 @@ impl ApiClient {
base_url: base_url.trim_end_matches('/').to_owned(),
credentials: CredentialSource::Explicit(token),
client: Client::new(),
routing: routing::RoutingCache::default(),
routing: Arc::default(),
deployment: None,
scope: Scope::default(),
}
}

pub fn scope(&self) -> &Scope {
&self.scope
}

pub fn has_api_key(&self) -> Result<bool> {
Ok(self.token()?.is_some_and(|token| token.starts_with("rt_")))
}

/// A view of this client whose requests act on `scope`; it shares the routing cache.
pub fn with_scope(&self, scope: Scope) -> Self {
// Settle the saved identity first, so every view of this client shares it.
let _ = self.token();
Self {
base_url: self.base_url.clone(),
credentials: self.credentials.clone(),
client: self.client.clone(),
routing: self.routing.clone(),
deployment: self.deployment.clone(),
scope,
}
}

Expand Down Expand Up @@ -89,8 +155,9 @@ impl ApiClient {
base_url: self.base_url.clone(),
credentials: self.credentials.clone(),
client: self.client.clone(),
routing: routing::RoutingCache::default(),
routing: Arc::default(),
deployment: self.deployment.clone(),
scope: self.scope.clone(),
})
}

Expand Down Expand Up @@ -204,17 +271,13 @@ impl ApiClient {
}

pub fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let url = reqwest::Url::parse(&format!("{}{}", self.base_url, path))?;
let organization = url.query_pairs().find(|(key, _)| key == "organization");
let value: Value = if url.path() == "/v1/clusters"
&& self.has_user_credential()?
&& self.deployment.is_none()
{
self.discover_clusters(organization.as_ref().map(|(_, name)| name.as_ref()), None)?
} else {
let req = self.routed_request(reqwest::Method::GET, path)?;
handle_response(req.send().context("failed to connect to server")?)?
};
let value: Value =
if path == "/v1/clusters" && self.has_user_credential()? && self.deployment.is_none() {
self.discover_clusters(self.scope.organization.as_ref(), None)?
} else {
let req = self.routed_request(reqwest::Method::GET, path)?;
handle_response(req.send().context("failed to connect to server")?)?
};
self.remember_routing_metadata(path, &value);
serde_json::from_value(value).context("failed to parse server response")
}
Expand Down Expand Up @@ -284,18 +347,40 @@ fn check_status(resp: Response) -> Result<()> {
Err(format_server_error(&text, status.as_u16()))
}

/// A non-success response from the API.
#[derive(Debug)]
pub struct ServerError {
pub status: u16,
message: String,
}

impl ServerError {
/// The server error behind `error`, if one caused it.
pub fn of(error: &anyhow::Error) -> Option<&Self> {
error.chain().find_map(|cause| cause.downcast_ref())
}
}

impl std::fmt::Display for ServerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Server error ({}): {}", self.status, self.message)
}
}

impl std::error::Error for ServerError {}

fn format_server_error(body: &str, status: u16) -> anyhow::Error {
if let Ok(json) = serde_json::from_str::<Value>(body) {
let message = json["message"].as_str().unwrap_or("Unknown error");
let hint = json["hint"].as_str().unwrap_or("");
if hint.is_empty() {
anyhow::anyhow!("Server error ({}): {}", status, message)
} else {
anyhow::anyhow!("Server error ({}): {}\nHint: {}", status, message, hint)
let message = match serde_json::from_str::<Value>(body) {
Ok(json) => {
let message = json["message"].as_str().unwrap_or("Unknown error");
match json["hint"].as_str().unwrap_or("") {
"" => message.to_owned(),
hint => format!("{message}\nHint: {hint}"),
}
}
} else {
anyhow::anyhow!("Server error ({}): {}", status, body)
}
Err(_) => body.to_owned(),
};
ServerError { status, message }.into()
}

#[cfg(test)]
Expand Down
54 changes: 14 additions & 40 deletions src/client/discovery.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{
handle_response,
regions::Region,
routing::{before_deadline, valid_routing},
ApiClient,
routing::{before_deadline, valid_routing, with_scope_headers},
ApiClient, Selector,
};
use anyhow::{Context, Result};
use reqwest::{blocking::RequestBuilder, Method, StatusCode};
Expand Down Expand Up @@ -30,7 +30,7 @@ struct DeploymentTarget {
}

struct OrganizationCatalog {
name: String,
id: String,
regions: HashMap<String, Region>,
deployments: Vec<DeploymentTarget>,
}
Expand Down Expand Up @@ -103,17 +103,6 @@ enum CatalogAuthority {
OwningDeployment,
}

#[derive(Deserialize)]
struct Organization {
organization_id: String,
name: String,
}

#[derive(Deserialize)]
struct Organizations {
organizations: Vec<Organization>,
}

impl ApiClient {
pub(super) fn has_user_credential(&self) -> Result<bool> {
Ok(self
Expand All @@ -125,25 +114,13 @@ impl ApiClient {
/// Discover enabled deployments concurrently, retaining explicit partial-catalog metadata.
pub(super) fn discover_clusters(
&self,
organization: Option<&str>,
organization: Option<&Selector>,
deadline: Option<Instant>,
) -> Result<Value> {
let organizations: Organizations = handle_response(
before_deadline(
self.unrouted_request(Method::GET, "/v1/organizations")?,
deadline,
)?
.send()?,
)?;
let selected: Vec<_> = organizations
.organizations
.into_iter()
.filter(|item| organization.is_none_or(|name| item.name == name))
.collect();
anyhow::ensure!(
organization.is_none() || !selected.is_empty(),
"Organization not found."
);
let selected: Vec<_> = match organization {
Some(selector) => vec![self.find_organization(selector, deadline)?],
None => self.organizations(deadline)?,
};
let mut catalogs = Vec::new();
for owner in selected {
let regions = self.regions_for_organization(&owner.organization_id, deadline)?;
Expand All @@ -168,7 +145,7 @@ impl ApiClient {
}
}
catalogs.push(OrganizationCatalog {
name: owner.name,
id: owner.organization_id,
regions: regions
.regions
.into_iter()
Expand Down Expand Up @@ -197,14 +174,11 @@ impl ApiClient {
let requests = targets
.iter()
.map(|(catalog, target)| {
self.deployment_request(
Method::GET,
&format!(
"/v1/clusters?organization={}",
urlencoding::encode(&catalog.name)
),
target.routing.as_ref(),
)
Ok(with_scope_headers(
self.deployment_request(Method::GET, "/v1/clusters", target.routing.as_ref())?,
Some(&catalog.id),
None,
))
})
.collect::<Result<Vec<_>>>()?;
let responses = load_catalogs(requests, lookup_deadline)?;
Expand Down
20 changes: 14 additions & 6 deletions src/client/regions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use super::{handle_response, routing, ApiClient};
use super::{handle_response, routing, ApiClient, Scope, Selector};
use anyhow::{Context, Result};
use reqwest::Method;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Instant;

#[derive(Deserialize, Serialize)]
Expand All @@ -20,7 +21,7 @@ pub struct Regions {
}

impl ApiClient {
pub fn list_regions(&self, organization: &str) -> Result<Regions> {
pub fn list_regions(&self, organization: &Selector) -> Result<Regions> {
let id = self.organization_id(organization)?;
self.regions_for_organization(&id, None)
}
Expand All @@ -36,17 +37,21 @@ impl ApiClient {
handle_response(routing::before_deadline(request, deadline)?.send()?)
}

/// Scope pre-creation size discovery to the selected region without mutating this client.
pub fn for_region(&self, organization: Option<&str>, region_id: &str) -> Result<Self> {
/// An unscoped client for pre-creation size discovery in a region of this
/// client's organization.
pub fn for_region(&self, region_id: &str) -> Result<Self> {
anyhow::ensure!(
!self
.token()?
.as_deref()
.is_some_and(|token| token.starts_with("rt_")),
"Region selection requires a user credential. Run `rtree login`."
);
let organization =
organization.context("Choose an organization with --org when selecting a region.")?;
let organization = self
.scope
.organization
.as_ref()
.context("Choose an organization with --org when selecting a region.")?;
let region = self
.list_regions(organization)?
.regions
Expand All @@ -61,7 +66,10 @@ impl ApiClient {
"The selected region is not ready for cluster creation. Choose another region.",
)?;
let mut client = self.fork()?;
client.routing =
Arc::new(routing::RoutingCache::default().with_organizations_of(&self.routing));
client.deployment = Some((deployment, region.cloud_region));
client.scope = Scope::default();
Ok(client)
}
}
Loading