From 046f9f28eddf809f3b82e9cd3dfb683993cddcda Mon Sep 17 00:00:00 2001 From: jordiori Date: Wed, 25 Nov 2026 16:59:16 +0100 Subject: [PATCH 1/7] Select organization and cluster with ID headers in the CLI Resolve organization and cluster names to IDs in the client and send them as X-RawTree-Organization-Id and X-RawTree-Cluster-Id instead of query params. Commands pass a typed Scope, organization paths use IDs, and the saved defaults also store IDs so requests skip the name lookups. --- src/client.rs | 106 ++- src/client/discovery.rs | 57 +- src/client/regions.rs | 3 + src/client/routing.rs | 474 +++++++++---- src/client/routing_tests.rs | 437 +++++++++--- src/commands/auth.rs | 89 ++- src/commands/auth/selection.rs | 27 +- src/commands/cluster.rs | 213 +++--- src/commands/database.rs | 55 +- src/commands/federation_rule.rs | 15 +- src/commands/format.rs | 12 +- src/commands/insert.rs | 63 +- src/commands/keys.rs | 14 +- src/commands/logs.rs | 8 +- src/commands/organization.rs | 138 ++-- src/commands/query.rs | 6 +- src/commands/table.rs | 45 +- src/commands/workflow/mod.rs | 116 ++-- src/commands/workflow/sink.rs | 29 +- src/config.rs | 63 ++ src/main.rs | 1106 +++++++++++++++++-------------- src/org.rs | 107 +-- tests/api_contracts.rs | 271 ++++++-- tests/api_key_expiration.rs | 20 +- tests/api_key_login.rs | 40 +- tests/browser_login.rs | 17 +- tests/common/mod.rs | 26 + tests/federation.rs | 32 +- tests/format.rs | 21 +- tests/oauth_login.rs | 26 +- tests/oauth_refresh.rs | 12 +- tests/region_creation.rs | 2 +- tests/regional_discovery.rs | 4 +- tests/sql_input.rs | 4 +- tests/storage_contracts.rs | 20 +- 35 files changed, 2261 insertions(+), 1417 deletions(-) diff --git a/src/client.rs b/src/client.rs index 4ac708d..6014951 100644 --- a/src/client.rs +++ b/src/client.rs @@ -2,6 +2,7 @@ mod discovery; pub(crate) use discovery::UnavailableRegion; mod regions; mod routing; +pub(crate) use routing::is_uuid; #[cfg(test)] mod routing_tests; @@ -14,12 +15,16 @@ use serde::de::DeserializeOwned; use serde_json::Value; use std::cell::RefCell; use std::io::Write; +use std::sync::atomic::Ordering; +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)] @@ -34,12 +39,45 @@ struct SavedCredential { oauth_client_id: Option, } +/// The organization and cluster a request acts on, as the user typed them: +/// names or IDs. The client resolves them to the ID headers the API expects. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Scope { + pub organization: Option, + pub cluster: Option, +} + +impl Scope { + pub fn new(organization: Option<&str>, cluster: Option<&str>) -> Self { + Self { + organization: organization.map(str::to_owned), + cluster: cluster.map(str::to_owned), + } + } + + pub fn organization(organization: Option<&str>) -> Self { + Self::new(organization, None) + } +} + +/// IDs saved in the config for the default organization and cluster, each with +/// the name it was saved under. A scope that names the same organization or +/// cluster uses the saved ID instead of looking it up. Only set them for +/// selections that came from the config, never for flags or environment. +#[derive(Clone, Debug, Default)] +pub struct SavedIds { + pub organization: Option<(String, String)>, + pub cluster: Option<(String, String)>, +} + pub struct ApiClient { pub base_url: String, credentials: CredentialSource, client: Client, - routing: routing::RoutingCache, + routing: Arc, deployment: Option<(String, String)>, + scope: Scope, + saved: SavedIds, } impl ApiClient { @@ -48,8 +86,50 @@ 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(), + saved: SavedIds::default(), + } + } + + pub fn with_saved_ids(mut self, saved: SavedIds) -> Self { + self.saved = saved; + self + } + + /// Whether any request used an ID from the config instead of resolving a name. + pub fn used_saved_ids(&self) -> bool { + self.routing.saved_id_used.load(Ordering::Relaxed) + } + + /// The saved ID for `name`, when it is the organization the config saved. + pub fn saved_organization_id(&self, name: &str) -> Option { + let (_, id) = self + .saved + .organization + .as_ref() + .filter(|(saved, _)| saved == name)?; + self.routing.saved_id_used.store(true, Ordering::Relaxed); + Some(id.clone()) + } + + pub fn has_api_key(&self) -> Result { + 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, + saved: self.saved.clone(), } } @@ -89,8 +169,10 @@ 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(), + saved: self.saved.clone(), }) } @@ -204,17 +286,13 @@ impl ApiClient { } pub fn get(&self, path: &str) -> Result { - 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_deref(), 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") } diff --git a/src/client/discovery.rs b/src/client/discovery.rs index 782e50c..d171b3d 100644 --- a/src/client/discovery.rs +++ b/src/client/discovery.rs @@ -1,7 +1,7 @@ use super::{ handle_response, regions::Region, - routing::{before_deadline, valid_routing}, + routing::{before_deadline, is_uuid, valid_routing, with_scope_headers, Organization}, ApiClient, }; use anyhow::{Context, Result}; @@ -30,7 +30,7 @@ struct DeploymentTarget { } struct OrganizationCatalog { - name: String, + id: String, regions: HashMap, deployments: Vec, } @@ -103,17 +103,6 @@ enum CatalogAuthority { OwningDeployment, } -#[derive(Deserialize)] -struct Organization { - organization_id: String, - name: String, -} - -#[derive(Deserialize)] -struct Organizations { - organizations: Vec, -} - impl ApiClient { pub(super) fn has_user_credential(&self) -> Result { Ok(self @@ -128,18 +117,21 @@ impl ApiClient { organization: Option<&str>, deadline: Option, ) -> Result { - 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(); + let selected: Vec<_> = match organization { + Some(id) if is_uuid(id) => vec![Organization { + organization_id: id.to_owned(), + name: id.to_owned(), + }], + _ => self + .organizations(deadline)? + .into_iter() + .filter(|item| { + organization.is_none_or(|selected| { + item.name == selected || item.organization_id == selected + }) + }) + .collect(), + }; anyhow::ensure!( organization.is_none() || !selected.is_empty(), "Organization not found." @@ -168,7 +160,7 @@ impl ApiClient { } } catalogs.push(OrganizationCatalog { - name: owner.name, + id: owner.organization_id, regions: regions .regions .into_iter() @@ -197,14 +189,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::>>()?; let responses = load_catalogs(requests, lookup_deadline)?; diff --git a/src/client/regions.rs b/src/client/regions.rs index 090bfe5..bfe824e 100644 --- a/src/client/regions.rs +++ b/src/client/regions.rs @@ -2,6 +2,7 @@ use super::{handle_response, routing, ApiClient}; use anyhow::{Context, Result}; use reqwest::Method; use serde::{Deserialize, Serialize}; +use std::sync::Arc; use std::time::Instant; #[derive(Deserialize, Serialize)] @@ -61,6 +62,8 @@ 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)); Ok(client) } diff --git a/src/client/routing.rs b/src/client/routing.rs index 09eeb20..d05f218 100644 --- a/src/client/routing.rs +++ b/src/client/routing.rs @@ -1,21 +1,27 @@ -use super::{discovery::UnavailableRegion, handle_response, ApiClient}; +use super::{ + discovery::UnavailableRegion, handle_response, ApiClient, CLUSTER_ID_HEADER, + ORGANIZATION_ID_HEADER, +}; use anyhow::{Context, Result}; use reqwest::{blocking::RequestBuilder, Method, Url}; use serde::Deserialize; use std::{ - cell::RefCell, collections::HashMap, + sync::{ + atomic::{AtomicBool, Ordering}, + Mutex, + }, time::{Duration, Instant}, }; #[derive(Clone, Deserialize)] -struct Organization { - organization_id: String, - name: String, +pub(super) struct Organization { + pub(super) organization_id: String, + pub(super) name: String, } #[derive(Deserialize)] -struct Organizations { - organizations: Vec, +pub(super) struct Organizations { + pub(super) organizations: Vec, } #[derive(Clone, Deserialize)] struct Cluster { @@ -35,52 +41,150 @@ struct Clusters { #[derive(Default)] pub(super) struct RoutingCache { - organizations: RefCell)>>, - clusters: RefCell>, + organizations: Mutex)>>, + clusters: Mutex>, + bound_cluster: Mutex>, + pub(super) saved_id_used: AtomicBool, +} + +impl RoutingCache { + pub(super) fn store_organizations(&self, organizations: Vec) { + *self.organizations.lock().unwrap() = Some((Instant::now(), organizations)); + } + + pub(super) fn with_organizations_of(&self, other: &RoutingCache) -> RoutingCache { + let cache = RoutingCache::default(); + *cache.organizations.lock().unwrap() = other.organizations.lock().unwrap().clone(); + cache + } +} + +enum ClusterSelector { + Id(String), + Name(String), +} + +enum OrganizationSelector { + Id(String), + Name(String), +} + +struct Selectors { + organization: Option, + cluster: Option, + /// The cluster is addressed by the URL path, so no cluster header is sent. + cluster_in_path: bool, +} + +#[derive(Default)] +pub(super) struct ResolvedScope { + organization_id: Option, + cluster_id: Option, + deployment: Option<(String, String)>, +} + +pub(crate) fn is_uuid(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(index, byte)| match index { + 8 | 13 | 18 | 23 => byte == b'-', + _ => byte.is_ascii_hexdigit(), + }) +} + +fn organization_selector(value: &str) -> OrganizationSelector { + if is_uuid(value) { + OrganizationSelector::Id(value.to_owned()) + } else { + OrganizationSelector::Name(value.to_owned()) + } +} + +pub(super) fn with_scope_headers( + request: RequestBuilder, + organization_id: Option<&str>, + cluster_id: Option<&str>, +) -> RequestBuilder { + let request = match organization_id { + Some(id) => request.header(ORGANIZATION_ID_HEADER, id), + None => request, + }; + match cluster_id { + Some(id) => request.header(CLUSTER_ID_HEADER, id), + None => request, + } } impl ApiClient { pub(super) fn remember_routing_metadata(&self, path: &str, value: &serde_json::Value) { - let Ok(url) = Url::parse(&format!("{}{}", self.base_url, path)) else { - return; - }; - if url.path() == "/v1/organizations" { + if path == "/v1/organizations" { if let Ok(response) = serde_json::from_value::(value.clone()) { - *self.routing.organizations.borrow_mut() = - Some((Instant::now(), response.organizations)); + self.routing.store_organizations(response.organizations); } - } else if url.path() == "/v1/clusters" { - if let Some((_, organization)) = - url.query_pairs().find(|(key, _)| key == "organization") - { + } else if path == "/v1/clusters" { + let selected = self.scope.organization.as_deref().and_then(|organization| { + if is_uuid(organization) { + Some(organization.to_owned()) + } else { + self.cached_organization(organization) + .map(|item| item.organization_id) + } + }); + if let Some(organization_id) = selected { if let Ok(response) = serde_json::from_value::(value.clone()) { self.routing .clusters - .borrow_mut() - .insert(clusters_path(&organization), (Instant::now(), response)); + .lock() + .unwrap() + .insert(organization_id, (Instant::now(), response)); } } } } - pub(super) fn organization_id(&self, name: &str) -> Result { - let response: Organizations = self.get("/v1/organizations")?; - response - .organizations - .into_iter() - .find(|organization| organization.name == name) + fn cached_organization(&self, name_or_id: &str) -> Option { + let cache = self.routing.organizations.lock().unwrap(); + let (time, organizations) = cache.as_ref()?; + if time.elapsed() >= Duration::from_secs(30) { + return None; + } + organizations + .iter() + .find(|item| item.name == name_or_id || item.organization_id == name_or_id) + .cloned() + } + + /// Resolves an organization name or ID to its ID. + pub fn organization_id(&self, name_or_id: &str) -> Result { + self.find_organization(&organization_selector(name_or_id), None) .map(|organization| organization.organization_id) + } + + fn find_organization( + &self, + selector: &OrganizationSelector, + deadline: Option, + ) -> Result { + if let OrganizationSelector::Id(id) = selector { + return Ok(Organization { + organization_id: id.clone(), + name: id.clone(), + }); + } + let matches = |item: &Organization| match selector { + OrganizationSelector::Id(id) => item.organization_id == *id, + OrganizationSelector::Name(name) => item.name == *name, + }; + let organizations = self.organizations(deadline)?; + organizations + .into_iter() + .find(|item| matches(item)) .context("Organization not found.") } - fn organization_name(&self, id: &str, deadline: Option) -> Result { - if let Some((time, organizations)) = self.routing.organizations.borrow().as_ref() { + pub(super) fn organizations(&self, deadline: Option) -> Result> { + if let Some((time, organizations)) = self.routing.organizations.lock().unwrap().as_ref() { if time.elapsed() < Duration::from_secs(30) { - if let Some(organization) = - organizations.iter().find(|item| item.organization_id == id) - { - return Ok(organization.name.clone()); - } + return Ok(organizations.clone()); } } let response: Organizations = handle_response( @@ -90,13 +194,9 @@ impl ApiClient { )? .send()?, )?; - let name = response - .organizations - .iter() - .find(|item| item.organization_id == id) - .map(|item| item.name.clone()); - *self.routing.organizations.borrow_mut() = Some((Instant::now(), response.organizations)); - name.context("Organization not found.") + self.routing + .store_organizations(response.organizations.clone()); + Ok(response.organizations) } pub(super) fn routed_request(&self, method: Method, path: &str) -> Result { @@ -121,58 +221,128 @@ impl ApiClient { path: &str, deadline: Option, ) -> Result { - let pair = self.deployment_for(path, deadline)?; + let scope = self.resolve_scope(path, deadline)?; if method != Method::GET && (path.starts_with("/v1/organizations") || path.starts_with("/v1/clusters")) { - self.routing.clusters.borrow_mut().clear(); - *self.routing.organizations.borrow_mut() = None; + self.routing.clusters.lock().unwrap().clear(); + *self.routing.organizations.lock().unwrap() = None; } - let request = - self.deployment_request(method, path, pair.as_ref().or(self.deployment.as_ref()))?; + let request = self.deployment_request( + method, + path, + scope.deployment.as_ref().or(self.deployment.as_ref()), + )?; + let request = with_scope_headers( + request, + scope.organization_id.as_deref(), + scope.cluster_id.as_deref(), + ); before_deadline(request, deadline) } - fn deployment_for( + fn resolve_scope(&self, path: &str, deadline: Option) -> Result { + let selectors = self.selectors(path); + if selectors.organization.is_none() && selectors.cluster.is_none() { + return Ok(ResolvedScope::default()); + } + if self.has_user_credential()? { + self.user_scope(selectors, deadline) + } else { + self.bound_scope(selectors, deadline) + } + } + + /// API keys are bound to one organization and cluster. Names are matched + /// against the key's own organization (the only entry `GET /v1/organizations` + /// returns for a key) and bound cluster. + fn bound_scope( &self, - path: &str, + selectors: Selectors, deadline: Option, - ) -> Result> { - if self - .token()? - .as_deref() - .is_none_or(|token| token.starts_with("rt_")) - { - return Ok(None); - } - let url = Url::parse(&format!("{}{}", self.base_url, path)).context("invalid API URL")?; - let Some((organization, cluster)) = scope(&url) else { - return Ok(None); + ) -> Result { + let organization_id = match selectors.organization { + Some(OrganizationSelector::Id(id)) => Some(id), + Some(OrganizationSelector::Name(name)) if self.token()?.is_some() => { + let organization = self + .organizations(deadline)? + .into_iter() + .find(|item| item.name == name) + .with_context(|| { + format!("Organization '{name}' is not the API key's organization.") + })?; + Some(organization.organization_id) + } + Some(OrganizationSelector::Name(_)) | None => None, }; - let organization = match organization { - OrganizationSelector::Id(id) => self.organization_name(&id, deadline)?, - OrganizationSelector::Name(name) => name, + let mut scope = ResolvedScope { + organization_id, + ..ResolvedScope::default() }; - let collection = clusters_path(&organization); - let cached = self - .routing + if selectors.cluster_in_path { + return Ok(scope); + } + scope.cluster_id = match selectors.cluster { + Some(ClusterSelector::Id(id)) => Some(id), + Some(ClusterSelector::Name(_)) if self.token()?.is_none() => None, + Some(ClusterSelector::Name(name)) => { + let bound = self.bound_cluster(deadline)?; + anyhow::ensure!( + bound.name == name, + "The API key is not bound to cluster '{name}'." + ); + Some(bound.id) + } + None => None, + }; + Ok(scope) + } + + fn bound_cluster(&self, deadline: Option) -> Result { + if let Some(cluster) = self.routing.bound_cluster.lock().unwrap().as_ref() { + return Ok(cluster.clone()); + } + let bound: Clusters = handle_response( + before_deadline( + self.unrouted_request(Method::GET, "/v1/clusters")?, + deadline, + )? + .send()?, + )?; + let cluster = bound .clusters - .borrow() - .get(&collection) - .filter(|(time, _)| time.elapsed() < Duration::from_secs(30)) - .map(|(_, clusters)| clusters.clone()); - let clusters = match cached { - Some(clusters) => clusters, - None => { - let response: Clusters = - serde_json::from_value(self.discover_clusters(Some(&organization), deadline)?)?; - self.routing - .clusters - .borrow_mut() - .insert(collection, (Instant::now(), response.clone())); - response + .into_iter() + .next() + .context("The API key is not bound to a cluster.")?; + *self.routing.bound_cluster.lock().unwrap() = Some(cluster.clone()); + Ok(cluster) + } + + fn user_scope(&self, selectors: Selectors, deadline: Option) -> Result { + let organization = selectors + .organization + .as_ref() + .map(|selector| self.find_organization(selector, deadline)) + .transpose()?; + let mut scope = ResolvedScope { + organization_id: organization + .as_ref() + .map(|organization| organization.organization_id.clone()), + ..ResolvedScope::default() + }; + let Some(cluster) = selectors.cluster else { + return Ok(scope); + }; + let Some(organization) = organization else { + match cluster { + ClusterSelector::Id(id) => scope.cluster_id = Some(id), + ClusterSelector::Name(name) => anyhow::bail!( + "Choose an organization with --org to select cluster '{name}' by name." + ), } + return Ok(scope); }; + let clusters = self.organization_clusters(&organization, deadline)?; let target = clusters.clusters.iter().find(|item| match &cluster { ClusterSelector::Id(id) => item.id == *id, ClusterSelector::Name(name) => item.name == *name, @@ -181,18 +351,58 @@ impl ApiClient { // Keep known routes usable, but retry missing routes after a region recovers. self.routing .clusters - .borrow_mut() - .remove(&clusters_path(&organization)); + .lock() + .unwrap() + .remove(&organization.organization_id); anyhow::bail!("Some regions are unavailable. Cannot resolve the selected cluster; retry when regional discovery recovers."); } + if !selectors.cluster_in_path { + scope.cluster_id = match (&cluster, target) { + (_, Some(target)) => Some(target.id.clone()), + (ClusterSelector::Id(id), None) => Some(id.clone()), + (ClusterSelector::Name(name), None) => { + anyhow::bail!( + "Cluster '{name}' not found in organization '{}'.", + organization.name + ) + } + }; + } let pair = target.and_then(|item| { item.deployment_id .as_deref() .zip(item.cloud_region.as_deref()) }); - Ok(pair + scope.deployment = pair .filter(|(deployment, region)| valid_routing(deployment, region)) - .map(|(deployment, region)| (deployment.to_owned(), region.to_owned()))) + .map(|(deployment, region)| (deployment.to_owned(), region.to_owned())); + Ok(scope) + } + + fn organization_clusters( + &self, + organization: &Organization, + deadline: Option, + ) -> Result { + let cached = self + .routing + .clusters + .lock() + .unwrap() + .get(&organization.organization_id) + .filter(|(time, _)| time.elapsed() < Duration::from_secs(30)) + .map(|(_, clusters)| clusters.clone()); + if let Some(clusters) = cached { + return Ok(clusters); + } + let response: Clusters = serde_json::from_value( + self.discover_clusters(Some(&organization.organization_id), deadline)?, + )?; + self.routing.clusters.lock().unwrap().insert( + organization.organization_id.clone(), + (Instant::now(), response.clone()), + ); + Ok(response) } } @@ -212,45 +422,67 @@ pub(super) fn before_deadline( } } -enum ClusterSelector { - Id(String), - Name(String), -} - -enum OrganizationSelector { - Id(String), - Name(String), -} - -fn clusters_path(organization: &str) -> String { - format!( - "/v1/clusters?organization={}", - urlencoding::encode(organization) - ) -} +impl ApiClient { + fn selectors(&self, path: &str) -> Selectors { + let saved_organization = self + .saved + .organization + .as_ref() + .filter(|(name, _)| self.scope.organization.as_deref() == Some(name.as_str())); + let saved_cluster = self + .saved + .cluster + .as_ref() + .filter(|(name, _)| self.scope.cluster.as_deref() == Some(name.as_str())); + let organization = match saved_organization { + Some((_, id)) => { + self.routing.saved_id_used.store(true, Ordering::Relaxed); + Some(OrganizationSelector::Id(id.clone())) + } + None => self + .scope + .organization + .as_deref() + .map(organization_selector), + }; + let path_cluster = path + .split('?') + .next() + .and_then(|path| path.strip_prefix("/v1/clusters/")) + .and_then(|path| path.split('/').next()) + .filter(|part| { + !part.is_empty() && !matches!(*part, "sizes" | "metrics" | "verify-s3-access") + }) + .and_then(|id| urlencoding::decode(id).ok()) + .map(|id| id.into_owned()); + let cluster_in_path = path_cluster.is_some(); + let cluster = match (path_cluster, saved_cluster) { + (Some(id), _) => Some(ClusterSelector::Id(id)), + (None, Some((_, id))) => { + self.routing.saved_id_used.store(true, Ordering::Relaxed); + Some(ClusterSelector::Id(id.clone())) + } + (None, None) => self.scope.cluster.as_deref().map(|cluster| { + if is_uuid(cluster) { + ClusterSelector::Id(cluster.to_owned()) + } else { + ClusterSelector::Name(cluster.to_owned()) + } + }), + }; + Selectors { + organization, + cluster, + cluster_in_path, + } + } -fn scope(url: &Url) -> Option<(OrganizationSelector, ClusterSelector)> { - let query: HashMap<_, _> = url.query_pairs().into_owned().collect(); - let organization = if let Some(id) = query.get("organization_id") { - OrganizationSelector::Id(id.clone()) - } else { - OrganizationSelector::Name(query.get("organization")?.clone()) - }; - let path_cluster = url - .path() - .strip_prefix("/v1/clusters/") - .and_then(|path| path.split('/').next()) - .filter(|part| { - !part.is_empty() && !matches!(*part, "sizes" | "metrics" | "verify-s3-access") - }); - let cluster = if let Some(id) = path_cluster { - ClusterSelector::Id(urlencoding::decode(id).ok()?.into_owned()) - } else if let Some(id) = query.get("cluster_id") { - ClusterSelector::Id(id.clone()) - } else { - ClusterSelector::Name(query.get("cluster")?.clone()) - }; - Some((organization, cluster)) + /// The organization and cluster IDs this client's scope resolves to, for + /// saving in the config. + pub fn resolve_scope_ids(&self) -> Result<(Option, Option)> { + let resolved = self.resolve_scope("/v1/databases", None)?; + Ok((resolved.organization_id, resolved.cluster_id)) + } } // Match the backend/worker syntax; do not maintain a catalog of AWS regions. diff --git a/src/client/routing_tests.rs b/src/client/routing_tests.rs index a2f0f2d..fe3f96c 100644 --- a/src/client/routing_tests.rs +++ b/src/client/routing_tests.rs @@ -1,4 +1,4 @@ -use super::ApiClient; +use super::{ApiClient, SavedIds, Scope}; use serde_json::{json, Value}; use std::collections::HashMap; use std::io::{BufRead, BufReader, Read, Write}; @@ -7,6 +7,7 @@ use std::thread; use std::time::{Duration, Instant}; const ORG: &str = "00000000-0000-4000-8000-000000000001"; +const CLUSTER: &str = "00000000-0000-4000-8000-0000000000c1"; struct Request { path: String, headers: HashMap, @@ -56,7 +57,8 @@ fn server(responses: Vec<(&'static str, Value)>) -> (String, thread::JoinHandle< .unwrap_or(0); let mut body = vec![0; length]; reader.read_exact(&mut body).unwrap(); - let index = if first.starts_with("GET /v1/clusters?") && !regional_targets.is_empty() { + let is_catalog = first.starts_with("GET /v1/clusters HTTP"); + let index = if is_catalog && !regional_targets.is_empty() { let pair = headers .get("x-rawtree-deployment-id") .zip(headers.get("x-rawtree-region")) @@ -68,7 +70,7 @@ fn server(responses: Vec<(&'static str, Value)>) -> (String, thread::JoinHandle< } else { 0 }; - if first.starts_with("GET /v1/clusters?") && !regional_targets.is_empty() { + if is_catalog && !regional_targets.is_empty() { regional_targets.remove(index); } let (order, (status, payload)) = responses.remove(index); @@ -120,7 +122,7 @@ fn metadata(pair: Value) -> Vec<(&'static str, Value)> { let mut responses = discovery_catalog(); responses.push(( "200 OK", - json!({"clusters": [{"id": "cluster-id", "name": "production", "deployment_id": pair["deployment_id"], "cloud_region": pair["cloud_region"]}]}), + json!({"clusters": [{"id": CLUSTER, "name": "production", "deployment_id": pair["deployment_id"], "cloud_region": pair["cloud_region"]}]}), )); responses } @@ -133,22 +135,22 @@ fn session_requests_resolve_scope_and_reuse_metadata_for_queries_and_gzip() { ("200 OK", json!({"ok":true})), ]); let (base, server) = server(responses); - let client = ApiClient::new(base, Some("session.fixture".to_string())); - let path = "/v1/query?organization=acme&cluster=production"; + let client = ApiClient::new(base, Some("session.fixture".to_string())) + .with_scope(Scope::new(Some("acme"), Some("production"))); + let path = "/v1/query"; let _: Value = client.post(path, &json!({"query": "SELECT 1"})).unwrap(); let _: Value = client - .post_compressed( - "/v1/tables/events?organization=acme&cluster=production", - "{\"value\":1}", - ) + .post_compressed("/v1/tables/events", "{\"value\":1}") .unwrap(); let requests = server.join().unwrap(); - assert_eq!( - requests[2].path, - "GET /v1/clusters?organization=acme HTTP/1.1" - ); + assert_eq!(requests[2].path, "GET /v1/clusters HTTP/1.1"); + assert_eq!(requests[2].headers["x-rawtree-organization-id"], ORG); assert!(!requests[2].headers.contains_key("x-rawtree-region")); + assert_eq!(requests[3].path, "POST /v1/query HTTP/1.1"); + assert_eq!(requests[4].path, "POST /v1/tables/events HTTP/1.1"); for request in &requests[3..] { + assert_eq!(request.headers["x-rawtree-organization-id"], ORG); + assert_eq!(request.headers["x-rawtree-cluster-id"], CLUSTER); assert_eq!(request.headers["x-rawtree-deployment-id"], "12abcdef"); assert_eq!(request.headers["x-rawtree-region"], "eu-west-1"); assert_eq!(request.headers["authorization"], "Bearer session.fixture"); @@ -175,7 +177,8 @@ fn absent_partial_and_invalid_metadata_keep_default_routing() { let (base, server) = server(responses); let client = ApiClient::new(base, Some("oauth.fixture".to_string())); let _: Value = client - .get("/v1/databases?organization=acme&cluster=production") + .with_scope(Scope::new(Some("acme"), Some("production"))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); assert!(!requests[3].headers.contains_key("x-rawtree-region")); @@ -184,35 +187,111 @@ fn absent_partial_and_invalid_metadata_keep_default_routing() { } #[test] -fn api_keys_skip_discovery_and_routing_headers() { +fn api_keys_resolve_names_against_their_own_organization_and_cluster() { + let (base, server) = server(vec![ + ( + "200 OK", + json!({"organizations":[{"organization_id":ORG,"name":"acme","role":null}]}), + ), + ( + "200 OK", + json!({"clusters":[{"id":CLUSTER,"name":"production"}]}), + ), + ("200 OK", json!({})), + ]); + let client = ApiClient::new(base, Some("rt_fixture".to_string())); + client + .with_scope(Scope::new(Some("acme"), Some("production"))) + .post_raw("/v1/query?database=analytics", &json!({"query":"SELECT 1"})) + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(requests[0].path, "GET /v1/organizations HTTP/1.1"); + assert_eq!(requests[1].path, "GET /v1/clusters HTTP/1.1"); + assert_eq!( + requests[2].path, + "POST /v1/query?database=analytics HTTP/1.1" + ); + assert_eq!(requests[2].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[2].headers["x-rawtree-cluster-id"], CLUSTER); + assert!(!requests[2].headers.contains_key("x-rawtree-region")); + assert_eq!(requests[2].headers["authorization"], "Bearer rt_fixture"); +} + +#[test] +fn api_keys_send_id_selectors_without_discovery() { let (base, server) = server(vec![("200 OK", json!({}))]); let client = ApiClient::new(base, Some("rt_fixture".to_string())); client - .post_raw( - "/v1/query?organization=acme&cluster=production", - &json!({"query":"SELECT 1"}), - ) + .with_scope(Scope::new(Some(ORG), Some(CLUSTER))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) .unwrap(); let requests = server.join().unwrap(); assert_eq!(requests.len(), 1); - assert!(!requests[0].headers.contains_key("x-rawtree-region")); - assert_eq!(requests[0].headers["authorization"], "Bearer rt_fixture"); + assert_eq!(requests[0].path, "POST /v1/query HTTP/1.1"); + assert_eq!(requests[0].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[0].headers["x-rawtree-cluster-id"], CLUSTER); } #[test] -fn cluster_id_actions_preserve_organization_query_and_serving_headers() { +fn api_keys_reject_clusters_they_are_not_bound_to() { + let (base, server) = server(vec![( + "200 OK", + json!({"clusters":[{"id":CLUSTER,"name":"production"}]}), + )]); + let client = ApiClient::new(base, Some("rt_fixture".to_string())); + let error = client + .with_scope(Scope::new(None, Some("staging"))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) + .unwrap_err(); + assert!(error.to_string().contains("not bound to cluster 'staging'")); + assert_eq!(server.join().unwrap().len(), 1); +} + +#[test] +fn api_keys_reject_organizations_that_are_not_their_own() { + let (base, server) = server(vec![( + "200 OK", + json!({"organizations":[{"organization_id":ORG,"name":"acme","role":null}]}), + )]); + let client = ApiClient::new(base, Some("rt_fixture".to_string())); + let error = client + .with_scope(Scope::organization(Some("other"))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) + .unwrap_err(); + assert!(error + .to_string() + .contains("'other' is not the API key's organization")); + assert_eq!(server.join().unwrap().len(), 1); +} + +#[test] +fn api_keys_resolve_organization_names_to_ids_for_paths() { + let (base, server) = server(vec![( + "200 OK", + json!({"organizations":[{"organization_id":ORG,"name":"acme","role":null}]}), + )]); + let client = ApiClient::new(base, Some("rt_fixture".to_string())); + assert_eq!(client.organization_id("acme").unwrap(), ORG); + assert_eq!(server.join().unwrap().len(), 1); +} + +#[test] +fn cluster_id_actions_send_organization_header_and_serving_headers() { let mut responses = metadata(json!({"deployment_id": "12abcdef", "cloud_region": "us-east-1"})); responses.push(("200 OK", json!({}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".to_string())); let _: Value = client - .post_empty("/v1/clusters/cluster-id/stop?organization=acme") + .with_scope(Scope::new(Some("acme"), None)) + .post_empty(&format!("/v1/clusters/{CLUSTER}/stop")) .unwrap(); let requests = server.join().unwrap(); assert_eq!( requests[3].path, - "POST /v1/clusters/cluster-id/stop?organization=acme HTTP/1.1" + format!("POST /v1/clusters/{CLUSTER}/stop HTTP/1.1") ); + assert_eq!(requests[3].headers["x-rawtree-organization-id"], ORG); + assert!(!requests[3].headers.contains_key("x-rawtree-cluster-id")); assert_eq!(requests[3].headers["x-rawtree-deployment-id"], "12abcdef"); } @@ -227,7 +306,8 @@ fn discovery_failure_does_not_execute_the_operation() { let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".to_string())); assert!(client - .get::("/v1/databases?organization=acme&cluster=production") + .with_scope(Scope::new(Some("acme"), Some("production"))) + .get::("/v1/databases") .is_err()); assert_eq!(server.join().unwrap().len(), 1); } @@ -237,24 +317,32 @@ fn cluster_creation_invalidates_previously_discovered_empty_collection() { let mut responses = discovery_catalog(); responses.extend([ ("200 OK", json!({"clusters": []})), - ("200 OK", json!({"id": "new-id"})), + ("200 OK", json!({"id": CLUSTER})), ( "200 OK", - json!({"clusters": [{"id":"new-id", "name":"new", "deployment_id":"12abcdef", "cloud_region":"eu-west-1"}]}), + json!({"clusters": [{"id":CLUSTER, "name":"new", "deployment_id":"12abcdef", "cloud_region":"eu-west-1"}]}), ), ("200 OK", json!({"data":[]})), ]); responses.splice(4..4, discovery_catalog()); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".to_string())); - let collection = "/v1/clusters?organization=acme"; - let _: Value = client.get(&collection).unwrap(); - let _: Value = client.post(&collection, &json!({"name":"new"})).unwrap(); + let organization = client.with_scope(Scope::organization(Some("acme"))); + let collection = "/v1/clusters"; + let _: Value = organization.get(collection).unwrap(); + let _: Value = organization + .post(collection, &json!({"name":"new"})) + .unwrap(); let _: Value = client - .get("/v1/databases?organization=acme&cluster_id=new-id") + .with_scope(Scope::new(Some("acme"), Some(CLUSTER))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); - assert_eq!(requests[6].path, format!("GET {collection} HTTP/1.1")); + assert_eq!(requests[3].path, "POST /v1/clusters HTTP/1.1"); + assert_eq!(requests[3].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[6].path, "GET /v1/clusters HTTP/1.1"); + assert_eq!(requests[7].path, "GET /v1/databases HTTP/1.1"); + assert_eq!(requests[7].headers["x-rawtree-cluster-id"], CLUSTER); assert_eq!(requests[7].headers["x-rawtree-region"], "eu-west-1"); } @@ -275,54 +363,60 @@ fn explicit_timeout_includes_routing_discovery() { }); let client = ApiClient::new(base, Some("session.fixture".to_string())); let started = Instant::now(); - let result = client.post_with_timeout::( - "/v1/query?organization=acme&cluster=production", - &json!({"query":"SELECT 1"}), - Duration::from_millis(50), - ); + let result = client + .with_scope(Scope::new(Some("acme"), Some("production"))) + .post_with_timeout::( + "/v1/query", + &json!({"query":"SELECT 1"}), + Duration::from_millis(50), + ); assert!(result.is_err()); assert!(started.elapsed() < Duration::from_millis(300)); server.join().unwrap(); } #[test] -fn explicit_id_and_name_selectors_cannot_collide() { +fn uuid_selectors_are_ids_and_other_values_are_names() { + const OTHER: &str = "00000000-0000-4000-8000-0000000000c2"; let mut responses = discovery_catalog(); responses.extend([ ( "200 OK", json!({"clusters":[ - {"id":"other-id", "name":"target-id", "deployment_id":"abcdef12", "cloud_region":"ap-south-1"}, - {"id":"target-id", "name":"production", "deployment_id":"12abcdef", "cloud_region":"eu-west-1"} + {"id":OTHER, "name":"target", "deployment_id":"abcdef12", "cloud_region":"ap-south-1"}, + {"id":CLUSTER, "name":"production", "deployment_id":"12abcdef", "cloud_region":"eu-west-1"} ]}), ), ("200 OK", json!({})), - ( - "200 OK", - json!({"organizations": [{"organization_id": ORG, "name": "acme"}]}), - ), ("200 OK", json!({})), ("200 OK", json!({})), ]); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".to_string())); let _: Value = client - .get("/v1/clusters/target-id?organization=acme") + .with_scope(Scope::organization(Some("acme"))) + .get(&format!("/v1/clusters/{CLUSTER}")) .unwrap(); let _: Value = client - .get(&format!( - "/v1/metrics?organization_id={ORG}&cluster_id=target-id" - )) + .with_scope(Scope::new(Some(ORG), Some(CLUSTER))) + .get("/v1/metrics") .unwrap(); let _: Value = client - .get(&format!( - "/v1/databases?organization_id={ORG}&cluster=target-id" - )) + .with_scope(Scope::new(Some("acme"), Some("target"))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); + assert_eq!( + requests[3].path, + format!("GET /v1/clusters/{CLUSTER} HTTP/1.1") + ); assert_eq!(requests[3].headers["x-rawtree-region"], "eu-west-1"); - assert_eq!(requests[5].headers["x-rawtree-region"], "eu-west-1"); - assert_eq!(requests[6].headers["x-rawtree-region"], "ap-south-1"); + assert!(!requests[3].headers.contains_key("x-rawtree-cluster-id")); + assert_eq!(requests[4].path, "GET /v1/metrics HTTP/1.1"); + assert_eq!(requests[4].headers["x-rawtree-region"], "eu-west-1"); + assert_eq!(requests[4].headers["x-rawtree-cluster-id"], CLUSTER); + assert_eq!(requests[5].headers["x-rawtree-region"], "ap-south-1"); + assert_eq!(requests[5].headers["x-rawtree-cluster-id"], OTHER); } fn region_catalog(overrides: Value) -> Vec<(&'static str, Value)> { @@ -353,10 +447,8 @@ fn creation_and_sizes_use_selected_region_without_mutating_default_client() { let regional = client.for_region(Some("acme"), "region-id").unwrap(); let _: Value = regional.get("/v1/clusters/sizes").unwrap(); let _: Value = regional - .post( - "/v1/clusters?organization=acme", - &json!({"region_id":"region-id"}), - ) + .with_scope(Scope::new(Some("acme"), None)) + .post("/v1/clusters", &json!({"region_id":"region-id"})) .unwrap(); let _: Value = client.get("/v1/clusters/sizes").unwrap(); let requests = server.join().unwrap(); @@ -364,6 +456,8 @@ fn creation_and_sizes_use_selected_region_without_mutating_default_client() { requests[1].path, format!("GET /v1/regions?organization_id={ORG} HTTP/1.1") ); + assert_eq!(requests[3].path, "POST /v1/clusters HTTP/1.1"); + assert_eq!(requests[3].headers["x-rawtree-organization-id"], ORG); for request in &requests[2..4] { assert_eq!(request.headers["x-rawtree-deployment-id"], "abcd1234"); assert_eq!(request.headers["x-rawtree-region"], "eu-central-1"); @@ -453,7 +547,10 @@ fn discovery_merges_regions_and_uses_authoritative_metadata_for_queries() { responses.push(("200 OK", json!({"data":[]}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - let result: Value = client.get("/v1/clusters?organization=acme").unwrap(); + let result: Value = client + .with_scope(Scope::new(Some("acme"), None)) + .get("/v1/clusters") + .unwrap(); assert_eq!(result["clusters"].as_array().unwrap().len(), 2); assert_eq!(result["organization"]["name"], "acme"); assert_eq!(result["clusters"][1]["deployment_id"], deployment); @@ -463,11 +560,15 @@ fn discovery_merges_regions_and_uses_authoritative_metadata_for_queries() { "data" ); let _: Value = client - .get("/v1/databases?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); assert_eq!(requests.len(), 5); assert!(!requests[2].headers.contains_key("x-rawtree-region")); + assert_eq!(requests[4].path, "GET /v1/databases HTTP/1.1"); + assert_eq!(requests[4].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[4].headers["x-rawtree-cluster-id"], "eu"); for index in [3, 4] { assert_eq!( requests[index].headers["x-rawtree-deployment-id"], @@ -490,27 +591,33 @@ fn discovery_runs_before_a_direct_cluster_request_and_retries_after_regional_fai json!({"message":"Europe unavailable"}), ); responses.push(("200 OK", json!({"tables":[]}))); - responses.extend(multi_region_catalog("1234abcd")); + responses.extend(multi_region_catalog("1234abcd").into_iter().skip(1)); responses.push(("200 OK", json!({"data":[]}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - let partial: Value = client.get("/v1/clusters?organization=acme").unwrap(); + let partial: Value = client + .with_scope(Scope::new(Some("acme"), None)) + .get("/v1/clusters") + .unwrap(); assert_eq!(partial["clusters"].as_array().unwrap().len(), 1); assert_eq!(partial["unavailable_regions"].as_array().unwrap().len(), 2); let _: Value = client - .get("/v1/tables?organization=acme&cluster=america") + .with_scope(Scope::new(Some("acme"), Some("america"))) + .get("/v1/tables") .unwrap(); assert!(client - .get::("/v1/databases?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get::("/v1/databases") .unwrap_err() .to_string() .contains("Some regions are unavailable")); let _: Value = client - .get("/v1/databases?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); - assert_eq!(requests.len(), 10); - assert_eq!(requests[9].headers["x-rawtree-region"], "eu-west-1"); + assert_eq!(requests.len(), 9); + assert_eq!(requests[8].headers["x-rawtree-region"], "eu-west-1"); } #[test] @@ -520,7 +627,8 @@ fn discovery_rejects_unknown_region_references() { let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); assert!(client - .get::("/v1/databases?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get::("/v1/databases") .unwrap_err() .to_string() .contains("Region 'missing'")); @@ -535,19 +643,26 @@ fn public_origins_use_deployment_hosts_and_keep_paths_queries_and_headers() { format!("https://api.rawtree.{env}"), Some("session.fixture".into()), ); - client.remember_routing_metadata("/v1/clusters?organization=acme", &json!({"clusters":[{ + client.remember_routing_metadata( + "/v1/organizations", + &json!({"organizations":[{"organization_id":ORG,"name":"acme"}]}), + ); + client.with_scope(Scope::new(Some("acme"), None)).remember_routing_metadata("/v1/clusters", &json!({"clusters":[{ "id":"eu", "name":"europe", "deployment_id":deployment,"cloud_region":"eu-west-1" }]})); let request = client - .routed_request( - reqwest::Method::GET, - "/v1/databases?organization=acme&cluster=europe", - ) + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .routed_request(reqwest::Method::GET, "/v1/databases") .unwrap() .build() .unwrap(); - assert_eq!(request.url().as_str(), format!("https://api.{deployment}.eu-west-1.aws.rawtree.{env}/v1/databases?organization=acme&cluster=europe")); + assert_eq!( + request.url().as_str(), + format!("https://api.{deployment}.eu-west-1.aws.rawtree.{env}/v1/databases") + ); assert_eq!(request.headers()["x-rawtree-deployment-id"], deployment); + assert_eq!(request.headers()["x-rawtree-organization-id"], ORG); + assert_eq!(request.headers()["x-rawtree-cluster-id"], "eu"); } } for url in [ @@ -589,7 +704,10 @@ fn owning_catalog_wins_over_duplicates_in_either_order() { responses.push(("200 OK", json!({}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - let catalog: Value = client.get("/v1/clusters?organization=acme").unwrap(); + let catalog: Value = client + .with_scope(Scope::new(Some("acme"), None)) + .get("/v1/clusters") + .unwrap(); assert_eq!(catalog["clusters"].as_array().unwrap().len(), 1); assert_eq!( catalog["clusters"][0]["s3_storage"], @@ -597,7 +715,8 @@ fn owning_catalog_wins_over_duplicates_in_either_order() { ); assert_eq!(catalog["clusters"][0]["status"], "running"); let _: Value = client - .get("/v1/databases?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); let headers = &requests.last().unwrap().headers; @@ -612,14 +731,17 @@ fn owning_catalog_wins_over_duplicates_in_either_order() { fn api_keys_preserve_the_public_gateway_url() { let client = ApiClient::new("https://api.rawtree.com".into(), Some("rt_fixture".into())); let request = client - .routed_request( - reqwest::Method::GET, - "/v1/databases?organization=acme&cluster=europe", - ) + .with_scope(Scope::new(Some(ORG), Some(CLUSTER))) + .routed_request(reqwest::Method::GET, "/v1/databases") .unwrap() .build() .unwrap(); - assert_eq!(request.url().host_str(), Some("api.rawtree.com")); + assert_eq!( + request.url().as_str(), + "https://api.rawtree.com/v1/databases" + ); + assert_eq!(request.headers()["x-rawtree-organization-id"], ORG); + assert_eq!(request.headers()["x-rawtree-cluster-id"], CLUSTER); assert!(!request.headers().contains_key("x-rawtree-region")); } @@ -631,21 +753,28 @@ fn empty_partial_catalog_is_marked_and_explicit_refresh_replaces_it() { "503 Service Unavailable", json!({"message":"Europe unavailable"}), ); - responses.extend(multi_region_catalog("1234abcd")); + responses.extend(multi_region_catalog("1234abcd").into_iter().skip(1)); responses.push(("200 OK", json!({"tables":[]}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - let partial: Value = client.get("/v1/clusters?organization=acme").unwrap(); + let partial: Value = client + .with_scope(Scope::new(Some("acme"), None)) + .get("/v1/clusters") + .unwrap(); assert_eq!(partial["clusters"], json!([])); assert_eq!(partial["unavailable_regions"].as_array().unwrap().len(), 2); - let refreshed: Value = client.get("/v1/clusters?organization=acme").unwrap(); + let refreshed: Value = client + .with_scope(Scope::new(Some("acme"), None)) + .get("/v1/clusters") + .unwrap(); assert!(refreshed.get("unavailable_regions").is_none()); let _: Value = client - .get("/v1/tables?organization=acme&cluster=europe") + .with_scope(Scope::new(Some("acme"), Some("europe"))) + .get("/v1/tables") .unwrap(); let requests = server.join().unwrap(); - assert_eq!(requests.len(), 9); - assert_eq!(requests[8].headers["x-rawtree-deployment-id"], "1234abcd"); + assert_eq!(requests.len(), 8); + assert_eq!(requests[7].headers["x-rawtree-deployment-id"], "1234abcd"); } #[test] @@ -677,20 +806,27 @@ fn all_organization_discovery_is_concurrent_and_retains_healthy_catalogs() { let mut reader = BufReader::new(socket.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); + let mut organization = String::new(); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" { break; } + if let Some(value) = line + .to_ascii_lowercase() + .strip_prefix("x-rawtree-organization-id:") + { + organization = value.trim().to_owned(); + } } - (socket, first) + (socket, first, organization) }; let reply = |socket: &mut std::net::TcpStream, status: u16, body: Value| { let body = body.to_string(); write!(socket, "HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); }; - let (mut socket, first) = read(); + let (mut socket, first, _) = read(); assert!(first.starts_with("GET /v1/organizations ")); let mut organizations = vec![ json!({"organization_id":"acme-id","name":"acme"}), @@ -701,7 +837,7 @@ fn all_organization_discovery_is_concurrent_and_retains_healthy_catalogs() { } reply(&mut socket, 200, json!({"organizations":organizations})); for _ in 0..2 { - let (mut socket, first) = read(); + let (mut socket, first, _) = read(); assert!(first.starts_with("GET /v1/regions?organization_id=")); reply( &mut socket, @@ -712,15 +848,16 @@ fn all_organization_discovery_is_concurrent_and_retains_healthy_catalogs() { // Accept both catalog requests before replying to either. A serial // implementation cannot satisfy this barrier, even with a short timeout. let catalogs = [read(), read()]; - for (mut socket, first) in catalogs { - if first.contains("organization=acme ") { + for (mut socket, first, organization) in catalogs { + assert!(first.starts_with("GET /v1/clusters ")); + if organization == "acme-id" { reply( &mut socket, 200, json!({"clusters":[{"id":"healthy", "name":"production", "region_id":"legacy"}]}), ); } else { - assert!(first.contains("organization=other ")); + assert_eq!(organization, "other-id"); reply( &mut socket, 503, @@ -740,3 +877,117 @@ fn all_organization_discovery_is_concurrent_and_retains_healthy_catalogs() { server.join().unwrap(); } } + +#[test] +fn organization_names_and_ids_resolve_to_ids_from_one_listing() { + let (base, server) = server(vec![( + "200 OK", + json!({"organizations":[{"organization_id":ORG,"name":"acme"}]}), + )]); + let client = ApiClient::new(base, Some("session.fixture".into())); + assert_eq!(client.organization_id("acme").unwrap(), ORG); + assert_eq!(client.organization_id(ORG).unwrap(), ORG); + assert!(client + .organization_id("missing") + .unwrap_err() + .to_string() + .contains("Organization not found")); + assert_eq!(server.join().unwrap().len(), 1); +} + +fn saved(organization: bool, cluster: bool) -> SavedIds { + SavedIds { + organization: organization.then(|| ("acme".to_string(), ORG.to_string())), + cluster: cluster.then(|| ("production".to_string(), CLUSTER.to_string())), + } +} + +#[test] +fn saved_ids_are_sent_without_lookups_for_api_keys() { + let (base, server) = server(vec![("200 OK", json!({}))]); + let client = + ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(saved(true, true)); + assert!(!client.used_saved_ids()); + client + .with_scope(Scope::new(Some("acme"), Some("production"))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) + .unwrap(); + assert!(client.used_saved_ids()); + let requests = server.join().unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[0].headers["x-rawtree-cluster-id"], CLUSTER); +} + +#[test] +fn saved_ids_skip_the_organization_listing_but_keep_regional_routing() { + let (base, server) = server(vec![ + ( + "200 OK", + json!({"regions":[{"id":"legacy","name":"Virginia","cloud_region":"us-east-1","deployment_id":null,"enabled":true,"organization_id":null}]}), + ), + ( + "200 OK", + json!({"clusters":[{"id":CLUSTER,"name":"renamed","deployment_id":"12abcdef","cloud_region":"eu-west-1"}]}), + ), + ("200 OK", json!({})), + ]); + let client = + ApiClient::new(base, Some("session.fixture".to_string())).with_saved_ids(saved(true, true)); + let _: Value = client + .with_scope(Scope::new(Some("acme"), Some("production"))) + .get("/v1/databases") + .unwrap(); + let requests = server.join().unwrap(); + assert_eq!(requests.len(), 3); + assert_eq!( + requests[0].path, + format!("GET /v1/regions?organization_id={ORG} HTTP/1.1") + ); + assert_eq!(requests[2].headers["x-rawtree-organization-id"], ORG); + assert_eq!(requests[2].headers["x-rawtree-cluster-id"], CLUSTER); + assert_eq!(requests[2].headers["x-rawtree-deployment-id"], "12abcdef"); +} + +#[test] +fn names_that_differ_from_the_saved_ones_are_resolved_by_name() { + const OTHER_ORG: &str = "00000000-0000-4000-8000-000000000002"; + let (base, server) = server(vec![ + ( + "200 OK", + json!({"organizations":[{"organization_id":OTHER_ORG,"name":"other","role":null}]}), + ), + ( + "200 OK", + json!({"clusters":[{"id":CLUSTER,"name":"staging"}]}), + ), + ("200 OK", json!({})), + ]); + let client = + ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(saved(true, true)); + client + .with_scope(Scope::new(Some("other"), Some("staging"))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) + .unwrap(); + assert!(!client.used_saved_ids()); + let requests = server.join().unwrap(); + assert_eq!(requests.len(), 3); + assert_eq!(requests[2].headers["x-rawtree-organization-id"], OTHER_ORG); +} + +#[test] +fn a_renamed_cluster_keeps_working_through_its_saved_id() { + let (base, server) = server(vec![("200 OK", json!({}))]); + let client = ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(SavedIds { + organization: None, + cluster: Some(("old-name".to_string(), CLUSTER.to_string())), + }); + client + .with_scope(Scope::new(None, Some("old-name"))) + .post_raw("/v1/query", &json!({"query":"SELECT 1"})) + .unwrap(); + assert_eq!( + server.join().unwrap()[0].headers["x-rawtree-cluster-id"], + CLUSTER + ); +} diff --git a/src/commands/auth.rs b/src/commands/auth.rs index 619f96c..1b26abc 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -12,7 +12,7 @@ use reqwest::blocking::Client as HttpClient; use serde::Deserialize; use serde_json::json; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::config; use crate::constants::DEFAULT_API_URL; use crate::org; @@ -56,10 +56,33 @@ enum CliDeviceTokenPoll { #[derive(Clone, Debug, Default)] struct AuthSelection { organization: Option, + organization_id: Option, cluster: Option, + cluster_id: Option, database: Option, } +/// Saves the IDs of the selected organization and cluster next to their names. +/// Best effort: a lookup that fails only leaves the ID unsaved, and requests +/// keep resolving that name. +fn attach_ids(client: &ApiClient, mut selection: AuthSelection) -> AuthSelection { + if let Some(organization) = selection.organization.as_deref() { + selection.organization_id = client + .with_scope(Scope::organization(Some(organization))) + .resolve_scope_ids() + .ok() + .and_then(|(organization_id, _)| organization_id); + } + if let Some(cluster) = selection.cluster.as_deref() { + selection.cluster_id = client + .with_scope(Scope::new(selection.organization.as_deref(), Some(cluster))) + .resolve_scope_ids() + .ok() + .and_then(|(_, cluster_id)| cluster_id); + } + selection +} + #[derive(Deserialize)] struct DatabaseContextResponse { database: Option, @@ -102,8 +125,11 @@ fn apply_auth_config( cfg.oauth = None; cfg.token = Some(token.to_string()); cfg.email = email.map(str::to_string); - cfg.default_organization = selection.organization.clone(); - cfg.default_cluster = selection.cluster.clone(); + cfg.set_default_organization( + selection.organization.clone(), + selection.organization_id.clone(), + ); + cfg.set_default_cluster(selection.cluster.clone(), selection.cluster_id.clone()); cfg.default_database = selection.database.clone(); cfg.url = (base_url != DEFAULT_API_URL).then(|| base_url.to_string()); } @@ -149,6 +175,7 @@ fn auth_selection_from_database_context( organization: organization.or_else(|| cli_org.map(str::to_string)), cluster: cluster.map(str::to_string), database: database.or_else(|| cli_database.map(str::to_string)), + ..AuthSelection::default() }) } @@ -159,10 +186,11 @@ fn resolve_api_key_auth_selection( cli_cluster: Option<&str>, cli_database: Option<&str>, ) -> Result { - let authed_client = ApiClient::new(base_url.to_string(), Some(token.to_string())); - let (keys_path, tables_path) = api_key_context_paths(cli_org, cli_cluster, cli_database); + let authed_client = ApiClient::new(base_url.to_string(), Some(token.to_string())) + .with_scope(Scope::new(cli_org, cli_cluster)); + let (keys_path, tables_path) = api_key_context_paths(cli_database); - match authed_client.get::(&keys_path) { + let selection = match authed_client.get::(&keys_path) { Ok(response) => auth_selection_from_database_context( response.context, cli_org, @@ -182,20 +210,17 @@ fn resolve_api_key_auth_selection( tables_err )), }, - } + }; + selection.map(|selection| attach_ids(&authed_client, selection)) } -fn api_key_context_paths( - cli_org: Option<&str>, - cli_cluster: Option<&str>, - cli_database: Option<&str>, -) -> (String, String) { +fn api_key_context_paths(cli_database: Option<&str>) -> (String, String) { let keys_path = cli_database - .map(|database| org::database_scoped_path(database, "/api-keys", cli_org, cli_cluster)) - .unwrap_or_else(|| org::scoped_path("/v1/api-keys", cli_org, cli_cluster)); + .map(|database| org::database_path(database, "/api-keys")) + .unwrap_or_else(|| "/v1/api-keys".to_string()); let tables_path = cli_database - .map(|database| org::database_scoped_path(database, "/tables", cli_org, cli_cluster)) - .unwrap_or_else(|| org::scoped_path("/v1/tables", cli_org, cli_cluster)); + .map(|database| org::database_path(database, "/tables")) + .unwrap_or_else(|| "/v1/tables".to_string()); (keys_path, tables_path) } @@ -584,7 +609,9 @@ mod tests { let resp = sample_auth_response(); let selection = AuthSelection { organization: Some("team_alpha".to_string()), + organization_id: Some("org-id".to_string()), cluster: Some("production".to_string()), + cluster_id: Some("cluster-id".to_string()), database: Some("analytics".to_string()), }; apply_auth_config( @@ -595,6 +622,8 @@ mod tests { &selection, ); + assert_eq!(cfg.default_organization_id.as_deref(), Some("org-id")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("cluster-id")); assert_eq!(cfg.token.as_deref(), Some("jwt")); assert_eq!(cfg.email.as_deref(), Some("user@example.com")); assert_eq!(cfg.default_organization.as_deref(), Some("team_alpha")); @@ -652,6 +681,8 @@ mod tests { default_database: Some("old_database".to_string()), default_organization: Some("old_team".to_string()), default_cluster: Some("old_cluster".to_string()), + default_organization_id: Some("old-org-id".to_string()), + default_cluster_id: Some("old-cluster-id".to_string()), ..Config::default() }; let resp = sample_auth_response(); @@ -666,6 +697,8 @@ mod tests { assert_eq!(cfg.default_organization, None); assert_eq!(cfg.default_cluster, None); + assert_eq!(cfg.default_organization_id, None); + assert_eq!(cfg.default_cluster_id, None); assert_eq!(cfg.default_database, None); } @@ -711,26 +744,12 @@ mod tests { } #[test] - fn api_key_context_paths_do_not_invent_organization() { - let (keys_path, tables_path) = api_key_context_paths(None, None, Some("analytics")); + fn api_key_context_paths_carry_only_the_database() { + let (keys_path, tables_path) = api_key_context_paths(Some("analytics")); assert_eq!(keys_path, "/v1/api-keys?database=analytics"); assert_eq!(tables_path, "/v1/tables?database=analytics"); - } - - #[test] - fn api_key_context_paths_include_explicit_organization() { - let (keys_path, tables_path) = - api_key_context_paths(Some("team alpha"), Some("prod/eu"), Some("analytics")); - - assert_eq!( - keys_path, - "/v1/api-keys?database=analytics&organization=team%20alpha&cluster=prod%2Feu" - ); - assert_eq!( - tables_path, - "/v1/tables?database=analytics&organization=team%20alpha&cluster=prod%2Feu" - ); + assert_eq!(api_key_context_paths(None).0, "/v1/api-keys"); } #[test] @@ -743,6 +762,8 @@ mod tests { default_database: Some("analytics".to_string()), default_organization: Some("team_alpha".to_string()), default_cluster: Some("production".to_string()), + default_organization_id: Some("org-id".to_string()), + default_cluster_id: Some("cluster-id".to_string()), }; clear_auth_config(&mut cfg); @@ -753,6 +774,8 @@ mod tests { assert_eq!(cfg.default_database, None); assert_eq!(cfg.default_organization, None); assert_eq!(cfg.default_cluster, None); + assert_eq!(cfg.default_organization_id, None); + assert_eq!(cfg.default_cluster_id, None); } #[test] diff --git a/src/commands/auth/selection.rs b/src/commands/auth/selection.rs index 37bb8ec..5defbb7 100644 --- a/src/commands/auth/selection.rs +++ b/src/commands/auth/selection.rs @@ -4,7 +4,10 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use super::{read_selection_input, AuthSelection}; -use crate::{client::ApiClient, org}; +use crate::{ + client::{ApiClient, Scope}, + org, +}; #[derive(Debug, Serialize)] #[serde(tag = "needs", rename_all = "lowercase")] @@ -163,8 +166,8 @@ fn list_databases_for_organization( organization_name: &str, cluster: Option<&str>, ) -> Result> { - let path = org::databases_collection_path(Some(organization_name), cluster); - let resp: ListDatabasesResponse = client.get(&path)?; + let client = client.with_scope(Scope::new(Some(organization_name), cluster)); + let resp: ListDatabasesResponse = client.get("/v1/databases")?; Ok(resp.databases.into_iter().map(|item| item.name).collect()) } @@ -172,8 +175,8 @@ fn list_clusters_for_organization( client: &ApiClient, organization_name: &str, ) -> Result> { - let path = org::scoped_path("/v1/clusters", Some(organization_name), None); - let resp: ListClustersResponse = client.get(&path)?; + let client = client.with_scope(Scope::organization(Some(organization_name))); + let resp: ListClustersResponse = client.get("/v1/clusters")?; Ok(resp.clusters.into_iter().map(|item| item.name).collect()) } @@ -258,11 +261,15 @@ pub(super) fn resolve_browser_auth_selection( Err(err) if json_mode || cli_database.is_some() => return Err(err.into()), Err(_) => None, }; - Ok(AuthSelection { - organization: Some(organization), - cluster, - database, - }) + Ok(super::attach_ids( + &client, + AuthSelection { + organization: Some(organization), + cluster, + database, + ..AuthSelection::default() + }, + )) } #[cfg(test)] diff --git a/src/commands/cluster.rs b/src/commands/cluster.rs index 49abbe0..0ac47c0 100644 --- a/src/commands/cluster.rs +++ b/src/commands/cluster.rs @@ -6,9 +6,9 @@ use serde_json::{json, Value}; use super::table_output::new_cli_table; use crate::cli::ClusterSizeArg; -use crate::client::{ApiClient, UnavailableRegion}; +use crate::client::{ApiClient, SavedIds, Scope, UnavailableRegion}; use crate::cluster_identity::ClusterIdentityArgs; -use crate::config; +use crate::config::{self, Config}; use crate::output; use crate::s3_storage::{format_storage, S3StorageArgs, S3StorageMetadata}; @@ -100,28 +100,20 @@ struct DeleteClusterResponse { deleted: bool, } -fn renamed_default_cluster( - current_default_cluster: Option<&str>, - old_name: &str, - cluster_id: &str, - new_name: &str, -) -> Option { - match current_default_cluster { - Some(current) if current == old_name || current == cluster_id => Some(new_name.to_string()), - Some(current) => Some(current.to_string()), - None => None, +fn is_default_cluster(cfg: &Config, name: &str, cluster_id: &str) -> bool { + cfg.default_cluster_id.as_deref() == Some(cluster_id) + || matches!(cfg.default_cluster.as_deref(), Some(current) if current == name || current == cluster_id) +} + +fn rename_default_cluster(cfg: &mut Config, old_name: &str, cluster_id: &str, new_name: &str) { + if is_default_cluster(cfg, old_name, cluster_id) { + cfg.set_default_cluster(Some(new_name.to_string()), Some(cluster_id.to_string())); } } -fn default_cluster_after_delete( - current_default_cluster: Option<&str>, - deleted_name: &str, - cluster_id: &str, -) -> Option { - match current_default_cluster { - Some(current) if current == deleted_name || current == cluster_id => None, - Some(current) => Some(current.to_string()), - None => None, +fn clear_default_cluster_if_deleted(cfg: &mut Config, name: &str, cluster_id: &str) { + if is_default_cluster(cfg, name, cluster_id) { + cfg.set_default_cluster(None, None); } } @@ -154,7 +146,9 @@ pub fn create( ); body["region_id"] = json!(options.region_id); - let value: Value = client.post(&clusters_collection_path(options.organization), &body)?; + let value: Value = client + .with_scope(Scope::organization(options.organization)) + .post("/v1/clusters", &body)?; let created: ClusterItem = serde_json::from_value(value.clone()).context("invalid cluster response from server")?; @@ -214,7 +208,8 @@ pub fn update( ); } - let (_, response) = load_dedicated_clusters(client, organization)?; + let client = client.with_scope(Scope::organization(organization)); + let (_, response) = load_dedicated_clusters(&client)?; let cluster = resolve_cluster(&response, name_or_id)?; let mut body = serde_json::Map::new(); if let Some(name) = name { @@ -227,21 +222,13 @@ pub fn update( ); } - let value: Value = client.patch( - &cluster_path(&cluster.id, None, organization), - &Value::Object(body), - )?; + let value: Value = client.patch(&cluster_path(&cluster.id, None), &Value::Object(body))?; let updated: ClusterItem = serde_json::from_value(value.clone()).context("invalid cluster response from server")?; if name.is_some() { let _config_lock = config::lock()?; let mut cfg = config::load()?; - cfg.default_cluster = renamed_default_cluster( - cfg.default_cluster.as_deref(), - &cluster.name, - &cluster.id, - &updated.name, - ); + rename_default_cluster(&mut cfg, &cluster.name, &cluster.id, &updated.name); config::save(&cfg)?; } @@ -256,7 +243,8 @@ pub fn update( } pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Result<()> { - let (value, resp) = load_dedicated_clusters(client, organization)?; + let client = client.with_scope(Scope::organization(organization)); + let (value, resp) = load_dedicated_clusters(&client)?; output::print_result(&value, json_mode, |_| { if !resp.unavailable_regions.is_empty() { let names = resp @@ -370,10 +358,22 @@ pub fn sizes(client: &ApiClient, json_mode: bool) -> Result<()> { Ok(()) } -pub fn use_cluster(name: &str, json_mode: bool) -> Result<()> { +pub fn use_cluster( + client: &ApiClient, + name: &str, + organization: Option<&str>, + json_mode: bool, +) -> Result<()> { + // Re-resolve by name: this command is how a rejected saved ID gets refreshed. + let cluster_id = client + .with_scope(Scope::new(organization, Some(name))) + .with_saved_ids(SavedIds::default()) + .resolve_scope_ids() + .ok() + .and_then(|(_, cluster_id)| cluster_id); let _config_lock = config::lock()?; let mut cfg = config::load()?; - cfg.default_cluster = Some(name.to_string()); + cfg.set_default_cluster(Some(name.to_string()), cluster_id); config::save(&cfg)?; output::print_result(&json!({"default_cluster": name}), json_mode, |_| { @@ -388,7 +388,8 @@ pub fn status( organization: Option<&str>, json_mode: bool, ) -> Result<()> { - let (_, resp) = load_dedicated_clusters(client, organization)?; + let client = client.with_scope(Scope::organization(organization)); + let (_, resp) = load_dedicated_clusters(&client)?; let cluster = resolve_cluster(&resp, name_or_id)?; output::print_result(cluster, json_mode, |cluster| { @@ -463,19 +464,16 @@ pub fn delete( organization: Option<&str>, json_mode: bool, ) -> Result<()> { - let (_, resp) = load_dedicated_clusters(client, organization)?; + let client = client.with_scope(Scope::organization(organization)); + let (_, resp) = load_dedicated_clusters(&client)?; let cluster = resolve_cluster(&resp, name_or_id)?.clone(); - let path = cluster_path(&cluster.id, None, organization); + let path = cluster_path(&cluster.id, None); let result: DeleteClusterResponse = client.delete(&path)?; let value = delete_output(&cluster, result.deleted); if result.deleted { let _config_lock = config::lock()?; let mut cfg = config::load()?; - cfg.default_cluster = default_cluster_after_delete( - cfg.default_cluster.as_deref(), - &cluster.name, - &cluster.id, - ); + clear_default_cluster_if_deleted(&mut cfg, &cluster.name, &cluster.id); config::save(&cfg)?; } @@ -510,12 +508,8 @@ fn empty_list_message(resp: &ListClustersResponse, organization: Option<&str>) - } } -fn load_dedicated_clusters( - client: &ApiClient, - organization: Option<&str>, -) -> Result<(Value, ListClustersResponse)> { - let path = clusters_collection_path(organization); - let value: Value = client.get(&path)?; +fn load_dedicated_clusters(client: &ApiClient) -> Result<(Value, ListClustersResponse)> { + let value: Value = client.get("/v1/clusters")?; let resp = serde_json::from_value(value.clone()).context("invalid clusters response from server")?; Ok((value, resp)) @@ -627,9 +621,10 @@ fn request_lifecycle( action: LifecycleAction, json_mode: bool, ) -> Result<()> { - let (_, resp) = load_dedicated_clusters(client, organization)?; + let client = client.with_scope(Scope::organization(organization)); + let (_, resp) = load_dedicated_clusters(&client)?; let cluster = resolve_cluster(&resp, name_or_id)?; - let path = cluster_path(&cluster.id, Some(action.path_segment()), organization); + let path = cluster_path(&cluster.id, Some(action.path_segment())); let value: Value = client.post_empty(&path)?; let updated: ClusterItem = serde_json::from_value(value.clone()).context("invalid cluster response from server")?; @@ -649,23 +644,12 @@ fn request_lifecycle( Ok(()) } -fn clusters_collection_path(organization: Option<&str>) -> String { - match organization { - Some(name) => format!("/v1/clusters?organization={}", urlencoding::encode(name)), - None => "/v1/clusters".to_string(), - } -} - -fn cluster_path(cluster_id: &str, action: Option<&str>, organization: Option<&str>) -> String { +fn cluster_path(cluster_id: &str, action: Option<&str>) -> String { let mut path = format!("/v1/clusters/{}", urlencoding::encode(cluster_id)); if let Some(action) = action { path.push('/'); path.push_str(action); } - if let Some(name) = organization { - path.push_str("?organization="); - path.push_str(&urlencoding::encode(name)); - } path } @@ -723,37 +707,21 @@ mod tests { use serde_json::json; use super::{ - cluster_path, cluster_size_json, clusters_collection_path, create_request_body, - default_cluster_after_delete, delete_output, empty_list_message, format_created_at, - format_idle_timeout, format_phase, format_size_per_replica, renamed_default_cluster, - resolve_cluster, resolve_cluster_size, ClusterItem, ClusterResources, ClusterSizeItem, - ClusterStatus, ListClustersResponse, + clear_default_cluster_if_deleted, cluster_path, cluster_size_json, create_request_body, + delete_output, empty_list_message, format_created_at, format_idle_timeout, format_phase, + format_size_per_replica, rename_default_cluster, resolve_cluster, resolve_cluster_size, + ClusterItem, ClusterResources, ClusterSizeItem, ClusterStatus, ListClustersResponse, }; use crate::cli::ClusterSizeArg; + use crate::config::Config; #[test] - fn collection_path_encodes_organization() { - assert_eq!( - clusters_collection_path(Some("team alpha")), - "/v1/clusters?organization=team%20alpha" - ); - assert_eq!(clusters_collection_path(None), "/v1/clusters"); - } - - #[test] - fn lifecycle_paths_encode_cluster_and_organization() { + fn lifecycle_paths_encode_cluster() { assert_eq!( - cluster_path("cluster/id", Some("stop"), Some("team alpha")), - "/v1/clusters/cluster%2Fid/stop?organization=team%20alpha" - ); - assert_eq!( - cluster_path("cluster-id", Some("resume"), None), - "/v1/clusters/cluster-id/resume" - ); - assert_eq!( - cluster_path("cluster-id", None, Some("team alpha")), - "/v1/clusters/cluster-id?organization=team%20alpha" + cluster_path("cluster/id", Some("stop")), + "/v1/clusters/cluster%2Fid/stop" ); + assert_eq!(cluster_path("cluster-id", None), "/v1/clusters/cluster-id"); } #[test] @@ -987,39 +955,48 @@ mod tests { ); } + fn config_with_default_cluster(name: &str, id: Option<&str>) -> Config { + Config { + default_cluster: Some(name.to_string()), + default_cluster_id: id.map(str::to_string), + ..Config::default() + } + } + #[test] - fn renamed_cluster_updates_matching_default_name_or_id() { - assert_eq!( - renamed_default_cluster(Some("production"), "production", "cluster-id", "analytics") - .as_deref(), - Some("analytics") - ); - assert_eq!( - renamed_default_cluster(Some("cluster-id"), "production", "cluster-id", "analytics") - .as_deref(), - Some("analytics") - ); - assert_eq!( - renamed_default_cluster(Some("other"), "production", "cluster-id", "analytics") - .as_deref(), - Some("other") - ); + fn renamed_cluster_updates_matching_default_name_or_id_and_keeps_the_id() { + for (current, id) in [ + ("production", None), + ("cluster-id", None), + ("stale-name", Some("cluster-id")), + ] { + let mut cfg = config_with_default_cluster(current, id); + rename_default_cluster(&mut cfg, "production", "cluster-id", "analytics"); + assert_eq!(cfg.default_cluster.as_deref(), Some("analytics")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("cluster-id")); + } + let mut cfg = config_with_default_cluster("other", Some("other-id")); + rename_default_cluster(&mut cfg, "production", "cluster-id", "analytics"); + assert_eq!(cfg.default_cluster.as_deref(), Some("other")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("other-id")); } #[test] - fn deleted_cluster_clears_matching_default_name_or_id() { - assert_eq!( - default_cluster_after_delete(Some("production"), "production", "cluster-id"), - None - ); - assert_eq!( - default_cluster_after_delete(Some("cluster-id"), "production", "cluster-id"), - None - ); - assert_eq!( - default_cluster_after_delete(Some("other"), "production", "cluster-id").as_deref(), - Some("other") - ); + fn deleted_cluster_clears_matching_default_name_id_and_saved_id() { + for (current, id) in [ + ("production", None), + ("cluster-id", None), + ("stale-name", Some("cluster-id")), + ] { + let mut cfg = config_with_default_cluster(current, id); + clear_default_cluster_if_deleted(&mut cfg, "production", "cluster-id"); + assert_eq!(cfg.default_cluster, None); + assert_eq!(cfg.default_cluster_id, None); + } + let mut cfg = config_with_default_cluster("other", Some("other-id")); + clear_default_cluster_if_deleted(&mut cfg, "production", "cluster-id"); + assert_eq!(cfg.default_cluster.as_deref(), Some("other")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("other-id")); } #[test] diff --git a/src/commands/database.rs b/src/commands/database.rs index 5160f88..f8fd7d8 100644 --- a/src/commands/database.rs +++ b/src/commands/database.rs @@ -2,9 +2,8 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::config; -use crate::org; use crate::output; use crate::s3_storage::{format_storage, S3StorageArgs, S3StorageMetadata}; @@ -34,26 +33,23 @@ fn apply_database_create_config( resp: &CreateDatabaseResponse, organization: Option<&str>, cluster: Option<&str>, + ids: (Option, Option), ) { cfg.default_database = Some(resp.database.name.clone()); - cfg.default_organization = organization.map(str::to_string); + cfg.set_default_organization(organization.map(str::to_string), ids.0); if let Some(cluster) = cluster { - cfg.default_cluster = Some(cluster.to_string()); + cfg.set_default_cluster(Some(cluster.to_string()), ids.1); } } -fn database_create_collection_path(organization: Option<&str>, cluster: Option<&str>) -> String { - org::databases_collection_path(organization, cluster) -} - pub fn list( client: &ApiClient, organization: Option<&str>, cluster: Option<&str>, json_mode: bool, ) -> Result<()> { - let path = org::databases_collection_path(organization, cluster); - let resp: ListDatabasesResponse = client.get(&path)?; + let client = client.with_scope(Scope::new(organization, cluster)); + let resp: ListDatabasesResponse = client.get("/v1/databases")?; output::print_result(&resp, json_mode, |resp| { if resp.databases.is_empty() { println!("No databases yet. Create one with `rtree database create `."); @@ -84,11 +80,13 @@ pub fn create( if let Some(storage) = s3_storage { body["s3_storage"] = storage; } - let path = database_create_collection_path(organization, cluster); - let resp: CreateDatabaseResponse = client.post(&path, &body)?; + let client = client.with_scope(Scope::new(organization, cluster)); + let resp: CreateDatabaseResponse = client.post("/v1/databases", &body)?; let _config_lock = config::lock()?; let mut cfg = config::load()?; - apply_database_create_config(&mut cfg, &resp, organization, cluster); + // Best effort: without IDs the names keep resolving on each request. + let ids = client.resolve_scope_ids().unwrap_or_default(); + apply_database_create_config(&mut cfg, &resp, organization, cluster, ids); config::save(&cfg)?; output::print_result(&resp, json_mode, |resp| { println!("Database '{}' created.", resp.database.name); @@ -123,11 +121,8 @@ pub fn delete( cluster: Option<&str>, json_mode: bool, ) -> Result<()> { - let path = org::scoped_path( - &format!("/v1/databases/{}", urlencoding::encode(name)), - organization, - cluster, - ); + let client = client.with_scope(Scope::new(organization, cluster)); + let path = format!("/v1/databases/{}", urlencoding::encode(name)); let resp: DeleteDatabaseResponse = client.delete(&path)?; output::print_result( &json!({"deleted": resp.deleted, "name": name}), @@ -143,10 +138,7 @@ pub fn delete( #[cfg(test)] mod tests { - use super::{ - apply_database_create_config, database_create_collection_path, CreateDatabaseResponse, - DatabaseRef, - }; + use super::{apply_database_create_config, CreateDatabaseResponse, DatabaseRef}; use crate::config::Config; #[test] @@ -163,21 +155,20 @@ mod tests { }, }; - apply_database_create_config(&mut cfg, &resp, Some("new_team"), Some("production")); + apply_database_create_config( + &mut cfg, + &resp, + Some("new_team"), + Some("production"), + (Some("org-id".into()), Some("cluster-id".into())), + ); assert_eq!(cfg.token.as_deref(), Some("jwt.token.value")); assert_eq!(cfg.email.as_deref(), Some("user@example.com")); assert_eq!(cfg.default_organization.as_deref(), Some("new_team")); assert_eq!(cfg.default_cluster.as_deref(), Some("production")); + assert_eq!(cfg.default_organization_id.as_deref(), Some("org-id")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("cluster-id")); assert_eq!(cfg.default_database.as_deref(), Some("analytics")); } - - #[test] - fn database_create_collection_path_uses_databases_endpoint() { - assert_eq!(database_create_collection_path(None, None), "/v1/databases"); - assert_eq!( - database_create_collection_path(Some("team alpha"), Some("prod/eu")), - "/v1/databases?organization=team%20alpha&cluster=prod%2Feu" - ); - } } diff --git a/src/commands/federation_rule.rs b/src/commands/federation_rule.rs index 96c70b5..7409933 100644 --- a/src/commands/federation_rule.rs +++ b/src/commands/federation_rule.rs @@ -6,7 +6,10 @@ use serde::Serialize; use serde_json::Value; use super::service_account::{parse_description, parse_name}; -use crate::{client::ApiClient, org, output}; +use crate::{ + client::{ApiClient, Scope}, + output, +}; #[derive(Clone, Debug, Serialize, ValueEnum)] #[serde(rename_all = "snake_case")] @@ -112,12 +115,10 @@ pub fn run( .context("Select an organization with --org, RAWTREE_ORG or `rtree organization use`")?; let cluster = cluster .context("Select a cluster with --cluster, RAWTREE_CLUSTER or `rtree cluster use`")?; - let path = |id: Option<&str>| { - let base = match id { - Some(id) => format!("/v1/federation-rules/{}", urlencoding::encode(id)), - None => "/v1/federation-rules".into(), - }; - org::scoped_path(&base, Some(organization), Some(cluster)) + let client = client.with_scope(Scope::new(Some(organization), Some(cluster))); + let path = |id: Option<&str>| match id { + Some(id) => format!("/v1/federation-rules/{}", urlencoding::encode(id)), + None => "/v1/federation-rules".into(), }; let result: Value = match action { Command::List => client.get(&path(None))?, diff --git a/src/commands/format.rs b/src/commands/format.rs index 85429ad..64cf81c 100644 --- a/src/commands/format.rs +++ b/src/commands/format.rs @@ -6,7 +6,10 @@ use clap::Args; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::{client::ApiClient, org}; +use crate::{ + client::{ApiClient, Scope}, + org, +}; #[derive(Args)] pub struct FormatArgs { @@ -34,11 +37,10 @@ pub fn format( sql: &str, json_mode: bool, ) -> Result<()> { + let client = client.with_scope(Scope::new(organization, cluster)); let path = match database { - Some(database) => { - org::database_scoped_path(database, "/query-format", organization, cluster) - } - None => org::scoped_path("/v1/query-format", organization, cluster), + Some(database) => org::database_path(database, "/query-format"), + None => "/v1/query-format".to_string(), }; // Allow upload/download time in addition to the server's 30-second formatter timeout. let response: QueryFormatResponse = diff --git a/src/commands/insert.rs b/src/commands/insert.rs index 798eabc..9ba2a46 100644 --- a/src/commands/insert.rs +++ b/src/commands/insert.rs @@ -11,7 +11,7 @@ use indicatif::{ProgressBar, ProgressStyle}; use serde::Deserialize; use serde_json::{json, Value}; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::org; use crate::output; @@ -81,8 +81,9 @@ pub fn insert( transform: Option<&str>, json_mode: bool, ) -> Result<()> { - let base_path = - org::database_scoped_path(database, &format!("/tables/{table}"), organization, cluster); + let scoped = client.with_scope(Scope::new(organization, cluster)); + let client = &scoped; + let base_path = org::database_path(database, &format!("/tables/{table}")); let api_path = append_transform_param(&base_path, transform); // Small inline data — send in one request @@ -94,32 +95,14 @@ pub fn insert( } if let Some(raw_url) = url { - return insert_from_url( - client, - database, - organization, - cluster, - table, - raw_url, - transform, - json_mode, - ); + return insert_from_url(client, database, table, raw_url, transform, json_mode); } let path = file.ok_or_else(|| anyhow::anyhow!("provide exactly one of --data, --file, or --url"))?; if is_jsonl(path) { - insert_jsonl_streaming( - client, - database, - organization, - cluster, - table, - path, - transform, - json_mode, - )?; + insert_jsonl_streaming(client, database, table, path, transform, json_mode)?; } else { // Non-JSONL files: parse entire file (assumed to be a JSON array or object) let contents = @@ -136,14 +119,12 @@ pub fn insert( fn insert_from_url( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, table: &str, url: &str, transform: Option<&str>, json_mode: bool, ) -> Result<()> { - let base_path = build_url_ingest_path(database, organization, cluster, table, url); + let base_path = build_url_ingest_path(database, table, url); let path = append_transform_param(&base_path, transform); let (response, query_id): (UrlInsertResponse, _) = client.post_empty_with_query_id(&path)?; if json_mode { @@ -160,27 +141,14 @@ fn insert_from_url( Ok(()) } -fn build_url_ingest_path( - database: &str, - organization: Option<&str>, - cluster: Option<&str>, - table: &str, - url: &str, -) -> String { +fn build_url_ingest_path(database: &str, table: &str, url: &str) -> String { let encoded_url = urlencoding::encode(url); - org::database_scoped_path( - database, - &format!("/tables/{table}?url={encoded_url}"), - organization, - cluster, - ) + org::database_path(database, &format!("/tables/{table}?url={encoded_url}")) } fn insert_jsonl_streaming( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, table: &str, path: &str, transform: Option<&str>, @@ -213,8 +181,7 @@ fn insert_jsonl_streaming( let first_error: Arc>> = Arc::new(std::sync::Mutex::new(None)); // Spawn sender threads — each reuses a body buffer, compresses, and POSTs - let base_url = - org::database_scoped_path(database, &format!("/tables/{table}"), organization, cluster); + let base_url = org::database_path(database, &format!("/tables/{table}")); let url = append_transform_param(&base_url, transform); let mut handles = Vec::with_capacity(senders); for _ in 0..senders { @@ -330,17 +297,11 @@ mod tests { #[test] fn url_ingest_path_uses_query_param_route() { - let path = build_url_ingest_path( - "events_2", - None, - Some("production"), - "events", - "https://example.com/a b.ndjson", - ); + let path = build_url_ingest_path("events_2", "events", "https://example.com/a b.ndjson"); assert_eq!( path, - "/v1/tables/events?url=https%3A%2F%2Fexample.com%2Fa%20b.ndjson&database=events_2&cluster=production" + "/v1/tables/events?url=https%3A%2F%2Fexample.com%2Fa%20b.ndjson&database=events_2" ); } diff --git a/src/commands/keys.rs b/src/commands/keys.rs index 1d0805c..b44076e 100644 --- a/src/commands/keys.rs +++ b/src/commands/keys.rs @@ -2,7 +2,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::org; use crate::output; @@ -65,8 +65,8 @@ pub fn list( cluster: Option<&str>, json_mode: bool, ) -> Result<()> { - let path = org::scoped_path("/v1/api-keys", organization, cluster); - let resp: ListApiKeysResponse = client.get(&path)?; + let client = client.with_scope(Scope::new(organization, cluster)); + let resp: ListApiKeysResponse = client.get("/v1/api-keys")?; output::print_result(&resp, json_mode, |_| { if resp.keys.is_empty() { println!("No API keys."); @@ -104,9 +104,10 @@ pub fn create( request: CreateApiKeyRequest<'_>, json_mode: bool, ) -> Result<()> { + let client = client.with_scope(Scope::new(organization, cluster)); let path = match database { - Some(database) => org::database_scoped_path(database, "/api-keys", organization, cluster), - None => org::scoped_path("/v1/api-keys", organization, cluster), + Some(database) => org::database_path(database, "/api-keys"), + None => "/v1/api-keys".to_string(), }; let resp: CreateApiKeyResponse = client.post(&path, &serde_json::to_value(request)?)?; output::print_result(&resp, json_mode, |_| { @@ -130,7 +131,8 @@ pub fn delete( id: uuid::Uuid, json_mode: bool, ) -> Result<()> { - let path = org::scoped_path(&format!("/v1/api-keys/{id}"), organization, cluster); + let client = client.with_scope(Scope::new(organization, cluster)); + let path = format!("/v1/api-keys/{id}"); let resp: DeleteApiKeyResponse = client.delete(&path)?; output::print_result( &json!({"deleted": resp.deleted, "id": id.to_string()}), diff --git a/src/commands/logs.rs b/src/commands/logs.rs index a4a544e..5eca2bc 100644 --- a/src/commands/logs.rs +++ b/src/commands/logs.rs @@ -3,8 +3,7 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; -use crate::client::ApiClient; -use crate::org; +use crate::client::{ApiClient, Scope}; use crate::output; #[derive(Debug, Deserialize, Serialize)] @@ -314,8 +313,9 @@ fn fetch_logs( limit, offset, ); - let path = org::scoped_path(&format!("/v1/logs?{query_string}"), organization, cluster); - client.get(&path) + client + .with_scope(Scope::new(organization, cluster)) + .get(&format!("/v1/logs?{query_string}")) } #[allow(clippy::too_many_arguments)] diff --git a/src/commands/organization.rs b/src/commands/organization.rs index d260467..bbee136 100644 --- a/src/commands/organization.rs +++ b/src/commands/organization.rs @@ -2,8 +2,8 @@ use anyhow::Result; use serde::Deserialize; use serde_json::json; -use crate::client::ApiClient; -use crate::config; +use crate::client::{ApiClient, SavedIds, Scope}; +use crate::config::{self, Config}; use crate::org; use crate::output; @@ -22,27 +22,28 @@ struct DeleteOrganizationResponse { deleted: bool, } -fn renamed_default_org( - current_default_organization: Option<&str>, - old_name: &str, - new_name: &str, -) -> Option { - match current_default_organization { - Some(current) if current == old_name => Some(new_name.to_string()), - Some(current) => Some(current.to_string()), - None => None, +fn is_default_org(cfg: &Config, name: &str, id: &str) -> bool { + cfg.default_organization_id.as_deref() == Some(id) + || matches!(cfg.default_organization.as_deref(), Some(current) if current == name || current == id) +} + +fn rename_default_org(cfg: &mut Config, old_name: &str, id: &str, new_name: &str) { + if is_default_org(cfg, old_name, id) { + cfg.set_default_organization(Some(new_name.to_string()), Some(id.to_string())); } } +/// The saved cluster belongs to the previous default organization. fn default_org_after_delete( - current_default_organization: Option<&str>, + cfg: &mut Config, deleted_name: &str, - next_available_organization: Option, -) -> Option { - match current_default_organization { - Some(current) if current == deleted_name => next_available_organization, - Some(current) => Some(current.to_string()), - None => None, + id: &str, + next_available_organization: Option<(String, String)>, +) { + if is_default_org(cfg, deleted_name, id) { + let (name, id) = next_available_organization.unzip(); + cfg.set_default_organization(name, id); + cfg.default_cluster_id = None; } } @@ -60,7 +61,11 @@ pub fn list(client: &ApiClient, json_mode: bool) -> Result<()> { ); } else { for item in &organizations { - println!("{:<20} {:<8}", item.name, item.role); + println!( + "{:<20} {:<8}", + item.name, + item.role.as_deref().unwrap_or("-") + ); } } }, @@ -83,10 +88,19 @@ pub fn create(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { Ok(()) } -pub fn use_organization(name: &str, json_mode: bool) -> Result<()> { +pub fn use_organization(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { + // Re-resolve by name: this command is how a rejected saved ID gets refreshed. + let id = client + .with_scope(Scope::default()) + .with_saved_ids(SavedIds::default()) + .organization_id(name) + .ok(); let _config_lock = config::lock()?; let mut cfg = config::load()?; - cfg.default_organization = Some(name.to_string()); + if cfg.default_organization_id != id { + cfg.default_cluster_id = None; + } + cfg.set_default_organization(Some(name.to_string()), id); config::save(&cfg)?; output::print_result(&json!({"default_organization": name}), json_mode, |_| { @@ -96,14 +110,14 @@ pub fn use_organization(name: &str, json_mode: bool) -> Result<()> { } pub fn rename(client: &ApiClient, old: &str, new_name: &str, json_mode: bool) -> Result<()> { + let id = client.organization_id(old)?; let resp: RenameOrganizationResponse = client.patch( - &format!("/v1/organizations/{old}"), + &format!("/v1/organizations/{}", urlencoding::encode(&id)), &json!({"organization_name": new_name}), )?; let _config_lock = config::lock()?; let mut cfg = config::load()?; - cfg.default_organization = - renamed_default_org(cfg.default_organization.as_deref(), old, &resp.name); + rename_default_org(&mut cfg, old, &id, &resp.name); config::save(&cfg)?; output::print_result( @@ -117,17 +131,18 @@ pub fn rename(client: &ApiClient, old: &str, new_name: &str, json_mode: bool) -> } pub fn delete(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { - let resp: DeleteOrganizationResponse = client.delete(&format!("/v1/organizations/{name}"))?; - if resp.deleted && config::load()?.default_organization.as_deref() == Some(name) { + let id = client.organization_id(name)?; + let resp: DeleteOrganizationResponse = + client.delete(&format!("/v1/organizations/{}", urlencoding::encode(&id)))?; + if resp.deleted && is_default_org(&config::load()?, name, &id) { let next = org::list_organizations(client)? .into_iter() .next() - .map(|item| item.name); + .map(|item| (item.name, item.organization_id)); let _config_lock = config::lock()?; let mut cfg = config::load()?; - if cfg.default_organization.as_deref() == Some(name) { - cfg.default_organization = - default_org_after_delete(cfg.default_organization.as_deref(), name, next); + if is_default_org(&cfg, name, &id) { + default_org_after_delete(&mut cfg, name, &id, next); config::save(&cfg)?; } } @@ -146,40 +161,65 @@ pub fn delete(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { #[cfg(test)] mod tests { - use super::{default_org_after_delete, renamed_default_org}; + use super::{default_org_after_delete, rename_default_org}; + use crate::config::Config; + + fn config_with(name: &str, id: Option<&str>) -> Config { + Config { + default_organization: Some(name.to_string()), + default_organization_id: id.map(str::to_string), + default_cluster_id: Some("cluster-id".to_string()), + ..Config::default() + } + } #[test] - fn renamed_default_org_updates_matching_default() { - let updated = renamed_default_org(Some("team_old"), "team_old", "team_new"); - assert_eq!(updated.as_deref(), Some("team_new")); + fn renamed_default_org_updates_the_name_and_keeps_the_id() { + for (current, id) in [ + ("team_old", None), + ("org-id", None), + ("stale_name", Some("org-id")), + ] { + let mut cfg = config_with(current, id); + rename_default_org(&mut cfg, "team_old", "org-id", "team_new"); + assert_eq!(cfg.default_organization.as_deref(), Some("team_new")); + assert_eq!(cfg.default_organization_id.as_deref(), Some("org-id")); + } } #[test] fn renamed_default_org_preserves_non_matching_default() { - let updated = renamed_default_org(Some("team_other"), "team_old", "team_new"); - assert_eq!(updated.as_deref(), Some("team_other")); + let mut cfg = config_with("team_other", Some("other-id")); + rename_default_org(&mut cfg, "team_old", "org-id", "team_new"); + assert_eq!(cfg.default_organization.as_deref(), Some("team_other")); + assert_eq!(cfg.default_organization_id.as_deref(), Some("other-id")); } #[test] - fn default_org_after_delete_promotes_next_org() { - let updated = - default_org_after_delete(Some("team_old"), "team_old", Some("team_next".to_string())); - assert_eq!(updated.as_deref(), Some("team_next")); + fn default_org_after_delete_promotes_next_org_with_its_id() { + let mut cfg = config_with("team_old", Some("org-id")); + let next = Some(("team_next".to_string(), "next-id".to_string())); + default_org_after_delete(&mut cfg, "team_old", "org-id", next); + assert_eq!(cfg.default_organization.as_deref(), Some("team_next")); + assert_eq!(cfg.default_organization_id.as_deref(), Some("next-id")); + assert_eq!(cfg.default_cluster_id, None); } #[test] fn default_org_after_delete_keeps_non_matching_default() { - let updated = default_org_after_delete( - Some("team_other"), - "team_old", - Some("team_next".to_string()), - ); - assert_eq!(updated.as_deref(), Some("team_other")); + let mut cfg = config_with("team_other", Some("other-id")); + let next = Some(("team_next".to_string(), "next-id".to_string())); + default_org_after_delete(&mut cfg, "team_old", "org-id", next); + assert_eq!(cfg.default_organization.as_deref(), Some("team_other")); + assert_eq!(cfg.default_organization_id.as_deref(), Some("other-id")); + assert_eq!(cfg.default_cluster_id.as_deref(), Some("cluster-id")); } #[test] - fn default_org_after_delete_clears_when_no_next_org() { - let updated = default_org_after_delete(Some("team_old"), "team_old", None); - assert_eq!(updated, None); + fn default_org_after_delete_clears_name_and_id_when_no_next_org() { + let mut cfg = config_with("team_old", Some("org-id")); + default_org_after_delete(&mut cfg, "team_old", "org-id", None); + assert_eq!(cfg.default_organization, None); + assert_eq!(cfg.default_organization_id, None); } } diff --git a/src/commands/query.rs b/src/commands/query.rs index 9a3db3b..1962ee4 100644 --- a/src/commands/query.rs +++ b/src/commands/query.rs @@ -6,7 +6,7 @@ use console::style; use serde_json::json; use serde_json::{Map, Value}; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::org; #[derive(Default)] @@ -34,8 +34,8 @@ pub fn query( let body = json!({ "sql": sql }); - let path = org::database_scoped_path(database, "/query", organization, cluster); - let raw = client.post_raw(&path, &body)?; + let client = client.with_scope(Scope::new(organization, cluster)); + let raw = client.post_raw(&org::database_path(database, "/query"), &body)?; if let Ok(value) = serde_json::from_str::(&raw) { if json_mode { diff --git a/src/commands/table.rs b/src/commands/table.rs index 1998219..19b95f6 100644 --- a/src/commands/table.rs +++ b/src/commands/table.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use super::table_output::new_cli_table; -use crate::client::ApiClient; +use crate::client::{ApiClient, Scope}; use crate::org; use crate::output; @@ -62,7 +62,8 @@ pub fn list( cluster: Option<&str>, json_mode: bool, ) -> Result<()> { - let list_path = org::database_scoped_path(database, "/tables", organization, cluster); + let client = client.with_scope(Scope::new(organization, cluster)); + let list_path = org::database_path(database, "/tables"); let resp: TablesResponse = client.get(&list_path)?; output::print_result( &json!({ @@ -101,8 +102,8 @@ pub fn describe( table: &str, json_mode: bool, ) -> Result<()> { - let describe_path = - org::database_scoped_path(database, &format!("/tables/{table}"), organization, cluster); + let client = client.with_scope(Scope::new(organization, cluster)); + let describe_path = org::database_path(database, &format!("/tables/{table}")); let resp: DescribeTableResponse = client.get(&describe_path)?; let details = &resp.table; output::print_result( @@ -154,7 +155,8 @@ pub fn create( sorting_key: Option<&str>, json_mode: bool, ) -> Result<()> { - let path = org::database_scoped_path(database, "/tables", organization, cluster); + let client = client.with_scope(Scope::new(organization, cluster)); + let path = org::database_path(database, "/tables"); let body = match sorting_key { Some(key) => json!({ "name": table, "sorting_key": key }), None => json!({ "name": table }), @@ -183,8 +185,8 @@ pub fn update( sorting_key: &str, json_mode: bool, ) -> Result<()> { - let path = - org::database_scoped_path(database, &format!("/tables/{table}"), organization, cluster); + let client = client.with_scope(Scope::new(organization, cluster)); + let path = org::database_path(database, &format!("/tables/{table}")); let response: TableMutationResponse = client.patch(&path, &json!({ "sorting_key": sorting_key }))?; output::print_result(&response, json_mode, |_| { @@ -280,19 +282,21 @@ mod tests { #[test] fn table_mutations_send_sorting_key_as_one_string() { + const ORG: &str = "00000000-0000-4000-8000-000000000001"; + const CLUSTER: &str = "00000000-0000-4000-8000-0000000000c1"; let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server"); let address = listener.local_addr().expect("test server address"); let server = std::thread::spawn(move || { for (method, path, expected_body, response) in [ ( "POST", - "/v1/tables?database=analytics&organization=acme&cluster=production", + "/v1/tables?database=analytics", json!({"name":"events","sorting_key":"region, ifNull(cityHash64(host, instanceId), 0)"}), r#"{"database":"analytics","table":"events","sorting_key":"region, ifNull(cityHash64(host, instanceId), 0)","storage":{"type":"default"}}"#, ), ( "PATCH", - "/v1/tables/events?database=analytics&organization=acme&cluster=production", + "/v1/tables/events?database=analytics", json!({"sorting_key":"region, toStartOfHour(timestamp)"}), r#"{"database":"analytics","table":"events","sorting_key":"region, toStartOfHour(timestamp)"}"#, ), @@ -306,17 +310,32 @@ mod tests { "{start}" ); let mut content_length = 0; + let mut scope_headers = Vec::new(); loop { let mut line = String::new(); reader.read_line(&mut line).expect("header"); if line == "\r\n" { break; } + let lowered = line.to_ascii_lowercase(); + if lowered.starts_with("x-rawtree-organization-id:") + || lowered.starts_with("x-rawtree-cluster-id:") + { + scope_headers.push(lowered.trim().to_owned()); + } if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length: ") { content_length = value.trim().parse().expect("content length"); } } + scope_headers.sort(); + assert_eq!( + scope_headers, + [ + format!("x-rawtree-cluster-id: {CLUSTER}"), + format!("x-rawtree-organization-id: {ORG}"), + ] + ); let mut body = vec![0; content_length]; reader.read_exact(&mut body).expect("request body"); assert_eq!( @@ -331,8 +350,8 @@ mod tests { create( &client, "analytics", - Some("acme"), - Some("production"), + Some(ORG), + Some(CLUSTER), "events", Some("region, ifNull(cityHash64(host, instanceId), 0)"), true, @@ -341,8 +360,8 @@ mod tests { update( &client, "analytics", - Some("acme"), - Some("production"), + Some(ORG), + Some(CLUSTER), "events", "region, toStartOfHour(timestamp)", true, diff --git a/src/commands/workflow/mod.rs b/src/commands/workflow/mod.rs index 52d971d..8c35eda 100644 --- a/src/commands/workflow/mod.rs +++ b/src/commands/workflow/mod.rs @@ -11,28 +11,14 @@ use super::logs::parse_duration; use super::table_output::new_cli_table; use crate::cli::WorkflowTimeRange; use crate::client::ApiClient; -use crate::org; use crate::output; -/// Organization and cluster are mandatory on every workflow route, even for -/// API keys that are already bound to a cluster. -pub struct WorkflowScope<'a> { - pub organization: &'a str, - pub cluster: &'a str, +fn collection_path(suffix: &str) -> String { + format!("/v1/workflows{suffix}") } -impl WorkflowScope<'_> { - fn path(&self, suffix: &str) -> String { - org::scoped_path( - &format!("/v1/workflows{suffix}"), - Some(self.organization), - Some(self.cluster), - ) - } - - fn workflow_path(&self, id: &str, suffix: &str) -> String { - self.path(&format!("/{}{suffix}", urlencoding::encode(id))) - } +fn workflow_path(id: &str, suffix: &str) -> String { + collection_path(&format!("/{}{suffix}", urlencoding::encode(id))) } #[derive(Deserialize)] @@ -278,10 +264,12 @@ fn window_params(range: &WorkflowTimeRange) -> Result> { Ok(params) } -fn with_params(scoped_path: String, params: &[String]) -> String { - params - .iter() - .fold(scoped_path, |path, param| format!("{path}&{param}")) +fn with_params(path: String, params: &[String]) -> String { + if params.is_empty() { + path + } else { + format!("{path}?{}", params.join("&")) + } } fn format_ms(ms: i64) -> String { @@ -359,8 +347,8 @@ fn print_workflow(workflow: &Workflow) { } } -pub fn list(client: &ApiClient, scope: &WorkflowScope, json_mode: bool) -> Result<()> { - let value: Value = client.get(&scope.path(""))?; +pub fn list(client: &ApiClient, json_mode: bool) -> Result<()> { + let value: Value = client.get(&collection_path(""))?; print_response(value, json_mode, |resp: ListWorkflowsResponse| { if resp.workflows.is_empty() { println!("No workflows yet. Create one with `rtree workflow create`."); @@ -405,28 +393,22 @@ pub fn list(client: &ApiClient, scope: &WorkflowScope, json_mode: bool) -> Resul }) } -pub fn get(client: &ApiClient, scope: &WorkflowScope, id: &str, json_mode: bool) -> Result<()> { - let value: Value = client.get(&scope.workflow_path(id, ""))?; +pub fn get(client: &ApiClient, id: &str, json_mode: bool) -> Result<()> { + let value: Value = client.get(&workflow_path(id, ""))?; print_response(value, json_mode, |workflow: Workflow| { println!("Workflow '{}':", workflow.name); print_workflow(&workflow); }) } -pub fn create( - client: &ApiClient, - scope: &WorkflowScope, - request: CreateWorkflow, - json_mode: bool, -) -> Result<()> { +pub fn create(client: &ApiClient, request: CreateWorkflow, json_mode: bool) -> Result<()> { let body = create_body(request)?; - let value: Value = - client - .post(&scope.path(""), &body) - .map_err(|error| match body["sinks"].as_array() { - Some(sinks) if !sinks.is_empty() => sink::with_help_hint(error), - _ => error, - })?; + let value: Value = client.post(&collection_path(""), &body).map_err(|error| { + match body["sinks"].as_array() { + Some(sinks) if !sinks.is_empty() => sink::with_help_hint(error), + _ => error, + } + })?; print_response(value, json_mode, |workflow: Workflow| { println!("Workflow '{}' created:", workflow.name); print_workflow(&workflow); @@ -435,27 +417,25 @@ pub fn create( pub fn update( client: &ApiClient, - scope: &WorkflowScope, id: &str, request: UpdateWorkflow, json_mode: bool, ) -> Result<()> { let body = update_body(request)?; - let value: Value = - client - .patch(&scope.workflow_path(id, ""), &body) - .map_err(|error| match body["sinks"].as_array() { - Some(sinks) if !sinks.is_empty() => sink::with_help_hint(error), - _ => error, - })?; + let value: Value = client + .patch(&workflow_path(id, ""), &body) + .map_err(|error| match body["sinks"].as_array() { + Some(sinks) if !sinks.is_empty() => sink::with_help_hint(error), + _ => error, + })?; print_response(value, json_mode, |workflow: Workflow| { println!("Workflow '{}' updated:", workflow.name); print_workflow(&workflow); }) } -pub fn delete(client: &ApiClient, scope: &WorkflowScope, id: &str, json_mode: bool) -> Result<()> { - client.delete_no_content(&scope.workflow_path(id, ""))?; +pub fn delete(client: &ApiClient, id: &str, json_mode: bool) -> Result<()> { + client.delete_no_content(&workflow_path(id, ""))?; output::print_result(&json!({"id": id, "deleted": true}), json_mode, |_| { println!("Workflow '{id}' deleted."); }); @@ -464,13 +444,12 @@ pub fn delete(client: &ApiClient, scope: &WorkflowScope, id: &str, json_mode: bo pub fn run( client: &ApiClient, - scope: &WorkflowScope, id: &str, idempotency_key: Option<&str>, json_mode: bool, ) -> Result<()> { let value: Value = - client.post_empty_idempotent(&scope.workflow_path(id, "/runs"), idempotency_key)?; + client.post_empty_idempotent(&workflow_path(id, "/runs"), idempotency_key)?; print_response(value, json_mode, |run: AcceptedRun| { println!("Run {} started for workflow {}.", run.id, run.workflow_id); println!( @@ -482,7 +461,6 @@ pub fn run( pub fn runs( client: &ApiClient, - scope: &WorkflowScope, id: &str, limit: Option, cursor: Option<&str>, @@ -495,7 +473,7 @@ pub fn runs( if let Some(cursor) = cursor { params.push(format!("cursor={}", urlencoding::encode(cursor))); } - let path = with_params(scope.workflow_path(id, "/runs"), ¶ms); + let path = with_params(workflow_path(id, "/runs"), ¶ms); let value: Value = client.get(&path)?; print_response(value, json_mode, |resp: WorkflowRunsResponse| { if resp.runs.is_empty() { @@ -520,14 +498,8 @@ pub fn runs( }) } -pub fn cancel( - client: &ApiClient, - scope: &WorkflowScope, - id: &str, - run_id: &str, - json_mode: bool, -) -> Result<()> { - let path = scope.workflow_path(id, &format!("/runs/{}/cancel", urlencoding::encode(run_id))); +pub fn cancel(client: &ApiClient, id: &str, run_id: &str, json_mode: bool) -> Result<()> { + let path = workflow_path(id, &format!("/runs/{}/cancel", urlencoding::encode(run_id))); client.post_no_content(&path)?; output::print_result( &json!({"workflow_id": id, "run_id": run_id, "cancel_requested": true}), @@ -565,7 +537,6 @@ fn log_detail(log: &WorkflowLog) -> String { pub fn logs( client: &ApiClient, - scope: &WorkflowScope, id: &str, range: &WorkflowTimeRange, limit: Option, @@ -579,7 +550,7 @@ pub fn logs( if let Some(cursor) = cursor { params.push(format!("cursor={}", urlencoding::encode(cursor))); } - let path = with_params(scope.workflow_path(id, "/logs"), ¶ms); + let path = with_params(workflow_path(id, "/logs"), ¶ms); let value: Value = client.get(&path)?; print_response(value, json_mode, |resp: WorkflowLogsResponse| { if resp.logs.is_empty() { @@ -616,23 +587,10 @@ pub fn logs( mod tests { use super::*; - fn scope() -> WorkflowScope<'static> { - WorkflowScope { - organization: "team alpha", - cluster: "prod/eu", - } - } - #[test] - fn paths_carry_required_scope_and_encode_ids() { - assert_eq!( - scope().path(""), - "/v1/workflows?organization=team%20alpha&cluster=prod%2Feu" - ); - assert_eq!( - scope().workflow_path("a/b", "/runs"), - "/v1/workflows/a%2Fb/runs?organization=team%20alpha&cluster=prod%2Feu" - ); + fn paths_encode_ids() { + assert_eq!(collection_path(""), "/v1/workflows"); + assert_eq!(workflow_path("a/b", "/runs"), "/v1/workflows/a%2Fb/runs"); } #[test] diff --git a/src/commands/workflow/sink.rs b/src/commands/workflow/sink.rs index 611a6fa..ddf66af 100644 --- a/src/commands/workflow/sink.rs +++ b/src/commands/workflow/sink.rs @@ -3,22 +3,16 @@ use std::io::Read; use anyhow::{Context, Result}; use serde_json::{json, Value}; -use super::{describe_sink, WorkflowScope}; +use super::describe_sink; use crate::client::ApiClient; use crate::output; const HELP_HINT: &str = "Run `rtree workflow sink --help` for sink commands and their help."; -pub fn create( - client: &ApiClient, - scope: &WorkflowScope, - workflow_id: &str, - sink: &str, - json_mode: bool, -) -> Result<()> { +pub fn create(client: &ApiClient, workflow_id: &str, sink: &str, json_mode: bool) -> Result<()> { let body = read_object(sink, "sink")?; let value: Value = client - .post(&scope.workflow_path(workflow_id, "/sinks"), &body) + .post(&super::workflow_path(workflow_id, "/sinks"), &body) .map_err(with_help_hint)?; print_sink( &value, @@ -30,7 +24,6 @@ pub fn create( pub fn update( client: &ApiClient, - scope: &WorkflowScope, workflow_id: &str, sink_id: &str, changes: &str, @@ -38,20 +31,14 @@ pub fn update( ) -> Result<()> { let body = read_object(changes, "changes")?; let value: Value = client - .patch(&sink_path(scope, workflow_id, sink_id), &body) + .patch(&sink_path(workflow_id, sink_id), &body) .map_err(with_help_hint)?; print_sink(&value, json_mode, &format!("Sink '{sink_id}' updated:")); Ok(()) } -pub fn delete( - client: &ApiClient, - scope: &WorkflowScope, - workflow_id: &str, - sink_id: &str, - json_mode: bool, -) -> Result<()> { - client.delete_no_content(&sink_path(scope, workflow_id, sink_id))?; +pub fn delete(client: &ApiClient, workflow_id: &str, sink_id: &str, json_mode: bool) -> Result<()> { + client.delete_no_content(&sink_path(workflow_id, sink_id))?; output::print_result( &json!({"workflow_id": workflow_id, "sink_id": sink_id, "deleted": true}), json_mode, @@ -60,8 +47,8 @@ pub fn delete( Ok(()) } -fn sink_path(scope: &WorkflowScope, workflow_id: &str, sink_id: &str) -> String { - scope.workflow_path( +fn sink_path(workflow_id: &str, sink_id: &str) -> String { + super::workflow_path( workflow_id, &format!("/sinks/{}", urlencoding::encode(sink_id)), ) diff --git a/src/config.rs b/src/config.rs index 90be2a3..64ec999 100644 --- a/src/config.rs +++ b/src/config.rs @@ -20,6 +20,28 @@ pub struct Config { pub default_organization: Option, #[serde(default, rename = "cluster", alias = "default_cluster")] pub default_cluster: Option, + /// IDs saved next to the default names, so requests skip name lookups and + /// survive renames. Absent in configs written before IDs were saved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_organization_id: Option, + #[serde( + default, + rename = "cluster_id", + skip_serializing_if = "Option::is_none" + )] + pub default_cluster_id: Option, +} + +impl Config { + pub fn set_default_organization(&mut self, name: Option, id: Option) { + self.default_organization = name; + self.default_organization_id = id; + } + + pub fn set_default_cluster(&mut self, name: Option, id: Option) { + self.default_cluster = name; + self.default_cluster_id = id; + } } fn config_path() -> Result { @@ -115,6 +137,47 @@ mod tests { assert_eq!(cfg.default_organization.as_deref(), Some("team_alpha")); } + #[test] + fn ids_round_trip_next_to_the_names() { + let cfg = Config { + default_organization: Some("team".into()), + default_organization_id: Some("org-id".into()), + default_cluster: Some("prod".into()), + default_cluster_id: Some("cluster-id".into()), + ..Config::default() + }; + let json = serde_json::to_value(&cfg).unwrap(); + assert_eq!(json["default_organization_id"], "org-id"); + assert_eq!(json["cluster_id"], "cluster-id"); + let back: Config = serde_json::from_value(json).unwrap(); + assert_eq!(back.default_organization_id.as_deref(), Some("org-id")); + assert_eq!(back.default_cluster_id.as_deref(), Some("cluster-id")); + } + + #[test] + fn missing_ids_are_not_written_and_old_configs_load_without_them() { + let old: Config = + serde_json::from_str(r#"{"default_organization":"team","cluster":"prod"}"#).unwrap(); + assert_eq!(old.default_organization.as_deref(), Some("team")); + assert!(old.default_organization_id.is_none()); + assert!(old.default_cluster_id.is_none()); + let json = serde_json::to_value(&old).unwrap(); + assert!(json.get("default_organization_id").is_none()); + assert!(json.get("cluster_id").is_none()); + } + + #[test] + fn setting_a_default_replaces_or_clears_its_id() { + let mut cfg = Config::default(); + cfg.set_default_organization(Some("team".into()), Some("org-id".into())); + cfg.set_default_organization(Some("other".into()), None); + assert_eq!(cfg.default_organization.as_deref(), Some("other")); + assert!(cfg.default_organization_id.is_none()); + cfg.set_default_cluster(Some("prod".into()), Some("cluster-id".into())); + cfg.set_default_cluster(None, None); + assert!(cfg.default_cluster.is_none() && cfg.default_cluster_id.is_none()); + } + #[test] fn config_serializes_cluster_key() { let cfg = Config { diff --git a/src/main.rs b/src/main.rs index c32f33b..f3c6e70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,7 +21,7 @@ use cli::{ IntegrationKind, OrganizationCommand, ServiceAccountCommand, ShellType, TableCommand, WorkflowCommand, WorkflowSinkCommand, }; -use client::ApiClient; +use client::{ApiClient, SavedIds}; use constants::DEFAULT_API_URL; fn resolve_url_from_sources( @@ -121,6 +121,54 @@ fn resolve_effective_org(client: &ApiClient, cli_org: Option) -> Option< resolve_effective_org_with(explicit_org, || org::first_organization_name(client)) } +/// Saved IDs apply only to selections that come from the config. A flag or +/// environment variable names its target explicitly and is resolved by name. +fn saved_ids_from_sources( + cli_org: Option<&str>, + env_org: Option<&str>, + cli_cluster: Option<&str>, + env_cluster: Option<&str>, + cfg: &config::Config, +) -> SavedIds { + let pair = |name: &Option, id: &Option| name.clone().zip(id.clone()); + SavedIds { + organization: (cli_org.is_none() && env_org.is_none()) + .then(|| pair(&cfg.default_organization, &cfg.default_organization_id)) + .flatten(), + cluster: (cli_cluster.is_none() && env_cluster.is_none()) + .then(|| pair(&cfg.default_cluster, &cfg.default_cluster_id)) + .flatten(), + } +} + +fn saved_ids(cli_org: Option<&str>, cli_cluster: Option<&str>) -> SavedIds { + let Ok(cfg) = config::load() else { + return SavedIds::default(); + }; + saved_ids_from_sources( + cli_org, + std::env::var("RAWTREE_ORG").ok().as_deref(), + cli_cluster, + std::env::var("RAWTREE_CLUSTER").ok().as_deref(), + &cfg, + ) +} + +/// A rejected saved ID is never replaced by a name lookup, so say how to refresh it. +fn explain_rejected_saved_ids(client: &ApiClient, error: anyhow::Error) -> anyhow::Error { + let message = format!("{error:#}"); + if client.used_saved_ids() + && error.downcast_ref::().is_none() + && (message.contains("(403)") || message.contains("(404)")) + { + anyhow::anyhow!( + "{message}\nThe saved organization or cluster ID was rejected; it may have been deleted or your access may have changed. Run `rtree organization use ` and `rtree cluster use `, or `rtree login` again." + ) + } else { + error + } +} + fn read_stdin() -> Result { let mut buf = String::new(); io::stdin().read_to_string(&mut buf)?; @@ -172,20 +220,25 @@ fn require_organization(organization: Option<&str>) -> Result<&str> { }) } -fn require_workflow_scope<'a>( - organization: Option<&'a str>, - cluster: Option<&'a str>, -) -> Result> { - let organization = require_organization(organization)?; +/// API keys are bound to a cluster, so the backend takes their tenant from the +/// key; user credentials must select one. +fn require_workflow_scope( + client: &ApiClient, + organization: Option<&str>, + cluster: Option<&str>, +) -> Result { + if client.has_api_key()? { + return Ok(client::Scope::new(organization, cluster)); + } + if organization.is_none() && !cluster.is_some_and(client::is_uuid) { + require_organization(organization)?; + } let cluster = cluster.ok_or_else(|| { anyhow::anyhow!( "No cluster specified. Use --cluster, RAWTREE_CLUSTER env, or `rtree cluster use `" ) })?; - Ok(commands::workflow::WorkflowScope { - organization, - cluster, - }) + Ok(client::Scope::new(organization, Some(cluster))) } fn main() -> ExitCode { @@ -220,551 +273,570 @@ fn run(cli: Cli) -> Result { ApiClient::new(url.clone(), Some(key)) } else { ApiClient::from_saved_config(url.clone()) - }; + } + .with_saved_ids(saved_ids(cli_org.as_deref(), cli_cluster.as_deref())); let effective_cluster = resolve_cluster(cli_cluster.clone()); let login_cluster = resolve_login_cluster(cli_cluster); - match command { - Command::Login { - device_auth, - no_browser, - timeout_seconds, - database, - } => { - if device_auth && cli_api_key.is_some() { - anyhow::bail!("--device-auth cannot be used with --api-key"); - } - let client = ApiClient::new(url.clone(), None); - if let Some(api_key) = cli_api_key.or_else(|| { - std::env::var("RAWTREE_API_KEY") - .ok() - .filter(|_| !device_auth) - }) { - commands::auth::login_with_api_key( - &client, - &api_key, - cli_org.clone(), - login_cluster.clone(), - database, - json, - ) - } else { - return commands::auth::login_with_browser( - &client, - commands::auth::BrowserLoginOptions { - device_auth, - no_browser, - timeout_seconds, - }, - cli_org.clone(), - login_cluster.clone(), - database, - json, - ); - } - } - Command::Logout => commands::auth::logout(json), - Command::Database { action } => match action { - DatabaseCommand::List => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::database::list( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ) + let result = (|| -> Result { + match command { + Command::Login { + device_auth, + no_browser, + timeout_seconds, + database, + } => { + if device_auth && cli_api_key.is_some() { + anyhow::bail!("--device-auth cannot be used with --api-key"); + } + let client = ApiClient::new(url.clone(), None); + if let Some(api_key) = cli_api_key.or_else(|| { + std::env::var("RAWTREE_API_KEY") + .ok() + .filter(|_| !device_auth) + }) { + commands::auth::login_with_api_key( + &client, + &api_key, + cli_org.clone(), + login_cluster.clone(), + database, + json, + ) + } else { + return commands::auth::login_with_browser( + &client, + commands::auth::BrowserLoginOptions { + device_auth, + no_browser, + timeout_seconds, + }, + cli_org.clone(), + login_cluster.clone(), + database, + json, + ); + } } - DatabaseCommand::Create { name, s3_storage } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::database::create( - &client, - &name, - effective_org.as_deref(), - effective_cluster.as_deref(), - s3_storage, - json, - ) + Command::Logout => commands::auth::logout(json), + Command::Database { action } => match action { + DatabaseCommand::List => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + commands::database::list( + &client, + effective_org.as_deref(), + effective_cluster.as_deref(), + json, + ) + } + DatabaseCommand::Create { name, s3_storage } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + commands::database::create( + &client, + &name, + effective_org.as_deref(), + effective_cluster.as_deref(), + s3_storage, + json, + ) + } + DatabaseCommand::Use { name } => commands::database::use_database(&name, json), + DatabaseCommand::Delete { name } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + commands::database::delete( + &client, + &name, + effective_org.as_deref(), + effective_cluster.as_deref(), + json, + ) + } + }, + Command::FederationIssuer { action } => { + let organization = resolve_explicit_org(cli_org); + commands::federation_issuer::run(&client, organization.as_deref(), action, json) } - DatabaseCommand::Use { name } => commands::database::use_database(&name, json), - DatabaseCommand::Delete { name } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::database::delete( + Command::FederationRule { action } => { + let organization = resolve_explicit_org(cli_org); + commands::federation_rule::run( &client, - &name, - effective_org.as_deref(), + organization.as_deref(), effective_cluster.as_deref(), + action, json, ) } - }, - Command::FederationIssuer { action } => { - let organization = resolve_explicit_org(cli_org); - commands::federation_issuer::run(&client, organization.as_deref(), action, json) - } - Command::FederationRule { action } => { - let organization = resolve_explicit_org(cli_org); - commands::federation_rule::run( - &client, - organization.as_deref(), - effective_cluster.as_deref(), - action, - json, - ) - } - Command::ServiceAccount { action } => { - let organization = resolve_explicit_org(cli_org); - match action { - ServiceAccountCommand::List => { - commands::service_account::list(&client, organization.as_deref(), json) - } - ServiceAccountCommand::Create { - name, - description, - role, - } => commands::service_account::create( - &client, - organization.as_deref(), - commands::service_account::CreateServiceAccount { + Command::ServiceAccount { action } => { + let organization = resolve_explicit_org(cli_org); + match action { + ServiceAccountCommand::List => { + commands::service_account::list(&client, organization.as_deref(), json) + } + ServiceAccountCommand::Create { name, description, role, - }, - json, - ), - } - } - Command::Organization { action } => match action { - OrganizationCommand::List => commands::organization::list(&client, json), - OrganizationCommand::Create { name } => { - commands::organization::create(&client, &name, json) - } - OrganizationCommand::Use { name } => { - commands::organization::use_organization(&name, json) - } - OrganizationCommand::Rename { old, new_name } => { - commands::organization::rename(&client, &old, &new_name, json) - } - OrganizationCommand::Delete { name } => { - commands::organization::delete(&client, &name, json) + } => commands::service_account::create( + &client, + organization.as_deref(), + commands::service_account::CreateServiceAccount { + name, + description, + role, + }, + json, + ), + } } - }, - Command::Cluster { action } => { - let effective_org = match &action { - ClusterCommand::Use { .. } | ClusterCommand::Sizes => None, - _ => resolve_effective_org(&client, cli_org.clone()), - }; - match action { - ClusterCommand::Use { name } => commands::cluster::use_cluster(&name, json), - ClusterCommand::List => { - commands::cluster::list(&client, effective_org.as_deref(), json) + Command::Organization { action } => match action { + OrganizationCommand::List => commands::organization::list(&client, json), + OrganizationCommand::Create { name } => { + commands::organization::create(&client, &name, json) } - ClusterCommand::Regions => { - commands::cluster::regions(&client, effective_org.as_deref(), json) + OrganizationCommand::Use { name } => { + commands::organization::use_organization(&client, &name, json) } - ClusterCommand::Sizes => commands::cluster::sizes(&client, json), - ClusterCommand::Create { - region_id, - name, - replicas, - min_size, - max_size, - idle_timeout_minutes, - s3_storage, - identity, - } => commands::cluster::create( - &client, - commands::cluster::ClusterCreateOptions { - region_id: ®ion_id, - organization: effective_org.as_deref(), - name: &name, + OrganizationCommand::Rename { old, new_name } => { + commands::organization::rename(&client, &old, &new_name, json) + } + OrganizationCommand::Delete { name } => { + commands::organization::delete(&client, &name, json) + } + }, + Command::Cluster { action } => { + let effective_org = match &action { + ClusterCommand::Use { .. } | ClusterCommand::Sizes => None, + _ => resolve_effective_org(&client, cli_org.clone()), + }; + match action { + ClusterCommand::Use { name } => commands::cluster::use_cluster( + &client, + &name, + resolve_explicit_org(cli_org.clone()).as_deref(), + json, + ), + ClusterCommand::List => { + commands::cluster::list(&client, effective_org.as_deref(), json) + } + ClusterCommand::Regions => { + commands::cluster::regions(&client, effective_org.as_deref(), json) + } + ClusterCommand::Sizes => commands::cluster::sizes(&client, json), + ClusterCommand::Create { + region_id, + name, replicas, min_size, max_size, idle_timeout_minutes, s3_storage, identity, - }, - json, - ), - ClusterCommand::Status { name_or_id } => { - commands::cluster::status(&client, &name_or_id, effective_org.as_deref(), json) - } - ClusterCommand::Update { - name_or_id, - name, - idle_timeout_minutes, - } => commands::cluster::update( - &client, - &name_or_id, - effective_org.as_deref(), - name.as_deref(), - idle_timeout_minutes, - json, - ), - ClusterCommand::Stop { name_or_id } => { - commands::cluster::stop(&client, &name_or_id, effective_org.as_deref(), json) - } - ClusterCommand::Resume { name_or_id } => { - commands::cluster::resume(&client, &name_or_id, effective_org.as_deref(), json) - } - ClusterCommand::Delete { name_or_id } => { - commands::cluster::delete(&client, &name_or_id, effective_org.as_deref(), json) - } - } - } - Command::ApiKey { action } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - match action { - ApiKeyCommand::List => commands::keys::list( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ), - ApiKeyCommand::Create { - database, - name, - permission, - expires_at, - } => { - let database = resolve_optional_database(database); - commands::keys::create( + } => commands::cluster::create( &client, - database.as_deref(), - effective_org.as_deref(), - effective_cluster.as_deref(), - commands::keys::CreateApiKeyRequest { + commands::cluster::ClusterCreateOptions { + region_id: ®ion_id, + organization: effective_org.as_deref(), name: &name, - permission: &permission, - expires_at: expires_at.as_deref(), + replicas, + min_size, + max_size, + idle_timeout_minutes, + s3_storage, + identity, }, json, - ) - } - ApiKeyCommand::Delete { id } => commands::keys::delete( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - id, - json, - ), - } - } - Command::Table { action } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - match action { - TableCommand::List { database } => { - let database = resolve_database(database)?; - commands::table::list( + ), + ClusterCommand::Status { name_or_id } => commands::cluster::status( &client, - &database, + &name_or_id, effective_org.as_deref(), - effective_cluster.as_deref(), json, - ) - } - TableCommand::Describe { database, table } => { - let database = resolve_database(database)?; - commands::table::describe( + ), + ClusterCommand::Update { + name_or_id, + name, + idle_timeout_minutes, + } => commands::cluster::update( &client, - &database, + &name_or_id, effective_org.as_deref(), - effective_cluster.as_deref(), - &table, + name.as_deref(), + idle_timeout_minutes, json, - ) + ), + ClusterCommand::Stop { name_or_id } => commands::cluster::stop( + &client, + &name_or_id, + effective_org.as_deref(), + json, + ), + ClusterCommand::Resume { name_or_id } => commands::cluster::resume( + &client, + &name_or_id, + effective_org.as_deref(), + json, + ), + ClusterCommand::Delete { name_or_id } => commands::cluster::delete( + &client, + &name_or_id, + effective_org.as_deref(), + json, + ), } - TableCommand::Create { - database, - table, - sorting_key, - } => { - let database = resolve_database(database)?; - commands::table::create( + } + Command::ApiKey { action } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + match action { + ApiKeyCommand::List => commands::keys::list( &client, - &database, effective_org.as_deref(), effective_cluster.as_deref(), - &table, - sorting_key.as_deref(), json, - ) - } - TableCommand::Update { - database, - table, - sorting_key, - } => { - let database = resolve_database(database)?; - commands::table::update( + ), + ApiKeyCommand::Create { + database, + name, + permission, + expires_at, + } => { + let database = resolve_optional_database(database); + commands::keys::create( + &client, + database.as_deref(), + effective_org.as_deref(), + effective_cluster.as_deref(), + commands::keys::CreateApiKeyRequest { + name: &name, + permission: &permission, + expires_at: expires_at.as_deref(), + }, + json, + ) + } + ApiKeyCommand::Delete { id } => commands::keys::delete( &client, - &database, effective_org.as_deref(), effective_cluster.as_deref(), - &table, - &sorting_key, + id, json, - ) + ), } } - } - Command::Integration { action } => match action { - IntegrationCommand::List => { - let organization = resolve_explicit_org(cli_org); - commands::integration::list(&client, organization.as_deref(), json) - } - IntegrationCommand::Add { - kind: IntegrationKind::Slack, - } => { - let effective_org = resolve_effective_org(&client, cli_org); - let organization = require_organization(effective_org.as_deref())?; - commands::integration::add_slack( - &commands::open::resolve_ui_base_url(&url), - organization, - json, - ) + Command::Table { action } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + match action { + TableCommand::List { database } => { + let database = resolve_database(database)?; + commands::table::list( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + json, + ) + } + TableCommand::Describe { database, table } => { + let database = resolve_database(database)?; + commands::table::describe( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + &table, + json, + ) + } + TableCommand::Create { + database, + table, + sorting_key, + } => { + let database = resolve_database(database)?; + commands::table::create( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + &table, + sorting_key.as_deref(), + json, + ) + } + TableCommand::Update { + database, + table, + sorting_key, + } => { + let database = resolve_database(database)?; + commands::table::update( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + &table, + &sorting_key, + json, + ) + } + } } - }, - Command::Workflow { action } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - let scope = - require_workflow_scope(effective_org.as_deref(), effective_cluster.as_deref())?; - match action { - WorkflowCommand::List => commands::workflow::list(&client, &scope, json), - WorkflowCommand::Get { id } => commands::workflow::get(&client, &scope, &id, json), - WorkflowCommand::Create { - name, - database, - sql, - schedule_cron, - schedule_enabled, - sinks, - } => { - ensure_single_stdin_reader(Some(&sql), &sinks)?; - commands::workflow::create( - &client, - &scope, - commands::workflow::CreateWorkflow { - name, - database: resolve_database(database)?, - sql: read_sql_arg(sql)?, - cron: schedule_cron.and_then(|cron| cron.0), - enabled: schedule_enabled, - sinks, - }, - json, - ) + Command::Integration { action } => match action { + IntegrationCommand::List => { + let organization = resolve_explicit_org(cli_org); + commands::integration::list(&client, organization.as_deref(), json) } - WorkflowCommand::Update { - id, - name, - database, - sql, - schedule_cron, - schedule_enabled, - sinks, - clear_sinks, + IntegrationCommand::Add { + kind: IntegrationKind::Slack, } => { - ensure_single_stdin_reader(sql.as_deref(), &sinks)?; - commands::workflow::update( - &client, - &scope, - &id, - commands::workflow::UpdateWorkflow { - name, - database, - sql: sql.map(read_sql_arg).transpose()?, - cron: schedule_cron.map(|cron| cron.0), - enabled: schedule_enabled, - sinks: (clear_sinks || !sinks.is_empty()).then_some(sinks), - }, + let effective_org = resolve_effective_org(&client, cli_org); + let organization = require_organization(effective_org.as_deref())?; + commands::integration::add_slack( + &commands::open::resolve_ui_base_url(&url), + organization, json, ) } - WorkflowCommand::Delete { id } => { - commands::workflow::delete(&client, &scope, &id, json) - } - WorkflowCommand::Run { - id, - idempotency_key, - } => { - commands::workflow::run(&client, &scope, &id, idempotency_key.as_deref(), json) - } - WorkflowCommand::Runs { id, limit, cursor } => { - commands::workflow::runs(&client, &scope, &id, limit, cursor.as_deref(), json) - } - WorkflowCommand::Cancel { id, run_id } => { - commands::workflow::cancel(&client, &scope, &id, &run_id, json) - } - WorkflowCommand::Logs { - id, - range, - limit, - cursor, - } => commands::workflow::logs( + }, + Command::Workflow { action } => { + let effective_org = if client.has_api_key()? { + resolve_explicit_org(cli_org.clone()) + } else { + resolve_effective_org(&client, cli_org.clone()) + }; + let scope = require_workflow_scope( &client, - &scope, - &id, - &range, - limit, - cursor.as_deref(), - json, - ), - WorkflowCommand::Sink { action } => match action { - WorkflowSinkCommand::Create { workflow_id, sink } => { - commands::workflow::sink::create(&client, &scope, &workflow_id, &sink, json) + effective_org.as_deref(), + effective_cluster.as_deref(), + )?; + let client = client.with_scope(scope); + match action { + WorkflowCommand::List => commands::workflow::list(&client, json), + WorkflowCommand::Get { id } => commands::workflow::get(&client, &id, json), + WorkflowCommand::Create { + name, + database, + sql, + schedule_cron, + schedule_enabled, + sinks, + } => { + ensure_single_stdin_reader(Some(&sql), &sinks)?; + commands::workflow::create( + &client, + commands::workflow::CreateWorkflow { + name, + database: resolve_database(database)?, + sql: read_sql_arg(sql)?, + cron: schedule_cron.and_then(|cron| cron.0), + enabled: schedule_enabled, + sinks, + }, + json, + ) } - WorkflowSinkCommand::Update { - workflow_id, - sink_id, - changes, - } => commands::workflow::sink::update( - &client, - &scope, - &workflow_id, - &sink_id, - &changes, - json, - ), - WorkflowSinkCommand::Delete { - workflow_id, - sink_id, - } => commands::workflow::sink::delete( + WorkflowCommand::Update { + id, + name, + database, + sql, + schedule_cron, + schedule_enabled, + sinks, + clear_sinks, + } => { + ensure_single_stdin_reader(sql.as_deref(), &sinks)?; + commands::workflow::update( + &client, + &id, + commands::workflow::UpdateWorkflow { + name, + database, + sql: sql.map(read_sql_arg).transpose()?, + cron: schedule_cron.map(|cron| cron.0), + enabled: schedule_enabled, + sinks: (clear_sinks || !sinks.is_empty()).then_some(sinks), + }, + json, + ) + } + WorkflowCommand::Delete { id } => { + commands::workflow::delete(&client, &id, json) + } + WorkflowCommand::Run { + id, + idempotency_key, + } => commands::workflow::run(&client, &id, idempotency_key.as_deref(), json), + WorkflowCommand::Runs { id, limit, cursor } => { + commands::workflow::runs(&client, &id, limit, cursor.as_deref(), json) + } + WorkflowCommand::Cancel { id, run_id } => { + commands::workflow::cancel(&client, &id, &run_id, json) + } + WorkflowCommand::Logs { + id, + range, + limit, + cursor, + } => commands::workflow::logs( &client, - &scope, - &workflow_id, - &sink_id, + &id, + &range, + limit, + cursor.as_deref(), json, ), - }, + WorkflowCommand::Sink { action } => match action { + WorkflowSinkCommand::Create { workflow_id, sink } => { + commands::workflow::sink::create(&client, &workflow_id, &sink, json) + } + WorkflowSinkCommand::Update { + workflow_id, + sink_id, + changes, + } => commands::workflow::sink::update( + &client, + &workflow_id, + &sink_id, + &changes, + json, + ), + WorkflowSinkCommand::Delete { + workflow_id, + sink_id, + } => { + commands::workflow::sink::delete(&client, &workflow_id, &sink_id, json) + } + }, + } } - } - Command::Logs { - search, - methods, - status_codes, - levels, - sources, - user_agent, - host, - paths, - min_duration_ms, - max_duration_ms, - limit, - offset, - since, - until, - start_time, - end_time, - } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::logs::logs( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - search.as_deref(), - &methods, - &status_codes, - &levels, - &sources, - user_agent.as_deref(), - host.as_deref(), - &paths, + Command::Logs { + search, + methods, + status_codes, + levels, + sources, + user_agent, + host, + paths, min_duration_ms, max_duration_ms, limit, offset, - since.as_deref(), - until.as_deref(), - start_time.as_deref(), - end_time.as_deref(), - json, - ) - } - Command::Query { - database, - sql_positional, - sql, - limit, - } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - let database = resolve_database(database)?; - let sql = resolve_sql(sql_positional, sql)?; - commands::query::query( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &sql, + since, + until, + start_time, + end_time, + } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + commands::logs::logs( + &client, + effective_org.as_deref(), + effective_cluster.as_deref(), + search.as_deref(), + &methods, + &status_codes, + &levels, + &sources, + user_agent.as_deref(), + host.as_deref(), + &paths, + min_duration_ms, + max_duration_ms, + limit, + offset, + since.as_deref(), + until.as_deref(), + start_time.as_deref(), + end_time.as_deref(), + json, + ) + } + Command::Query { + database, + sql_positional, + sql, limit, - json, - ) - } - Command::Format(args) => { - let database = resolve_optional_database(args.database); - let sql = resolve_sql(args.sql_positional, args.sql)?; - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::format::format( - &client, - database.as_deref(), - effective_org.as_deref(), - effective_cluster.as_deref(), - &sql, - json, - ) - } - Command::Insert { - database, - table, - data, - file, - url, - transform, - } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - let database = resolve_database(database)?; - - commands::insert::insert( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &table, - data.as_deref(), - file.as_deref(), - url.as_deref(), - transform.as_deref(), - json, - ) - } - Command::Feedback(args) => commands::feedback::submit(&client, args, json), - Command::Ping => commands::ping::ping(&client, json), - Command::Docs => commands::docs::docs(&client), - Command::Status => commands::status::status(&url, json), - Command::Update => commands::update::update(json), - Command::Open { database } => { - let ui_base_url = commands::open::resolve_ui_base_url(&url); - let effective_org = resolve_effective_org(&client, cli_org); - let database = resolve_optional_database(database); - commands::open::open( - &ui_base_url, - effective_org.as_deref(), - effective_cluster.as_deref(), - database.as_deref(), - json, - ) - } - Command::Completions { shell } => { - let shell = match shell { - ShellType::Bash => clap_complete::Shell::Bash, - ShellType::Zsh => clap_complete::Shell::Zsh, - ShellType::Fish => clap_complete::Shell::Fish, - }; - generate(shell, &mut Cli::command(), "rtree", &mut io::stdout()); - Ok(()) - } - }?; - Ok(ExitCode::SUCCESS) + } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + let database = resolve_database(database)?; + let sql = resolve_sql(sql_positional, sql)?; + commands::query::query( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + &sql, + limit, + json, + ) + } + Command::Format(args) => { + let database = resolve_optional_database(args.database); + let sql = resolve_sql(args.sql_positional, args.sql)?; + let effective_org = resolve_effective_org(&client, cli_org.clone()); + commands::format::format( + &client, + database.as_deref(), + effective_org.as_deref(), + effective_cluster.as_deref(), + &sql, + json, + ) + } + Command::Insert { + database, + table, + data, + file, + url, + transform, + } => { + let effective_org = resolve_effective_org(&client, cli_org.clone()); + let database = resolve_database(database)?; + + commands::insert::insert( + &client, + &database, + effective_org.as_deref(), + effective_cluster.as_deref(), + &table, + data.as_deref(), + file.as_deref(), + url.as_deref(), + transform.as_deref(), + json, + ) + } + Command::Feedback(args) => commands::feedback::submit(&client, args, json), + Command::Ping => commands::ping::ping(&client, json), + Command::Docs => commands::docs::docs(&client), + Command::Status => commands::status::status(&url, json), + Command::Update => commands::update::update(json), + Command::Open { database } => { + let ui_base_url = commands::open::resolve_ui_base_url(&url); + let effective_org = resolve_effective_org(&client, cli_org); + let database = resolve_optional_database(database); + commands::open::open( + &ui_base_url, + effective_org.as_deref(), + effective_cluster.as_deref(), + database.as_deref(), + json, + ) + } + Command::Completions { shell } => { + let shell = match shell { + ShellType::Bash => clap_complete::Shell::Bash, + ShellType::Zsh => clap_complete::Shell::Zsh, + ShellType::Fish => clap_complete::Shell::Fish, + }; + generate(shell, &mut Cli::command(), "rtree", &mut io::stdout()); + Ok(()) + } + }?; + Ok(ExitCode::SUCCESS) + })(); + result.map_err(|error| explain_rejected_saved_ids(&client, error)) } #[cfg(test)] @@ -775,9 +847,51 @@ mod tests { use super::{ effective_json_mode, resolve_cluster_from_sources, resolve_database_from_sources, resolve_effective_org_with, resolve_login_cluster_from_sources, resolve_org_from_sources, - resolve_url_from_sources, Cli, + resolve_url_from_sources, saved_ids_from_sources, Cli, }; + fn config_with_ids() -> super::config::Config { + super::config::Config { + default_organization: Some("team".into()), + default_organization_id: Some("org-id".into()), + default_cluster: Some("prod".into()), + default_cluster_id: Some("cluster-id".into()), + ..Default::default() + } + } + + #[test] + fn saved_ids_apply_only_to_config_selections() { + let cfg = config_with_ids(); + let saved = saved_ids_from_sources(None, None, None, None, &cfg); + assert_eq!(saved.organization, Some(("team".into(), "org-id".into()))); + assert_eq!(saved.cluster, Some(("prod".into(), "cluster-id".into()))); + + let saved = saved_ids_from_sources(Some("team"), None, None, Some("prod"), &cfg); + assert!( + saved.organization.is_none(), + "an --org flag is resolved by name" + ); + assert!( + saved.cluster.is_none(), + "RAWTREE_CLUSTER is resolved by name" + ); + + let saved = saved_ids_from_sources(None, Some("team"), Some("prod"), None, &cfg); + assert!(saved.organization.is_none() && saved.cluster.is_none()); + } + + #[test] + fn configs_without_ids_have_nothing_saved() { + let cfg = super::config::Config { + default_organization: Some("team".into()), + default_cluster: Some("prod".into()), + ..Default::default() + }; + let saved = saved_ids_from_sources(None, None, None, None, &cfg); + assert!(saved.organization.is_none() && saved.cluster.is_none()); + } + #[test] fn json_is_automatic_only_for_non_terminal_login() { for (args, terminal, expected) in [ diff --git a/src/org.rs b/src/org.rs index d13fd35..456cbcd 100644 --- a/src/org.rs +++ b/src/org.rs @@ -5,8 +5,10 @@ use crate::client::ApiClient; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OrganizationItem { + #[serde(default, skip_serializing)] + pub organization_id: String, pub name: String, - pub role: String, + pub role: Option, } #[derive(Debug, Deserialize)] @@ -27,43 +29,7 @@ pub fn first_organization_name(client: &ApiClient) -> Option { .map(|org| org.name) } -pub fn databases_collection_path(organization: Option<&str>, cluster: Option<&str>) -> String { - scoped_path("/v1/databases", organization, cluster) -} - -fn append_scope_params(path: &mut String, organization: Option<&str>, cluster: Option<&str>) { - if let Some(org) = organization { - path.push_str("&organization="); - path.push_str(&urlencoding::encode(org)); - } - if let Some(cluster) = cluster { - path.push_str("&cluster="); - path.push_str(&urlencoding::encode(cluster)); - } -} - -pub fn scoped_path(path: &str, organization: Option<&str>, cluster: Option<&str>) -> String { - let mut scoped = path.to_string(); - let mut params = Vec::new(); - if let Some(org) = organization { - params.push(format!("organization={}", urlencoding::encode(org))); - } - if let Some(cluster) = cluster { - params.push(format!("cluster={}", urlencoding::encode(cluster))); - } - if !params.is_empty() { - scoped.push(if path.contains('?') { '&' } else { '?' }); - scoped.push_str(¶ms.join("&")); - } - scoped -} - -pub fn database_scoped_path( - database: &str, - suffix: &str, - organization: Option<&str>, - cluster: Option<&str>, -) -> String { +pub fn database_path(database: &str, suffix: &str) -> String { let normalized_suffix = if suffix.is_empty() { String::new() } else if suffix.starts_with('/') { @@ -77,75 +43,37 @@ pub fn database_scoped_path( } else { '?' }; - let mut path = format!( + format!( "/v1{normalized_suffix}{sep}database={}", urlencoding::encode(database) - ); - append_scope_params(&mut path, organization, cluster); - path + ) } #[cfg(test)] mod tests { - use super::{database_scoped_path, databases_collection_path, scoped_path}; - - #[test] - fn databases_collection_path_uses_organization_filter() { - assert_eq!( - databases_collection_path(Some("team alpha"), None), - "/v1/databases?organization=team%20alpha" - ); - assert_eq!(databases_collection_path(None, None), "/v1/databases"); - assert_eq!( - databases_collection_path(Some("team alpha"), Some("prod/eu")), - "/v1/databases?organization=team%20alpha&cluster=prod%2Feu" - ); - } - - #[test] - fn database_scoped_path_adds_database_query_param() { - let path = database_scoped_path("analytics", "/query", None, None); - assert_eq!(path, "/v1/query?database=analytics"); - } + use super::database_path; #[test] - fn database_scoped_path_adds_organization_query_param() { - let path = database_scoped_path( - "analytics", - "/query", - Some("team_alpha"), - Some("production"), - ); + fn database_path_adds_database_query_param() { assert_eq!( - path, - "/v1/query?database=analytics&organization=team_alpha&cluster=production" + database_path("analytics", "/query"), + "/v1/query?database=analytics" ); } #[test] - fn database_scoped_path_accepts_suffix_without_leading_slash() { - let path = database_scoped_path("analytics", "tables", Some("team_alpha"), None); + fn database_path_accepts_suffix_without_leading_slash() { assert_eq!( - path, - "/v1/tables?database=analytics&organization=team_alpha" + database_path("analytics", "tables"), + "/v1/tables?database=analytics" ); } #[test] - fn database_scoped_path_appends_to_existing_query() { - let path = - database_scoped_path("analytics db", "/tables/events?url=x", Some("team a"), None); + fn database_path_appends_to_existing_query() { assert_eq!( - path, - "/v1/tables/events?url=x&database=analytics%20db&organization=team%20a" - ); - } - - #[test] - fn scoped_path_adds_cluster_without_organization() { - assert_eq!( - scoped_path("/v1/databases", None, Some("production")), - "/v1/databases?cluster=production" + database_path("analytics db", "/tables/events?url=x"), + "/v1/tables/events?url=x&database=analytics%20db" ); } } @@ -162,6 +90,9 @@ struct OrganizationsResponse { } pub fn organization_path(client: &ApiClient, organization: Option<&str>) -> Result { + if let Some(id) = organization.and_then(|name| client.saved_organization_id(name)) { + return Ok(format!("/v1/organizations/{}", urlencoding::encode(&id))); + } let response: OrganizationsResponse = client.get("/v1/organizations")?; let selected = match organization { Some(name) => response diff --git a/tests/api_contracts.rs b/tests/api_contracts.rs index 3bb6549..4775199 100644 --- a/tests/api_contracts.rs +++ b/tests/api_contracts.rs @@ -11,11 +11,21 @@ fn run( ) -> (Value, Value, Value) { let mut command = vec!["--org", "team alpha", "--cluster", "prod/eu", "--json"]; command.extend_from_slice(args); - let (output, saved, bodies) = common::run_cli( - &[(format!("{method} {path}"), "200 OK", response)], - &command, - &config, - ); + let bound_lookup = config["token"] + .as_str() + .is_some_and(|token| token.starts_with("rt_")) + .then(|| { + [ + common::key_organization("team alpha"), + common::bound_cluster("prod/eu"), + ] + }); + let responses: Vec<_> = bound_lookup + .into_iter() + .flatten() + .chain([(format!("{method} {path}"), "200 OK", response)]) + .collect(); + let (output, saved, bodies) = common::run_cli(&responses, &command, &config); assert!( output.status.success(), "{}", @@ -24,7 +34,7 @@ fn run( ( serde_json::from_slice(&output.stdout).unwrap(), saved, - bodies[0].clone(), + bodies.last().unwrap().clone(), ) } @@ -34,7 +44,7 @@ fn database_create_reads_nested_response_and_saves_requested_context() { let (result, saved, body) = run( &["database", "create", "analytics"], "POST", - "/v1/databases?organization=team%20alpha&cluster=prod%2Feu", + "/v1/databases", response.clone(), json!({"token": "rt_fixture", "default_organization": "old-org", "database": "old-db"}), ); @@ -43,6 +53,8 @@ fn database_create_reads_nested_response_and_saves_requested_context() { assert_eq!(saved["token"], "rt_fixture"); assert_eq!(saved["default_organization"], "team alpha"); assert_eq!(saved["cluster"], "prod/eu"); + assert_eq!(saved["default_organization_id"], common::ORG_ID); + assert_eq!(saved["cluster_id"], common::CLUSTER_ID); assert_eq!(saved["database"], "analytics"); } @@ -50,11 +62,15 @@ fn database_create_reads_nested_response_and_saves_requested_context() { fn database_create_failure_does_not_overwrite_config() { let config = json!({"token": "rt_fixture", "default_organization": "team", "cluster": "prod", "database": "old-db"}); let (output, saved, _) = common::run_cli( - &[( - "POST /v1/databases?organization=team&cluster=prod".to_string(), - "400 Bad Request", - json!({"message": "Invalid database name"}), - )], + &[ + common::key_organization("team"), + common::bound_cluster("prod"), + ( + "POST /v1/databases".to_string(), + "400 Bad Request", + json!({"message": "Invalid database name"}), + ), + ], &["--json", "database", "create", "invalid-name"], &config, ); @@ -71,18 +87,14 @@ fn database_list_preserves_current_metadata_without_obsolete_organization() { let (result, _, _) = run( &["database", "list"], "GET", - "/v1/databases?organization=team%20alpha&cluster=prod%2Feu", + "/v1/databases", response.clone(), json!({}), ); assert_eq!(result, response); let (output, _, _) = common::run_cli( - &[( - "GET /v1/databases?organization=team&cluster=prod".to_string(), - "200 OK", - response, - )], + &[("GET /v1/databases".to_string(), "200 OK", response)], &["--org", "team", "--cluster", "prod", "database", "list"], &json!({}), ); @@ -104,7 +116,7 @@ fn key_list_and_delete_are_cluster_scoped_even_with_a_saved_database() { let (result, _, _) = run( &["api-key", "list"], "GET", - "/v1/api-keys?organization=team%20alpha&cluster=prod%2Feu", + "/v1/api-keys", response.clone(), config.clone(), ); @@ -112,7 +124,7 @@ fn key_list_and_delete_are_cluster_scoped_even_with_a_saved_database() { let (result, _, _) = run( &["api-key", "delete", "11111111-1111-4111-8111-111111111111"], "DELETE", - "/v1/api-keys/11111111-1111-4111-8111-111111111111?organization=team%20alpha&cluster=prod%2Feu", + "/v1/api-keys/11111111-1111-4111-8111-111111111111", json!({"deleted": true}), config, ); @@ -126,22 +138,17 @@ fn key_list_and_delete_are_cluster_scoped_even_with_a_saved_database() { #[test] fn key_create_uses_server_default_or_an_explicit_or_saved_database() { for (selectors, config, query, database) in [ - ( - vec![], - json!({}), - "organization=team%20alpha&cluster=prod%2Feu", - "default", - ), + (vec![], json!({}), "", "default"), ( vec!["--database", "analytics"], json!({"database": "old-db"}), - "database=analytics&organization=team%20alpha&cluster=prod%2Feu", + "database=analytics", "analytics", ), ( vec![], json!({"database": "saved-db"}), - "database=saved-db&organization=team%20alpha&cluster=prod%2Feu", + "database=saved-db", "saved-db", ), ] { @@ -158,7 +165,14 @@ fn key_create_uses_server_default_or_an_explicit_or_saved_database() { let (result, _, body) = run( &args, "POST", - &format!("/v1/api-keys?{query}"), + &format!( + "/v1/api-keys{}", + if query.is_empty() { + String::new() + } else { + format!("?{query}") + } + ), response.clone(), config, ); @@ -174,15 +188,13 @@ fn logs_use_cluster_scope_without_a_database_or_with_a_stale_saved_database() { let (result, _, _) = run( &["logs", "--start-time", "2026-09-24T00:00:00Z", "--end-time", "2026-09-24T01:00:00Z", "--status-codes", "500"], "GET", - "/v1/logs?start_time=2026-09-24T00%3A00%3A00Z&end_time=2026-09-24T01%3A00%3A00Z&status_codes=500&limit=50&offset=0&organization=team%20alpha&cluster=prod%2Feu", + "/v1/logs?start_time=2026-09-24T00%3A00%3A00Z&end_time=2026-09-24T01%3A00%3A00Z&status_codes=500&limit=50&offset=0", response.clone(), config, ); assert_eq!(result, response); } } -const WORKFLOW_SCOPE: &str = "organization=team%20alpha&cluster=prod%2Feu"; - fn workflow_response() -> Value { json!({"id": "wf-1", "name": "alerts", "query": {"database": "analytics", "sql": "SELECT 1"}, "revision": 1, "schedule": {"cron": "* * * * *", "enabled": true, @@ -207,7 +219,7 @@ fn workflow_create_uses_saved_database_and_sends_sinks() { r#"{"type":"table","settings":{"database":"analytics","table":"out"}}"#, ], "POST", - &format!("/v1/workflows?{WORKFLOW_SCOPE}"), + "/v1/workflows", workflow_response(), json!({"database": "analytics"}), ); @@ -238,7 +250,7 @@ fn run_workflow_human(args: &[&str], method: &str, path: &str, response: Value) #[test] fn workflow_list_renders_empty_and_populated_responses() { - let path = format!("/v1/workflows?{WORKFLOW_SCOPE}"); + let path = "/v1/workflows".to_string(); let stdout = run_workflow_human( &["workflow", "list"], "GET", @@ -298,7 +310,7 @@ fn workflow_human_output_reads_query_and_optional_metadata() { let list = run_workflow_human( &["workflow", "list"], "GET", - &format!("/v1/workflows?{WORKFLOW_SCOPE}"), + "/v1/workflows", json!({"workflows": [response.clone()]}), ); let row = list.lines().find(|line| line.contains("alerts")).unwrap(); @@ -331,7 +343,7 @@ fn workflow_human_output_reads_query_and_optional_metadata() { let text = run_workflow_human( &args, method, - &format!("/v1/workflows{suffix}?{WORKFLOW_SCOPE}"), + &format!("/v1/workflows{suffix}"), response.clone(), ); assert!(text.contains("analytics"), "{text}"); @@ -370,7 +382,7 @@ fn workflow_query_updates_preserve_unspecified_fields() { let (_, _, body) = run( &args, "PATCH", - &format!("/v1/workflows/wf-1?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1", workflow_response(), json!({"database": "saved-db"}), ); @@ -395,7 +407,7 @@ fn workflow_scheduling_distinguishes_omitted_null_and_cron() { let (_, _, body) = run( &create, "POST", - &format!("/v1/workflows?{WORKFLOW_SCOPE}"), + "/v1/workflows", workflow_response(), json!({"database": "analytics"}), ); @@ -411,7 +423,7 @@ fn workflow_scheduling_distinguishes_omitted_null_and_cron() { let (_, _, body) = run( &update, "PATCH", - &format!("/v1/workflows/wf-1?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1", workflow_response(), json!({}), ); @@ -433,7 +445,7 @@ fn workflow_update_sends_only_changed_fields() { "--clear-sinks", ], "PATCH", - &format!("/v1/workflows/wf-1?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1", workflow_response(), json!({}), ); @@ -465,7 +477,7 @@ fn workflow_create_reads_sink_arrays_from_files() { &file_arg, ], "POST", - &format!("/v1/workflows?{WORKFLOW_SCOPE}"), + "/v1/workflows", workflow_response(), json!({}), ); @@ -476,7 +488,7 @@ fn workflow_create_reads_sink_arrays_from_files() { fn rejected_sinks_point_to_help() { let (output, _, _) = common::run_cli( &[( - format!("POST /v1/workflows?{WORKFLOW_SCOPE}"), + "POST /v1/workflows".to_string(), "422 Unprocessable Entity", json!({"message": "Invalid workflow.", "hint": "sinks[0].settings: unknown field `uri`, expected `url` or `headers`"}), @@ -518,7 +530,7 @@ fn workflow_sink_commands_change_one_sink() { r#"{"type":"table","settings":{"database":"analytics","table":"alerts"}}"#, ], "POST", - &format!("/v1/workflows/wf-1/sinks?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1/sinks", sink.clone(), json!({}), ); @@ -536,7 +548,7 @@ fn workflow_sink_commands_change_one_sink() { let (_, _, body) = run( &["workflow", "sink", "update", "wf-1", "sink 1", &file_arg], "PATCH", - &format!("/v1/workflows/wf-1/sinks/sink%201?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1/sinks/sink%201", sink, json!({}), ); @@ -545,7 +557,7 @@ fn workflow_sink_commands_change_one_sink() { let (result, _, _) = run( &["workflow", "sink", "delete", "wf-1", "sink-2"], "DELETE", - &format!("/v1/workflows/wf-1/sinks/sink-2?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1/sinks/sink-2", Value::Null, json!({}), ); @@ -567,7 +579,7 @@ fn workflow_sink_human_output_describes_the_sink() { r#"{"settings":{"table":"alerts_v2"}}"#, ], "PATCH", - &format!("/v1/workflows/wf-1/sinks/sink-2?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1/sinks/sink-2", json!({"type": "table", "id": "sink-2", "settings": {"database": "analytics", "table": "alerts_v2"}}), ); @@ -581,7 +593,7 @@ fn workflow_sink_human_output_describes_the_sink() { fn rejected_sink_changes_point_to_help() { let (output, _, _) = common::run_cli( &[( - format!("PATCH /v1/workflows/wf-1/sinks/sink-2?{WORKFLOW_SCOPE}"), + "PATCH /v1/workflows/wf-1/sinks/sink-2".to_string(), "400 Bad Request", json!({"message": "Invalid workflow sink.", "hint": "A sink's type cannot change. Delete the sink and add a new one."}), @@ -611,7 +623,7 @@ fn workflow_delete_and_cancel_accept_empty_responses() { let (result, _, _) = run( &["workflow", "delete", "wf-1"], "DELETE", - &format!("/v1/workflows/wf-1?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1", Value::Null, json!({}), ); @@ -620,7 +632,7 @@ fn workflow_delete_and_cancel_accept_empty_responses() { let (result, _, body) = run( &["workflow", "cancel", "wf-1", "run-1"], "POST", - &format!("/v1/workflows/wf-1/runs/run-1/cancel?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1/runs/run-1/cancel", Value::Null, json!({}), ); @@ -639,7 +651,7 @@ fn workflow_runs_and_logs_pass_pagination_and_time_window() { "workflow", "runs", "wf-1", "--limit", "5", "--cursor", "a+b", ], "GET", - &format!("/v1/workflows/wf-1/runs?{WORKFLOW_SCOPE}&limit=5&cursor=a%2Bb"), + "/v1/workflows/wf-1/runs?limit=5&cursor=a%2Bb", response.clone(), json!({}), ); @@ -658,7 +670,7 @@ fn workflow_runs_and_logs_pass_pagination_and_time_window() { "2026-10-01T01:00:00Z", ], "GET", - &format!("/v1/workflows/wf-1/logs?{WORKFLOW_SCOPE}&from=1790812800000&to=1790816400000"), + "/v1/workflows/wf-1/logs?from=1790812800000&to=1790816400000", response.clone(), json!({}), ); @@ -676,6 +688,35 @@ fn workflow_commands_require_a_cluster() { assert!(String::from_utf8_lossy(&output.stderr).contains("No cluster specified")); } +#[test] +fn workflow_commands_require_a_cluster_for_user_credentials() { + let (output, _, _) = common::run_cli( + &[], + &["--json", "--org", "team", "workflow", "list"], + &json!({"token": "session.fixture"}), + ); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("No cluster specified")); +} + +#[test] +fn workflow_commands_let_api_keys_omit_organization_and_cluster() { + let (output, _, _) = common::run_cli( + &[( + "GET /v1/workflows".to_string(), + "200 OK", + json!({"workflows": []}), + )], + &["--json", "workflow", "list"], + &json!({"token": "rt_fixture"}), + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + #[test] fn workflow_obsolete_intervals_are_rejected_before_sending_requests() { for args in [ @@ -726,7 +767,7 @@ fn workflow_schedule_pause_and_resume_fields_are_nested() { "false", ], "POST", - &format!("/v1/workflows?{WORKFLOW_SCOPE}"), + "/v1/workflows", workflow_response(), json!({"database":"analytics"}), ); @@ -756,7 +797,7 @@ fn workflow_schedule_pause_and_resume_fields_are_nested() { let (_, _, body) = run( &args, "PATCH", - &format!("/v1/workflows/wf-1?{WORKFLOW_SCOPE}"), + "/v1/workflows/wf-1", workflow_response(), json!({}), ); @@ -825,7 +866,7 @@ fn workflow_manual_schedule_rejects_pause_flags_before_http() { fn workflow_cron_validation_errors_are_returned_by_the_api() { let (output, _, bodies) = common::run_cli( &[( - "POST /v1/workflows?organization=team&cluster=prod".into(), + "POST /v1/workflows".into(), "400 Bad Request", json!({"message":"Invalid workflow cron", "hint":"Cron must have 5 or 6 fields."}), )], @@ -913,3 +954,125 @@ fn integration_list_preserves_json_and_renders_workspaces() { ); assert!(empty.contains("rtree integration add slack"), "{empty}"); } + +fn config_with_saved_ids() -> Value { + json!({ + "token": "rt_fixture", + "default_organization": "team", "default_organization_id": common::ORG_ID, + "cluster": "prod", "cluster_id": common::CLUSTER_ID, + }) +} + +#[test] +fn saved_ids_need_no_lookup_requests() { + let (output, saved, _) = common::run_cli( + &[( + "GET /v1/databases".to_string(), + "200 OK", + json!({"databases": []}), + )], + &["--json", "database", "list"], + &config_with_saved_ids(), + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(saved, config_with_saved_ids()); +} + +#[test] +fn an_org_flag_ignores_the_saved_id_and_resolves_by_name() { + let (output, _, _) = common::run_cli( + &[ + common::key_organization("other"), + ( + "GET /v1/databases".to_string(), + "200 OK", + json!({"databases": []}), + ), + ], + &["--json", "--org", "other", "database", "list"], + &config_with_saved_ids(), + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn a_rejected_saved_id_fails_with_a_refresh_hint_and_never_falls_back_to_names() { + let (output, saved, _) = common::run_cli( + &[( + "GET /v1/databases".to_string(), + "404 Not Found", + json!({"message": "Cluster not found."}), + )], + &["--json", "database", "list"], + &config_with_saved_ids(), + ); + assert_eq!(output.status.code(), Some(4)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("saved organization or cluster ID was rejected")); + assert!(stderr.contains("rtree organization use")); + assert_eq!(saved, config_with_saved_ids()); +} + +#[test] +fn configs_with_only_names_keep_resolving_by_name() { + let mut config = config_with_saved_ids(); + let fields = config.as_object_mut().unwrap(); + fields.remove("default_organization_id"); + fields.remove("cluster_id"); + let (output, _, _) = common::run_cli( + &[ + common::key_organization("team"), + common::bound_cluster("prod"), + ( + "GET /v1/databases".to_string(), + "200 OK", + json!({"databases": []}), + ), + ], + &["--json", "database", "list"], + &config, + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn organization_use_saves_the_id_and_drops_the_previous_clusters_id() { + let (output, saved, _) = common::run_cli( + &[common::key_organization("team")], + &["--json", "organization", "use", "team"], + &json!({"token": "rt_fixture", "default_organization": "old", "default_organization_id": "old-id", "cluster": "prod", "cluster_id": common::CLUSTER_ID}), + ); + assert!(output.status.success()); + assert_eq!(saved["default_organization"], "team"); + assert_eq!(saved["default_organization_id"], common::ORG_ID); + assert_eq!(saved["cluster"], "prod"); + assert!(saved.get("cluster_id").is_none()); +} + +#[test] +fn organization_use_without_a_resolvable_id_saves_only_the_name() { + let (output, saved, _) = common::run_cli( + &[( + "GET /v1/organizations".to_string(), + "503 Service Unavailable", + json!({"message": "down"}), + )], + &["--json", "organization", "use", "team"], + &json!({"token": "rt_fixture", "default_organization": "old", "default_organization_id": "old-id"}), + ); + assert!(output.status.success()); + assert_eq!(saved["default_organization"], "team"); + assert!(saved.get("default_organization_id").is_none()); +} diff --git a/tests/api_key_expiration.rs b/tests/api_key_expiration.rs index 9794672..1ce0196 100644 --- a/tests/api_key_expiration.rs +++ b/tests/api_key_expiration.rs @@ -15,11 +15,7 @@ fn create_sends_expiration_and_preserves_normalized_response() { let input = "2027-01-01T02:00:00+02:00"; let expected = key(Some(json!("2027-01-01T00:00:00Z"))); let (output, _, bodies) = common::run_cli( - &[( - "POST /v1/api-keys?organization=team&cluster=prod".into(), - "200 OK", - expected.clone(), - )], + &[("POST /v1/api-keys".into(), "200 OK", expected.clone())], &[ "--json", "api-key", @@ -79,11 +75,7 @@ fn create_and_list_display_expiration_or_never_in_text_and_json() { args.insert(0, "--json"); } let (output, _, bodies) = common::run_cli( - &[( - format!("{method} /v1/api-keys?organization=team&cluster=prod"), - "200 OK", - response, - )], + &[(format!("{method} /v1/api-keys"), "200 OK", response)], &args, &json!({"default_organization": "team", "cluster": "prod"}), ); @@ -125,7 +117,7 @@ fn create_and_list_display_expiration_or_never_in_text_and_json() { fn create_surfaces_backend_expiration_validation_errors() { let (output, _, bodies) = common::run_cli( &[( - "POST /v1/api-keys?organization=team&cluster=prod".into(), + "POST /v1/api-keys".into(), "400 Bad Request", json!({"error":"bad_request", "message":"Invalid expiration date.", "hint":"expires_at must be in the future."}), )], @@ -155,11 +147,7 @@ fn list_preserves_database_role_keys_and_expiration() { }]}); for args in [vec!["--json", "api-key", "list"], vec!["api-key", "list"]] { let (output, _, _) = common::run_cli( - &[( - "GET /v1/api-keys?organization=team&cluster=prod".into(), - "200 OK", - response.clone(), - )], + &[("GET /v1/api-keys".into(), "200 OK", response.clone())], &args, &json!({"default_organization": "team", "cluster": "prod"}), ); diff --git a/tests/api_key_login.rs b/tests/api_key_login.rs index 0fbf920..9fba1e4 100644 --- a/tests/api_key_login.rs +++ b/tests/api_key_login.rs @@ -3,14 +3,25 @@ mod common; use serde_json::{json, Value}; use std::process::Output; -fn login(responses: &[(&str, &str, Value)], selectors: &[&str]) -> (Output, Value, Value) { +fn login( + key_scope: (Option<&str>, Option<&str>), + responses: &[(&str, &str, Value)], + selectors: &[&str], +) -> (Output, Value, Value) { let original = json!({ "token": "old-test-credential", "email": "old@example.test", "default_organization": "old-org", "cluster": "old-cluster", "database": "old-db" }); - let responses = responses - .iter() - .map(|(path, status, body)| (format!("GET {path}"), *status, body.clone())) + let responses = key_scope + .0 + .map(common::key_organization) + .into_iter() + .chain(key_scope.1.map(common::bound_cluster)) + .chain( + responses + .iter() + .map(|(path, status, body)| (format!("GET {path}"), *status, body.clone())), + ) .collect::>(); let mut args = vec!["--api-key", "rt_login_fixture", "--json", "login"]; args.extend_from_slice(selectors); @@ -22,11 +33,7 @@ fn login(responses: &[(&str, &str, Value)], selectors: &[&str]) -> (Output, Valu fn api_key_login_accepts_current_responses_and_replaces_stale_defaults() { for fallback in [false, true] { for explicit in [false, true] { - let query = if explicit { - "?database=analytics&organization=team%20alpha&cluster=prod%2Feu" - } else { - "" - }; + let query = if explicit { "?database=analytics" } else { "" }; let keys = format!("/v1/api-keys{query}"); let tables = format!("/v1/tables{query}"); let responses = if fallback { @@ -53,7 +60,14 @@ fn api_key_login_accepts_current_responses_and_replaces_stale_defaults() { } else { vec![] }; - let (output, saved, _) = login(&responses, &selectors); + let (output, saved, _) = login( + ( + explicit.then_some("team alpha"), + explicit.then_some("prod/eu"), + ), + &responses, + &selectors, + ); assert!( output.status.success(), "{}", @@ -91,9 +105,10 @@ fn api_key_login_failures_preserve_saved_credentials() { ("200 OK", json!({})), ] { let (output, saved, original) = login( + (None, Some("other")), &[ - ("/v1/api-keys?cluster=other", status, body.clone()), - ("/v1/tables?cluster=other", status, body), + ("/v1/api-keys", status, body.clone()), + ("/v1/tables", status, body), ], &["--cluster", "other"], ); @@ -106,6 +121,7 @@ fn api_key_login_failures_preserve_saved_credentials() { #[test] fn api_key_login_preserves_legacy_response_metadata() { let (output, saved, _) = login( + (None, None), &[( "/v1/api-keys", "200 OK", diff --git a/tests/browser_login.rs b/tests/browser_login.rs index 577a6a4..7e52b04 100644 --- a/tests/browser_login.rs +++ b/tests/browser_login.rs @@ -59,7 +59,7 @@ fn regions() -> Response { fn clusters(names: &[&str]) -> Response { ( - "GET /v1/clusters?organization=team".into(), + "GET /v1/clusters".into(), "200 OK", json!({"clusters": names.iter().map(|name| json!({"id": name, "name": name})).collect::>()}), ) @@ -67,7 +67,7 @@ fn clusters(names: &[&str]) -> Response { fn databases(names: &[&str]) -> Response { ( - "GET /v1/databases?organization=team&cluster=production".into(), + "GET /v1/databases".into(), "200 OK", json!({"databases": names.iter().map(|name| json!({"id": name, "name": name})).collect::>()}), ) @@ -132,7 +132,6 @@ fn missing_cluster_returns_choices_in_the_selected_organization() { let mut responses = approved_login(); responses.extend([ organizations(&["team", "other"]), - organizations(&["team"]), regions(), clusters(&names), ]); @@ -149,7 +148,6 @@ fn missing_database_returns_choices_in_the_selected_cluster() { for names in [vec![], vec!["analytics", "billing"]] { let mut responses = approved_login(); responses.extend([ - organizations(&["team"]), organizations(&["team"]), regions(), clusters(&["staging", "production"]), @@ -182,7 +180,6 @@ fn approval_is_reported_before_polling_completes_and_only_once() { ), ); responses.extend([ - organizations(&["team"]), organizations(&["team"]), regions(), clusters(&["production"]), @@ -227,7 +224,6 @@ fn explicit_json_and_selectors_complete_login_with_no_browser() { let mut responses = approved_login(); responses.extend([ organizations(&["other", "team"]), - organizations(&["team"]), regions(), clusters(&["staging", "production"]), databases(&["billing", "analytics"]), @@ -266,11 +262,7 @@ fn invalid_selectors_return_json_errors_and_preserve_config() { let mut responses = approved_login(); responses.push(organizations(&["team"])); if flag != "--org" { - responses.extend([ - organizations(&["team"]), - regions(), - clusters(&["production"]), - ]); + responses.extend([regions(), clusters(&["production"])]); } if flag == "--database" { responses.push(databases(&["analytics"])); @@ -293,10 +285,9 @@ fn invalid_selectors_return_json_errors_and_preserve_config() { #[test] fn discovery_errors_are_not_treated_as_empty_choices_or_success() { - for stage in 0..5 { + for stage in 0..4 { let mut responses = approved_login(); let discovery = [ - organizations(&["team"]), organizations(&["team"]), regions(), clusters(&["production"]), diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 9becd7b..ac88ed3 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -4,6 +4,32 @@ use std::net::TcpListener; use std::process::{Command, Output, Stdio}; use std::time::{Duration, Instant}; +#[allow(dead_code)] // Used by the integration test binaries that select clusters by name. +pub const CLUSTER_ID: &str = "00000000-0000-4000-8000-0000000000c1"; + +#[allow(dead_code)] +pub const ORG_ID: &str = "00000000-0000-4000-8000-000000000001"; + +/// The response an API key gets when the CLI resolves an organization name against its own organization. +#[allow(dead_code)] +pub fn key_organization(name: &str) -> (String, &'static str, Value) { + ( + "GET /v1/organizations".to_string(), + "200 OK", + serde_json::json!({"organizations": [{"organization_id": ORG_ID, "name": name, "role": null, "plan_id": "trial"}]}), + ) +} + +/// The response an API key gets when the CLI resolves a cluster name against its bound cluster. +#[allow(dead_code)] +pub fn bound_cluster(name: &str) -> (String, &'static str, Value) { + ( + "GET /v1/clusters".to_string(), + "200 OK", + serde_json::json!({"clusters": [{"id": CLUSTER_ID, "name": name}]}), + ) +} + #[derive(Clone, Copy)] pub struct ProgressExpectation { pub before_response: &'static str, diff --git a/tests/federation.rs b/tests/federation.rs index f365ceb..eea1f2b 100644 --- a/tests/federation.rs +++ b/tests/federation.rs @@ -133,7 +133,19 @@ fn rules_use_full_put_and_exact_scope_for_both_access_modes() { json!({"id":"rule","principal_type":"service_account","principal_id":ORG}) }; let config = json!({"token":"rt_fixture","default_organization":"wrong","cluster":"wrong","database":"ignored"}); - let (out,saved,bodies)=common::run_cli(&[(format!("{method} /v1/federation-rules{suffix}?organization=team%20alpha&cluster=prod%2Feu"),"200 OK",response.clone())],&args,&config); + let (out, saved, bodies) = common::run_cli( + &[ + common::key_organization("team alpha"), + common::bound_cluster("prod/eu"), + ( + format!("{method} /v1/federation-rules{suffix}"), + "200 OK", + response.clone(), + ), + ], + &args, + &config, + ); assert!( out.status.success(), "{}", @@ -145,7 +157,7 @@ fn rules_use_full_put_and_exact_scope_for_both_access_modes() { response ); if matches!(action, "create" | "update") { - let body = &bodies[0]; + let body = bodies.last().unwrap(); assert_eq!(body["database"], "warehouse"); assert_eq!(body["enabled"], false); assert_eq!(body["claim_conditions"]["label"], "a=b"); @@ -246,11 +258,15 @@ fn unknown_org_and_api_errors_are_not_retried_or_retargeted() { "409 Conflict", ] { let (out, _, bodies) = common::run_cli( - &[( - "DELETE /v1/federation-rules/id?organization=team&cluster=prod".into(), - status, - json!({"message":"Denied"}), - )], + &[ + common::key_organization("team"), + common::bound_cluster("prod"), + ( + "DELETE /v1/federation-rules/id".into(), + status, + json!({"message":"Denied"}), + ), + ], &[ "--org", "team", @@ -264,6 +280,6 @@ fn unknown_org_and_api_errors_are_not_retried_or_retargeted() { ); assert!(!out.status.success()); assert!(String::from_utf8_lossy(&out.stderr).contains("Denied")); - assert_eq!(bodies.len(), 1); + assert_eq!(bodies.len(), 3); } } diff --git a/tests/format.rs b/tests/format.rs index 1ca77ee..6a4bc80 100644 --- a/tests/format.rs +++ b/tests/format.rs @@ -2,10 +2,10 @@ mod common; use serde_json::{json, Value}; -const PATH: &str = "POST /v1/query-format?organization=team&cluster=prod"; +const PATH: &str = "POST /v1/query-format"; fn config() -> Value { - json!({"token": "rt_fixture", "default_organization": "team", "cluster": "prod"}) + json!({"token": "rt_fixture", "default_organization": common::ORG_ID, "cluster": common::CLUSTER_ID}) } #[test] @@ -28,11 +28,22 @@ fn json_output_and_scope_overrides_preserve_the_document() { let formatted = "SELECT 1;\n\n"; let (output, _, bodies) = common::run_cli( &[( - "POST /v1/query-format?database=analytics%20db&organization=team%20alpha&cluster=prod%2Feu".to_string(), + "POST /v1/query-format?database=analytics%20db".to_string(), "200 OK", json!({"formatted": formatted}), )], - &["format", "--sql", "select 1", "--database", "analytics db", "--org", "team alpha", "--cluster", "prod/eu", "--json"], + &[ + "format", + "--sql", + "select 1", + "--database", + "analytics db", + "--org", + common::ORG_ID, + "--cluster", + common::CLUSTER_ID, + "--json", + ], &config(), ); assert!(output.status.success(), "{:?}", output); @@ -72,7 +83,7 @@ fn uses_saved_database_scope() { configuration["database"] = json!("saved db"); let (output, _, _) = common::run_cli( &[( - "POST /v1/query-format?database=saved%20db&organization=team&cluster=prod".to_string(), + "POST /v1/query-format?database=saved%20db".to_string(), "200 OK", json!({"formatted": "SELECT 1"}), )], diff --git a/tests/oauth_login.rs b/tests/oauth_login.rs index 123c972..21a9f00 100644 --- a/tests/oauth_login.rs +++ b/tests/oauth_login.rs @@ -40,23 +40,18 @@ fn login_responses() -> Vec { "200 OK", json!({"organizations":[{"name":"team","organization_id":"team-id","role":"owner"}]}), ), - ( - "GET /v1/organizations".into(), - "200 OK", - json!({"organizations":[{"name":"team","organization_id":"team-id","role":"owner"}]}), - ), ( "GET /v1/regions?organization_id=team-id".into(), "200 OK", json!({"regions":[{"id":"legacy","name":"Virginia","cloud_region":"us-east-1","deployment_id":null,"enabled":true}]}), ), ( - "GET /v1/clusters?organization=team".into(), + "GET /v1/clusters".into(), "200 OK", json!({"clusters":[{"id":"production","name":"production"}]}), ), ( - "GET /v1/databases?organization=team&cluster=production".into(), + "GET /v1/databases".into(), "200 OK", json!({"databases":[{"name":"analytics"}]}), ), @@ -569,11 +564,18 @@ fn oauth_timeout_zero_and_large_values_are_capped_at_ten_minutes() { #[test] fn deleting_other_or_absent_organizations_preserves_defaults() { for (deleted, selected) in [(false, "old"), (false, "other"), (true, "other")] { - let responses = [( - "DELETE /v1/organizations/old".into(), - "200 OK", - json!({"deleted":deleted}), - )]; + let responses = [ + ( + "GET /v1/organizations".into(), + "200 OK", + json!({"organizations":[{"name":"old","organization_id":"old-id","role":"owner"}]}), + ), + ( + "DELETE /v1/organizations/old-id".into(), + "200 OK", + json!({"deleted":deleted}), + ), + ]; let (output, saved, _) = common::run_cli( &responses, &["organization", "delete", "old", "--json"], diff --git a/tests/oauth_refresh.rs b/tests/oauth_refresh.rs index b17d082..3fcd40c 100644 --- a/tests/oauth_refresh.rs +++ b/tests/oauth_refresh.rs @@ -284,7 +284,13 @@ fn deleting_an_organization_does_not_overwrite_concurrently_selected_defaults() let server_path = path.clone(); let server = std::thread::spawn(move || { let (socket, first, _) = request(&listener); - assert!(first.starts_with("DELETE /v1/organizations/old ")); + assert!(first.starts_with("GET /v1/organizations ")); + reply( + socket, + json!({"organizations":[{"name":"old","organization_id":"old-id","role":"owner"}]}), + ); + let (socket, first, _) = request(&listener); + assert!(first.starts_with("DELETE /v1/organizations/old-id ")); reply(socket, json!({"deleted":true})); let (socket, first, _) = request(&listener); assert!(first.starts_with("GET /v1/organizations ")); @@ -298,7 +304,7 @@ fn deleting_an_organization_does_not_overwrite_concurrently_selected_defaults() } let organizations: Vec<_> = next .into_iter() - .map(|name| json!({"name":name,"role":"owner"})) + .map(|name| json!({"name":name,"organization_id":format!("{name}-id"),"role":"owner"})) .collect(); reply(socket, json!({"organizations":organizations})); }); @@ -331,7 +337,7 @@ fn api_key_validation_does_not_hold_the_config_lock() { .unwrap(); let (socket, first, _) = request(&listener); assert!(first.starts_with("GET /v1/api-keys ")); - let mut selection = command(home.path(), &url, &["organization", "use", "other"]) + let mut selection = command(home.path(), &url, &["database", "use", "other"]) .spawn() .unwrap(); let deadline = Instant::now() + Duration::from_secs(2); diff --git a/tests/region_creation.rs b/tests/region_creation.rs index 7969ba7..9b0e616 100644 --- a/tests/region_creation.rs +++ b/tests/region_creation.rs @@ -21,7 +21,7 @@ fn create_flag_routes_size_discovery_and_preserves_region_in_body() { let mut responses = discovery(); responses.extend([ ("GET /v1/clusters/sizes".into(), "200 OK", json!({"sizes":[{"cpu_cores":2,"memory_gib":8}]})), - ("POST /v1/clusters?organization=acme".into(), "200 OK", json!({"id":"new","name":"production","created_at":"2026-10-18T00:00:00Z","status":{"phase":"provisioning","ready":false,"message":null},"resources":null,"can_pause":false,"can_resume":false,"idle_timeout_minutes":30})), + ("POST /v1/clusters".into(), "200 OK", json!({"id":"new","name":"production","created_at":"2026-10-18T00:00:00Z","status":{"phase":"provisioning","ready":false,"message":null},"resources":null,"can_pause":false,"can_resume":false,"idle_timeout_minutes":30})), ]); let (output, _, bodies) = common::run_cli( &responses, diff --git a/tests/regional_discovery.rs b/tests/regional_discovery.rs index 8b2ff8f..e70c146 100644 --- a/tests/regional_discovery.rs +++ b/tests/regional_discovery.rs @@ -65,7 +65,7 @@ fn run(args: &[&str], failure: Failure, all_fail: bool) -> (Output, Vec, {"id":"duplicate","name":"Oregon duplicate","cloud_region":"us-west-2","deployment_id":"22222222","enabled":true}, {"id":"failed2","name":"Ireland","cloud_region":"eu-west-1","deployment_id":"33333333","enabled":true} ]})); - } else if first.starts_with("GET /v1/clusters?") { + } else if first.starts_with("GET /v1/clusters ") { if !all_fail && headers["x-rawtree-deployment-id"] == "11111111" { reply(&mut socket, 200, json!({"clusters":[{ "id":"healthy-id", "name":"production", "region_id":"healthy", "created_at":"2026-10-28T00:00:00Z", "shared":false, @@ -135,7 +135,7 @@ fn table_list_survives_http_and_connection_failures_in_other_regions() { assert_eq!( requests .iter() - .filter(|path| path.starts_with("GET /v1/clusters?")) + .filter(|path| path.starts_with("GET /v1/clusters ")) .count(), 3 ); diff --git a/tests/sql_input.rs b/tests/sql_input.rs index 7a660d7..4f06477 100644 --- a/tests/sql_input.rs +++ b/tests/sql_input.rs @@ -3,7 +3,7 @@ mod common; use serde_json::{json, Value}; fn config() -> Value { - json!({"token": "rt_fixture", "database": "analytics", "default_organization": "team", "cluster": "prod"}) + json!({"token": "rt_fixture", "database": "analytics", "default_organization": common::ORG_ID, "cluster": common::CLUSTER_ID}) } fn response(command: &str) -> (String, &'static str, Value) { @@ -13,7 +13,7 @@ fn response(command: &str) -> (String, &'static str, Value) { _ => unreachable!(), }; ( - format!("POST /v1/{endpoint}?database=analytics&organization=team&cluster=prod"), + format!("POST /v1/{endpoint}?database=analytics"), "200 OK", body, ) diff --git a/tests/storage_contracts.rs b/tests/storage_contracts.rs index a90a6aa..957ce4f 100644 --- a/tests/storage_contracts.rs +++ b/tests/storage_contracts.rs @@ -72,12 +72,12 @@ fn database_storage_create_uses_current_response_and_persists_only_on_success() json!({"regions":[{"id":"legacy","name":"Virginia","cloud_region":"us-east-1","deployment_id":null,"organization_id":null,"enabled":true}]}), ), ( - "GET /v1/clusters?organization=team%20alpha".into(), + "GET /v1/clusters".into(), "200 OK", - json!({"clusters": []}), + json!({"clusters": [{"id": common::CLUSTER_ID, "name": "prod/eu"}]}), ), ( - "POST /v1/databases?organization=team%20alpha&cluster=prod%2Feu".into(), + "POST /v1/databases".into(), if success { "200 OK" } else { "400 Bad Request" }, response.clone(), ), @@ -173,11 +173,7 @@ fn cluster_creation_forwards_optional_identity_and_nested_storage() { "200 OK", json!({"sizes": [{"cpu_cores": 2, "memory_gib": 8}]}), ), - ( - "POST /v1/clusters?organization=team".into(), - "200 OK", - response.clone(), - ), + ("POST /v1/clusters".into(), "200 OK", response.clone()), ], &args, &json!({"token":"session.fixture"}), @@ -241,7 +237,7 @@ fn cluster_list_and_status_show_storage_without_an_organization_envelope() { args.extend_from_slice(&action); let (output, _, _) = common::run_cli( &[( - "GET /v1/clusters?organization=team".into(), + "GET /v1/clusters".into(), "200 OK", json!({"clusters": [cluster()]}), )], @@ -341,7 +337,7 @@ fn managed_cluster_storage_and_inherited_database_storage_have_distinct_labels() args.extend_from_slice(&action); let (output, _, _) = common::run_cli( &[( - "GET /v1/clusters?organization=team".into(), + "GET /v1/clusters".into(), "200 OK", json!({"clusters": [managed]}), )], @@ -359,7 +355,7 @@ fn managed_cluster_storage_and_inherited_database_storage_have_distinct_labels() } let (output, _, _) = common::run_cli( &[( - "GET /v1/databases?organization=team&cluster=production".into(), + "GET /v1/databases".into(), "200 OK", json!({"databases": [{"name": "analytics", "s3_storage": null}]}), )], @@ -399,7 +395,7 @@ fn cluster_identity_validation_errors_come_from_the_api() { json!({"sizes": [{"cpu_cores": 2, "memory_gib": 8}]}), ), ( - "POST /v1/clusters?organization=team".into(), + "POST /v1/clusters".into(), "400 Bad Request", json!({"message": "Custom S3 storage requires s3_storage_access.external_id."}), ), From e25437ceb79bab0d6b6dd047a486424f5064beeb Mon Sep 17 00:00:00 2001 From: jordiori Date: Wed, 25 Nov 2026 17:46:55 +0100 Subject: [PATCH 2/7] Resolve the cluster by name when the organization is overridden --- src/main.rs | 9 ++++++--- tests/api_contracts.rs | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index f3c6e70..a6d58c5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,9 +135,12 @@ fn saved_ids_from_sources( organization: (cli_org.is_none() && env_org.is_none()) .then(|| pair(&cfg.default_organization, &cfg.default_organization_id)) .flatten(), - cluster: (cli_cluster.is_none() && env_cluster.is_none()) - .then(|| pair(&cfg.default_cluster, &cfg.default_cluster_id)) - .flatten(), + cluster: (cli_org.is_none() + && env_org.is_none() + && cli_cluster.is_none() + && env_cluster.is_none()) + .then(|| pair(&cfg.default_cluster, &cfg.default_cluster_id)) + .flatten(), } } diff --git a/tests/api_contracts.rs b/tests/api_contracts.rs index 4775199..450bf3c 100644 --- a/tests/api_contracts.rs +++ b/tests/api_contracts.rs @@ -983,10 +983,11 @@ fn saved_ids_need_no_lookup_requests() { } #[test] -fn an_org_flag_ignores_the_saved_id_and_resolves_by_name() { +fn an_org_flag_ignores_both_saved_ids_and_resolves_by_name() { let (output, _, _) = common::run_cli( &[ common::key_organization("other"), + common::bound_cluster("prod"), ( "GET /v1/databases".to_string(), "200 OK", From b14322bb7e26247844effb719402ddf2f843587e Mon Sep 17 00:00:00 2001 From: jordiori Date: Thu, 26 Nov 2026 09:27:02 +0100 Subject: [PATCH 3/7] Honor saved IDs in cluster listing, accept org IDs in org paths, and scope feedback by UUIDs --- src/client.rs | 10 +++++++++- src/client/routing.rs | 3 +++ src/commands/feedback.rs | 25 ++++++++++++++++--------- src/org.rs | 2 +- tests/api_contracts.rs | 21 +++++++++++++++++++++ 5 files changed, 50 insertions(+), 11 deletions(-) diff --git a/src/client.rs b/src/client.rs index 6014951..6f7d7c7 100644 --- a/src/client.rs +++ b/src/client.rs @@ -288,7 +288,15 @@ impl ApiClient { pub fn get(&self, path: &str) -> Result { let value: Value = if path == "/v1/clusters" && self.has_user_credential()? && self.deployment.is_none() { - self.discover_clusters(self.scope.organization.as_deref(), None)? + let saved = self + .scope + .organization + .as_deref() + .and_then(|name| self.saved_organization_id(name)); + self.discover_clusters( + saved.as_deref().or(self.scope.organization.as_deref()), + None, + )? } else { let req = self.routed_request(reqwest::Method::GET, path)?; handle_response(req.send().context("failed to connect to server")?)? diff --git a/src/client/routing.rs b/src/client/routing.rs index d05f218..d050ac0 100644 --- a/src/client/routing.rs +++ b/src/client/routing.rs @@ -155,6 +155,9 @@ impl ApiClient { /// Resolves an organization name or ID to its ID. pub fn organization_id(&self, name_or_id: &str) -> Result { + if let Some(id) = self.saved_organization_id(name_or_id) { + return Ok(id); + } self.find_organization(&organization_selector(name_or_id), None) .map(|organization| organization.organization_id) } diff --git a/src/commands/feedback.rs b/src/commands/feedback.rs index b852ecb..d25db88 100644 --- a/src/commands/feedback.rs +++ b/src/commands/feedback.rs @@ -3,7 +3,10 @@ use clap::{Args, ValueEnum}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; -use crate::{client::ApiClient, output}; +use crate::{ + client::{ApiClient, Scope}, + output, +}; #[derive(Clone, Debug, Serialize, ValueEnum)] #[serde(rename_all = "snake_case")] @@ -73,14 +76,18 @@ pub fn submit(client: &ApiClient, args: FeedbackArgs, json_mode: bool) -> Result serde_json::to_vec(&body)?.len() <= 32 * 1024, "feedback body exceeds 32 KiB" ); - // Reuse regional routing when user credentials provide both scope UUIDs. - let path = match (&args.organization_id, &args.cluster_id) { - (Some(org), Some(cluster)) => format!( - "/v1/feedback?organization_id={}&cluster_id={}", - urlencoding::encode(org), - urlencoding::encode(cluster) - ), - _ => "/v1/feedback".into(), + let scoped; + let (client, path) = match (&args.organization_id, &args.cluster_id) { + (Some(org), Some(cluster)) => { + scoped = client.with_scope(Scope::new(Some(org), Some(cluster))); + let path = format!( + "/v1/feedback?organization_id={}&cluster_id={}", + urlencoding::encode(org), + urlencoding::encode(cluster) + ); + (&scoped, path) + } + _ => (client, "/v1/feedback".to_owned()), }; let receipt: Receipt = client .post(&path, &body) diff --git a/src/org.rs b/src/org.rs index 456cbcd..a3536e4 100644 --- a/src/org.rs +++ b/src/org.rs @@ -98,7 +98,7 @@ pub fn organization_path(client: &ApiClient, organization: Option<&str>) -> Resu Some(name) => response .organizations .into_iter() - .find(|item| item.name == name) + .find(|item| item.name == name || item.organization_id == name) .with_context(|| { format!("Organization '{name}' was not found. Run `rtree organization list`.") })?, diff --git a/tests/api_contracts.rs b/tests/api_contracts.rs index 450bf3c..dbff1da 100644 --- a/tests/api_contracts.rs +++ b/tests/api_contracts.rs @@ -1077,3 +1077,24 @@ fn organization_use_without_a_resolvable_id_saves_only_the_name() { assert_eq!(saved["default_organization"], "team"); assert!(saved.get("default_organization_id").is_none()); } + +#[test] +fn cluster_list_uses_the_saved_organization_id_without_a_name_lookup() { + let (output, _, _) = common::run_cli( + &[( + format!("GET /v1/regions?organization_id={}", common::ORG_ID), + "200 OK", + json!({"regions": []}), + )], + &["--json", "cluster", "list"], + &json!({ + "token": "user_fixture", + "default_organization": "team", "default_organization_id": common::ORG_ID, + }), + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} From 109ea8ca9f9f5d261864621aac947d3e496778bc Mon Sep 17 00:00:00 2001 From: jordiori Date: Thu, 26 Nov 2026 11:00:17 +0100 Subject: [PATCH 4/7] Cache discovered clusters under the saved organization ID --- src/client/routing.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/client/routing.rs b/src/client/routing.rs index d050ac0..62f6984 100644 --- a/src/client/routing.rs +++ b/src/client/routing.rs @@ -124,6 +124,13 @@ impl ApiClient { let selected = self.scope.organization.as_deref().and_then(|organization| { if is_uuid(organization) { Some(organization.to_owned()) + } else if let Some((_, id)) = self + .saved + .organization + .as_ref() + .filter(|(name, _)| name == organization) + { + Some(id.clone()) } else { self.cached_organization(organization) .map(|item| item.organization_id) From 5a9b3488be761971788f534ee7c0e3f058bec0fa Mon Sep 17 00:00:00 2001 From: jordiori Date: Thu, 26 Nov 2026 11:28:16 +0100 Subject: [PATCH 5/7] Build the request scope once from typed selectors Replace the saved-ID side table with a Selector type: main resolves the organization and cluster from flags, environment and config, substituting saved IDs for config selections, and hands commands a scoped client. The client no longer knows where an ID came from. --- src/client.rs | 77 ++-- src/client/discovery.rs | 25 +- src/client/regions.rs | 17 +- src/client/routing.rs | 167 ++----- src/client/routing_tests.rs | 108 ++--- src/commands/cluster.rs | 75 +--- src/commands/database.rs | 20 +- src/commands/federation_issuer.rs | 7 +- src/commands/federation_rule.rs | 23 +- src/commands/format.rs | 8 +- src/commands/insert.rs | 6 +- src/commands/integration.rs | 6 +- src/commands/keys.rs | 22 +- src/commands/logs.rs | 12 +- src/commands/organization.rs | 13 +- src/commands/query.rs | 6 +- src/commands/service_account.rs | 11 +- src/commands/table.rs | 36 +- src/main.rs | 700 +++++++++++++----------------- src/org.rs | 61 ++- 20 files changed, 513 insertions(+), 887 deletions(-) diff --git a/src/client.rs b/src/client.rs index 6f7d7c7..496c358 100644 --- a/src/client.rs +++ b/src/client.rs @@ -2,7 +2,6 @@ mod discovery; pub(crate) use discovery::UnavailableRegion; mod regions; mod routing; -pub(crate) use routing::is_uuid; #[cfg(test)] mod routing_tests; @@ -15,7 +14,6 @@ use serde::de::DeserializeOwned; use serde_json::Value; use std::cell::RefCell; use std::io::Write; -use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Duration; @@ -39,19 +37,37 @@ struct SavedCredential { oauth_client_id: Option, } -/// The organization and cluster a request acts on, as the user typed them: -/// names or IDs. The client resolves them to the ID headers the API expects. +/// 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, - pub cluster: Option, + pub organization: Option, + pub cluster: Option, } impl Scope { pub fn new(organization: Option<&str>, cluster: Option<&str>) -> Self { Self { - organization: organization.map(str::to_owned), - cluster: cluster.map(str::to_owned), + organization: organization.map(Selector::parse), + cluster: cluster.map(Selector::parse), } } @@ -60,16 +76,6 @@ impl Scope { } } -/// IDs saved in the config for the default organization and cluster, each with -/// the name it was saved under. A scope that names the same organization or -/// cluster uses the saved ID instead of looking it up. Only set them for -/// selections that came from the config, never for flags or environment. -#[derive(Clone, Debug, Default)] -pub struct SavedIds { - pub organization: Option<(String, String)>, - pub cluster: Option<(String, String)>, -} - pub struct ApiClient { pub base_url: String, credentials: CredentialSource, @@ -77,7 +83,6 @@ pub struct ApiClient { routing: Arc, deployment: Option<(String, String)>, scope: Scope, - saved: SavedIds, } impl ApiClient { @@ -89,29 +94,11 @@ impl ApiClient { routing: Arc::default(), deployment: None, scope: Scope::default(), - saved: SavedIds::default(), } } - pub fn with_saved_ids(mut self, saved: SavedIds) -> Self { - self.saved = saved; - self - } - - /// Whether any request used an ID from the config instead of resolving a name. - pub fn used_saved_ids(&self) -> bool { - self.routing.saved_id_used.load(Ordering::Relaxed) - } - - /// The saved ID for `name`, when it is the organization the config saved. - pub fn saved_organization_id(&self, name: &str) -> Option { - let (_, id) = self - .saved - .organization - .as_ref() - .filter(|(saved, _)| saved == name)?; - self.routing.saved_id_used.store(true, Ordering::Relaxed); - Some(id.clone()) + pub fn scope(&self) -> &Scope { + &self.scope } pub fn has_api_key(&self) -> Result { @@ -129,7 +116,6 @@ impl ApiClient { routing: self.routing.clone(), deployment: self.deployment.clone(), scope, - saved: self.saved.clone(), } } @@ -172,7 +158,6 @@ impl ApiClient { routing: Arc::default(), deployment: self.deployment.clone(), scope: self.scope.clone(), - saved: self.saved.clone(), }) } @@ -288,15 +273,7 @@ impl ApiClient { pub fn get(&self, path: &str) -> Result { let value: Value = if path == "/v1/clusters" && self.has_user_credential()? && self.deployment.is_none() { - let saved = self - .scope - .organization - .as_deref() - .and_then(|name| self.saved_organization_id(name)); - self.discover_clusters( - saved.as_deref().or(self.scope.organization.as_deref()), - 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")?)? diff --git a/src/client/discovery.rs b/src/client/discovery.rs index d171b3d..e36cbc8 100644 --- a/src/client/discovery.rs +++ b/src/client/discovery.rs @@ -1,8 +1,8 @@ use super::{ handle_response, regions::Region, - routing::{before_deadline, is_uuid, valid_routing, with_scope_headers, Organization}, - ApiClient, + routing::{before_deadline, valid_routing, with_scope_headers}, + ApiClient, Selector, }; use anyhow::{Context, Result}; use reqwest::{blocking::RequestBuilder, Method, StatusCode}; @@ -114,28 +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, ) -> Result { let selected: Vec<_> = match organization { - Some(id) if is_uuid(id) => vec![Organization { - organization_id: id.to_owned(), - name: id.to_owned(), - }], - _ => self - .organizations(deadline)? - .into_iter() - .filter(|item| { - organization.is_none_or(|selected| { - item.name == selected || item.organization_id == selected - }) - }) - .collect(), + Some(selector) => vec![self.find_organization(selector, deadline)?], + None => self.organizations(deadline)?, }; - anyhow::ensure!( - organization.is_none() || !selected.is_empty(), - "Organization not found." - ); let mut catalogs = Vec::new(); for owner in selected { let regions = self.regions_for_organization(&owner.organization_id, deadline)?; diff --git a/src/client/regions.rs b/src/client/regions.rs index bfe824e..3ca6198 100644 --- a/src/client/regions.rs +++ b/src/client/regions.rs @@ -1,4 +1,4 @@ -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}; @@ -21,7 +21,7 @@ pub struct Regions { } impl ApiClient { - pub fn list_regions(&self, organization: &str) -> Result { + pub fn list_regions(&self, organization: &Selector) -> Result { let id = self.organization_id(organization)?; self.regions_for_organization(&id, None) } @@ -37,8 +37,9 @@ 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 { + /// 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 { anyhow::ensure!( !self .token()? @@ -46,8 +47,11 @@ impl ApiClient { .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 @@ -65,6 +69,7 @@ impl ApiClient { 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) } } diff --git a/src/client/routing.rs b/src/client/routing.rs index 62f6984..1ec5cd0 100644 --- a/src/client/routing.rs +++ b/src/client/routing.rs @@ -1,5 +1,5 @@ use super::{ - discovery::UnavailableRegion, handle_response, ApiClient, CLUSTER_ID_HEADER, + discovery::UnavailableRegion, handle_response, ApiClient, Selector, CLUSTER_ID_HEADER, ORGANIZATION_ID_HEADER, }; use anyhow::{Context, Result}; @@ -7,10 +7,7 @@ use reqwest::{blocking::RequestBuilder, Method, Url}; use serde::Deserialize; use std::{ collections::HashMap, - sync::{ - atomic::{AtomicBool, Ordering}, - Mutex, - }, + sync::Mutex, time::{Duration, Instant}, }; @@ -44,7 +41,6 @@ pub(super) struct RoutingCache { organizations: Mutex)>>, clusters: Mutex>, bound_cluster: Mutex>, - pub(super) saved_id_used: AtomicBool, } impl RoutingCache { @@ -59,19 +55,9 @@ impl RoutingCache { } } -enum ClusterSelector { - Id(String), - Name(String), -} - -enum OrganizationSelector { - Id(String), - Name(String), -} - struct Selectors { - organization: Option, - cluster: Option, + organization: Option, + cluster: Option, /// The cluster is addressed by the URL path, so no cluster header is sent. cluster_in_path: bool, } @@ -83,7 +69,7 @@ pub(super) struct ResolvedScope { deployment: Option<(String, String)>, } -pub(crate) fn is_uuid(value: &str) -> bool { +pub(super) fn is_uuid(value: &str) -> bool { value.len() == 36 && value.bytes().enumerate().all(|(index, byte)| match index { 8 | 13 | 18 | 23 => byte == b'-', @@ -91,14 +77,6 @@ pub(crate) fn is_uuid(value: &str) -> bool { }) } -fn organization_selector(value: &str) -> OrganizationSelector { - if is_uuid(value) { - OrganizationSelector::Id(value.to_owned()) - } else { - OrganizationSelector::Name(value.to_owned()) - } -} - pub(super) fn with_scope_headers( request: RequestBuilder, organization_id: Option<&str>, @@ -121,21 +99,13 @@ impl ApiClient { self.routing.store_organizations(response.organizations); } } else if path == "/v1/clusters" { - let selected = self.scope.organization.as_deref().and_then(|organization| { - if is_uuid(organization) { - Some(organization.to_owned()) - } else if let Some((_, id)) = self - .saved - .organization - .as_ref() - .filter(|(name, _)| name == organization) - { - Some(id.clone()) - } else { - self.cached_organization(organization) - .map(|item| item.organization_id) - } - }); + let selected = match &self.scope.organization { + Some(Selector::Id(id)) => Some(id.clone()), + Some(Selector::Name(name)) => self + .cached_organization(name) + .map(|item| item.organization_id), + None => None, + }; if let Some(organization_id) = selected { if let Ok(response) = serde_json::from_value::(value.clone()) { self.routing @@ -148,47 +118,36 @@ impl ApiClient { } } - fn cached_organization(&self, name_or_id: &str) -> Option { + fn cached_organization(&self, name: &str) -> Option { let cache = self.routing.organizations.lock().unwrap(); let (time, organizations) = cache.as_ref()?; if time.elapsed() >= Duration::from_secs(30) { return None; } - organizations - .iter() - .find(|item| item.name == name_or_id || item.organization_id == name_or_id) - .cloned() + organizations.iter().find(|item| item.name == name).cloned() } - /// Resolves an organization name or ID to its ID. - pub fn organization_id(&self, name_or_id: &str) -> Result { - if let Some(id) = self.saved_organization_id(name_or_id) { - return Ok(id); - } - self.find_organization(&organization_selector(name_or_id), None) + pub fn organization_id(&self, organization: &Selector) -> Result { + self.find_organization(organization, None) .map(|organization| organization.organization_id) } - fn find_organization( + pub(super) fn find_organization( &self, - selector: &OrganizationSelector, + selector: &Selector, deadline: Option, ) -> Result { - if let OrganizationSelector::Id(id) = selector { - return Ok(Organization { + match selector { + Selector::Id(id) => Ok(Organization { organization_id: id.clone(), name: id.clone(), - }); + }), + Selector::Name(name) => self + .organizations(deadline)? + .into_iter() + .find(|item| item.name == *name) + .context("Organization not found."), } - let matches = |item: &Organization| match selector { - OrganizationSelector::Id(id) => item.organization_id == *id, - OrganizationSelector::Name(name) => item.name == *name, - }; - let organizations = self.organizations(deadline)?; - organizations - .into_iter() - .find(|item| matches(item)) - .context("Organization not found.") } pub(super) fn organizations(&self, deadline: Option) -> Result> { @@ -272,8 +231,8 @@ impl ApiClient { deadline: Option, ) -> Result { let organization_id = match selectors.organization { - Some(OrganizationSelector::Id(id)) => Some(id), - Some(OrganizationSelector::Name(name)) if self.token()?.is_some() => { + Some(Selector::Id(id)) => Some(id), + Some(Selector::Name(name)) if self.token()?.is_some() => { let organization = self .organizations(deadline)? .into_iter() @@ -283,7 +242,7 @@ impl ApiClient { })?; Some(organization.organization_id) } - Some(OrganizationSelector::Name(_)) | None => None, + Some(Selector::Name(_)) | None => None, }; let mut scope = ResolvedScope { organization_id, @@ -293,9 +252,9 @@ impl ApiClient { return Ok(scope); } scope.cluster_id = match selectors.cluster { - Some(ClusterSelector::Id(id)) => Some(id), - Some(ClusterSelector::Name(_)) if self.token()?.is_none() => None, - Some(ClusterSelector::Name(name)) => { + Some(Selector::Id(id)) => Some(id), + Some(Selector::Name(_)) if self.token()?.is_none() => None, + Some(Selector::Name(name)) => { let bound = self.bound_cluster(deadline)?; anyhow::ensure!( bound.name == name, @@ -345,8 +304,8 @@ impl ApiClient { }; let Some(organization) = organization else { match cluster { - ClusterSelector::Id(id) => scope.cluster_id = Some(id), - ClusterSelector::Name(name) => anyhow::bail!( + Selector::Id(id) => scope.cluster_id = Some(id), + Selector::Name(name) => anyhow::bail!( "Choose an organization with --org to select cluster '{name}' by name." ), } @@ -354,8 +313,8 @@ impl ApiClient { }; let clusters = self.organization_clusters(&organization, deadline)?; let target = clusters.clusters.iter().find(|item| match &cluster { - ClusterSelector::Id(id) => item.id == *id, - ClusterSelector::Name(name) => item.name == *name, + Selector::Id(id) => item.id == *id, + Selector::Name(name) => item.name == *name, }); if target.is_none() && !clusters.unavailable_regions.is_empty() { // Keep known routes usable, but retry missing routes after a region recovers. @@ -369,8 +328,8 @@ impl ApiClient { if !selectors.cluster_in_path { scope.cluster_id = match (&cluster, target) { (_, Some(target)) => Some(target.id.clone()), - (ClusterSelector::Id(id), None) => Some(id.clone()), - (ClusterSelector::Name(name), None) => { + (Selector::Id(id), None) => Some(id.clone()), + (Selector::Name(name), None) => { anyhow::bail!( "Cluster '{name}' not found in organization '{}'.", organization.name @@ -405,9 +364,9 @@ impl ApiClient { if let Some(clusters) = cached { return Ok(clusters); } - let response: Clusters = serde_json::from_value( - self.discover_clusters(Some(&organization.organization_id), deadline)?, - )?; + let selector = Selector::Id(organization.organization_id.clone()); + let response: Clusters = + serde_json::from_value(self.discover_clusters(Some(&selector), deadline)?)?; self.routing.clusters.lock().unwrap().insert( organization.organization_id.clone(), (Instant::now(), response.clone()), @@ -434,27 +393,6 @@ pub(super) fn before_deadline( impl ApiClient { fn selectors(&self, path: &str) -> Selectors { - let saved_organization = self - .saved - .organization - .as_ref() - .filter(|(name, _)| self.scope.organization.as_deref() == Some(name.as_str())); - let saved_cluster = self - .saved - .cluster - .as_ref() - .filter(|(name, _)| self.scope.cluster.as_deref() == Some(name.as_str())); - let organization = match saved_organization { - Some((_, id)) => { - self.routing.saved_id_used.store(true, Ordering::Relaxed); - Some(OrganizationSelector::Id(id.clone())) - } - None => self - .scope - .organization - .as_deref() - .map(organization_selector), - }; let path_cluster = path .split('?') .next() @@ -464,26 +402,11 @@ impl ApiClient { !part.is_empty() && !matches!(*part, "sizes" | "metrics" | "verify-s3-access") }) .and_then(|id| urlencoding::decode(id).ok()) - .map(|id| id.into_owned()); - let cluster_in_path = path_cluster.is_some(); - let cluster = match (path_cluster, saved_cluster) { - (Some(id), _) => Some(ClusterSelector::Id(id)), - (None, Some((_, id))) => { - self.routing.saved_id_used.store(true, Ordering::Relaxed); - Some(ClusterSelector::Id(id.clone())) - } - (None, None) => self.scope.cluster.as_deref().map(|cluster| { - if is_uuid(cluster) { - ClusterSelector::Id(cluster.to_owned()) - } else { - ClusterSelector::Name(cluster.to_owned()) - } - }), - }; + .map(|id| Selector::Id(id.into_owned())); Selectors { - organization, - cluster, - cluster_in_path, + organization: self.scope.organization.clone(), + cluster_in_path: path_cluster.is_some(), + cluster: path_cluster.or_else(|| self.scope.cluster.clone()), } } diff --git a/src/client/routing_tests.rs b/src/client/routing_tests.rs index fe3f96c..c97cc8a 100644 --- a/src/client/routing_tests.rs +++ b/src/client/routing_tests.rs @@ -1,4 +1,4 @@ -use super::{ApiClient, SavedIds, Scope}; +use super::{ApiClient, Scope, Selector}; use serde_json::{json, Value}; use std::collections::HashMap; use std::io::{BufRead, BufReader, Read, Write}; @@ -271,7 +271,10 @@ fn api_keys_resolve_organization_names_to_ids_for_paths() { json!({"organizations":[{"organization_id":ORG,"name":"acme","role":null}]}), )]); let client = ApiClient::new(base, Some("rt_fixture".to_string())); - assert_eq!(client.organization_id("acme").unwrap(), ORG); + assert_eq!( + client.organization_id(&Selector::parse("acme")).unwrap(), + ORG + ); assert_eq!(server.join().unwrap().len(), 1); } @@ -444,7 +447,10 @@ fn creation_and_sizes_use_selected_region_without_mutating_default_client() { ]); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - let regional = client.for_region(Some("acme"), "region-id").unwrap(); + let regional = client + .with_scope(Scope::organization(Some("acme"))) + .for_region("region-id") + .unwrap(); let _: Value = regional.get("/v1/clusters/sizes").unwrap(); let _: Value = regional .with_scope(Scope::new(Some("acme"), None)) @@ -479,7 +485,10 @@ fn explicit_unusable_regions_never_reach_creation() { ] { let (base, server) = server(region_catalog(overrides)); let client = ApiClient::new(base, Some("session.fixture".into())); - assert!(client.for_region(Some("acme"), "region-id").is_err()); + assert!(client + .with_scope(Scope::organization(Some("acme"))) + .for_region("region-id") + .is_err()); assert_eq!(server.join().unwrap().len(), 2); } } @@ -492,7 +501,10 @@ fn legacy_region_is_rejected_and_unscoped_size_discovery_keeps_default_routing() responses.push(("200 OK", json!({}))); let (base, server) = server(responses); let client = ApiClient::new(base, Some("session.fixture".into())); - assert!(client.for_region(Some("acme"), id).is_err()); + assert!(client + .with_scope(Scope::organization(Some("acme"))) + .for_region(id) + .is_err()); let _: Value = client.get("/v1/clusters/sizes").unwrap(); for request in server.join().unwrap() { assert!(!request.headers.contains_key("x-rawtree-region")); @@ -503,7 +515,8 @@ fn legacy_region_is_rejected_and_unscoped_size_discovery_keeps_default_routing() fn api_keys_cannot_override_their_embedded_deployment() { let client = ApiClient::new("http://127.0.0.1:1".into(), Some("rt_fixture".into())); assert!(client - .for_region(Some("acme"), "region-id") + .with_scope(Scope::organization(Some("acme"))) + .for_region("region-id") .err() .unwrap() .to_string() @@ -885,42 +898,21 @@ fn organization_names_and_ids_resolve_to_ids_from_one_listing() { json!({"organizations":[{"organization_id":ORG,"name":"acme"}]}), )]); let client = ApiClient::new(base, Some("session.fixture".into())); - assert_eq!(client.organization_id("acme").unwrap(), ORG); - assert_eq!(client.organization_id(ORG).unwrap(), ORG); + assert_eq!( + client.organization_id(&Selector::parse("acme")).unwrap(), + ORG + ); + assert_eq!(client.organization_id(&Selector::parse(ORG)).unwrap(), ORG); assert!(client - .organization_id("missing") + .organization_id(&Selector::parse("missing")) .unwrap_err() .to_string() .contains("Organization not found")); assert_eq!(server.join().unwrap().len(), 1); } -fn saved(organization: bool, cluster: bool) -> SavedIds { - SavedIds { - organization: organization.then(|| ("acme".to_string(), ORG.to_string())), - cluster: cluster.then(|| ("production".to_string(), CLUSTER.to_string())), - } -} - -#[test] -fn saved_ids_are_sent_without_lookups_for_api_keys() { - let (base, server) = server(vec![("200 OK", json!({}))]); - let client = - ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(saved(true, true)); - assert!(!client.used_saved_ids()); - client - .with_scope(Scope::new(Some("acme"), Some("production"))) - .post_raw("/v1/query", &json!({"query":"SELECT 1"})) - .unwrap(); - assert!(client.used_saved_ids()); - let requests = server.join().unwrap(); - assert_eq!(requests.len(), 1); - assert_eq!(requests[0].headers["x-rawtree-organization-id"], ORG); - assert_eq!(requests[0].headers["x-rawtree-cluster-id"], CLUSTER); -} - #[test] -fn saved_ids_skip_the_organization_listing_but_keep_regional_routing() { +fn id_selectors_skip_the_organization_listing_but_keep_regional_routing() { let (base, server) = server(vec![ ( "200 OK", @@ -932,10 +924,9 @@ fn saved_ids_skip_the_organization_listing_but_keep_regional_routing() { ), ("200 OK", json!({})), ]); - let client = - ApiClient::new(base, Some("session.fixture".to_string())).with_saved_ids(saved(true, true)); + let client = ApiClient::new(base, Some("session.fixture".to_string())); let _: Value = client - .with_scope(Scope::new(Some("acme"), Some("production"))) + .with_scope(Scope::new(Some(ORG), Some(CLUSTER))) .get("/v1/databases") .unwrap(); let requests = server.join().unwrap(); @@ -948,46 +939,3 @@ fn saved_ids_skip_the_organization_listing_but_keep_regional_routing() { assert_eq!(requests[2].headers["x-rawtree-cluster-id"], CLUSTER); assert_eq!(requests[2].headers["x-rawtree-deployment-id"], "12abcdef"); } - -#[test] -fn names_that_differ_from_the_saved_ones_are_resolved_by_name() { - const OTHER_ORG: &str = "00000000-0000-4000-8000-000000000002"; - let (base, server) = server(vec![ - ( - "200 OK", - json!({"organizations":[{"organization_id":OTHER_ORG,"name":"other","role":null}]}), - ), - ( - "200 OK", - json!({"clusters":[{"id":CLUSTER,"name":"staging"}]}), - ), - ("200 OK", json!({})), - ]); - let client = - ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(saved(true, true)); - client - .with_scope(Scope::new(Some("other"), Some("staging"))) - .post_raw("/v1/query", &json!({"query":"SELECT 1"})) - .unwrap(); - assert!(!client.used_saved_ids()); - let requests = server.join().unwrap(); - assert_eq!(requests.len(), 3); - assert_eq!(requests[2].headers["x-rawtree-organization-id"], OTHER_ORG); -} - -#[test] -fn a_renamed_cluster_keeps_working_through_its_saved_id() { - let (base, server) = server(vec![("200 OK", json!({}))]); - let client = ApiClient::new(base, Some("rt_fixture".to_string())).with_saved_ids(SavedIds { - organization: None, - cluster: Some(("old-name".to_string(), CLUSTER.to_string())), - }); - client - .with_scope(Scope::new(None, Some("old-name"))) - .post_raw("/v1/query", &json!({"query":"SELECT 1"})) - .unwrap(); - assert_eq!( - server.join().unwrap()[0].headers["x-rawtree-cluster-id"], - CLUSTER - ); -} diff --git a/src/commands/cluster.rs b/src/commands/cluster.rs index 0ac47c0..2832582 100644 --- a/src/commands/cluster.rs +++ b/src/commands/cluster.rs @@ -6,7 +6,7 @@ use serde_json::{json, Value}; use super::table_output::new_cli_table; use crate::cli::ClusterSizeArg; -use crate::client::{ApiClient, SavedIds, Scope, UnavailableRegion}; +use crate::client::{ApiClient, Scope, UnavailableRegion}; use crate::cluster_identity::ClusterIdentityArgs; use crate::config::{self, Config}; use crate::output; @@ -123,7 +123,7 @@ pub fn create( json_mode: bool, ) -> Result<()> { let s3_storage = options.s3_storage.to_json()?; - let placement_client = client.for_region(options.organization, options.region_id)?; + let placement_client = client.for_region(options.region_id)?; let (_, sizes) = load_cluster_sizes(&placement_client)?; let (min_index, min_size) = resolve_cluster_size(&sizes.sizes, options.min_size)?; let (max_index, max_size) = options @@ -146,9 +146,7 @@ pub fn create( ); body["region_id"] = json!(options.region_id); - let value: Value = client - .with_scope(Scope::organization(options.organization)) - .post("/v1/clusters", &body)?; + let value: Value = client.post("/v1/clusters", &body)?; let created: ClusterItem = serde_json::from_value(value.clone()).context("invalid cluster response from server")?; @@ -184,7 +182,6 @@ pub fn create( pub struct ClusterCreateOptions<'a> { pub region_id: &'a str, - pub organization: Option<&'a str>, pub name: &'a str, pub replicas: u32, pub min_size: ClusterSizeArg, @@ -197,7 +194,6 @@ pub struct ClusterCreateOptions<'a> { pub fn update( client: &ApiClient, name_or_id: &str, - organization: Option<&str>, name: Option<&str>, idle_timeout_minutes: Option, json_mode: bool, @@ -208,8 +204,7 @@ pub fn update( ); } - let client = client.with_scope(Scope::organization(organization)); - let (_, response) = load_dedicated_clusters(&client)?; + let (_, response) = load_dedicated_clusters(client)?; let cluster = resolve_cluster(&response, name_or_id)?; let mut body = serde_json::Map::new(); if let Some(name) = name { @@ -243,8 +238,7 @@ pub fn update( } pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Result<()> { - let client = client.with_scope(Scope::organization(organization)); - let (value, resp) = load_dedicated_clusters(&client)?; + let (value, resp) = load_dedicated_clusters(client)?; output::print_result(&value, json_mode, |_| { if !resp.unavailable_regions.is_empty() { let names = resp @@ -307,7 +301,8 @@ pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Ok(()) } -pub fn regions(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Result<()> { +pub fn regions(client: &ApiClient, json_mode: bool) -> Result<()> { + let organization = client.scope().organization.as_ref(); let response = client.list_regions(organization.context("Choose an organization with --org.")?)?; output::print_result(&response, json_mode, |response| { @@ -364,10 +359,8 @@ pub fn use_cluster( organization: Option<&str>, json_mode: bool, ) -> Result<()> { - // Re-resolve by name: this command is how a rejected saved ID gets refreshed. let cluster_id = client .with_scope(Scope::new(organization, Some(name))) - .with_saved_ids(SavedIds::default()) .resolve_scope_ids() .ok() .and_then(|(_, cluster_id)| cluster_id); @@ -382,14 +375,8 @@ pub fn use_cluster( Ok(()) } -pub fn status( - client: &ApiClient, - name_or_id: &str, - organization: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::organization(organization)); - let (_, resp) = load_dedicated_clusters(&client)?; +pub fn status(client: &ApiClient, name_or_id: &str, json_mode: bool) -> Result<()> { + let (_, resp) = load_dedicated_clusters(client)?; let cluster = resolve_cluster(&resp, name_or_id)?; output::print_result(cluster, json_mode, |cluster| { @@ -428,44 +415,16 @@ pub fn status( Ok(()) } -pub fn stop( - client: &ApiClient, - name_or_id: &str, - organization: Option<&str>, - json_mode: bool, -) -> Result<()> { - request_lifecycle( - client, - name_or_id, - organization, - LifecycleAction::Stop, - json_mode, - ) +pub fn stop(client: &ApiClient, name_or_id: &str, json_mode: bool) -> Result<()> { + request_lifecycle(client, name_or_id, LifecycleAction::Stop, json_mode) } -pub fn resume( - client: &ApiClient, - name_or_id: &str, - organization: Option<&str>, - json_mode: bool, -) -> Result<()> { - request_lifecycle( - client, - name_or_id, - organization, - LifecycleAction::Resume, - json_mode, - ) +pub fn resume(client: &ApiClient, name_or_id: &str, json_mode: bool) -> Result<()> { + request_lifecycle(client, name_or_id, LifecycleAction::Resume, json_mode) } -pub fn delete( - client: &ApiClient, - name_or_id: &str, - organization: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::organization(organization)); - let (_, resp) = load_dedicated_clusters(&client)?; +pub fn delete(client: &ApiClient, name_or_id: &str, json_mode: bool) -> Result<()> { + let (_, resp) = load_dedicated_clusters(client)?; let cluster = resolve_cluster(&resp, name_or_id)?.clone(); let path = cluster_path(&cluster.id, None); let result: DeleteClusterResponse = client.delete(&path)?; @@ -617,12 +576,10 @@ fn resolve_cluster<'a>( fn request_lifecycle( client: &ApiClient, name_or_id: &str, - organization: Option<&str>, action: LifecycleAction, json_mode: bool, ) -> Result<()> { - let client = client.with_scope(Scope::organization(organization)); - let (_, resp) = load_dedicated_clusters(&client)?; + let (_, resp) = load_dedicated_clusters(client)?; let cluster = resolve_cluster(&resp, name_or_id)?; let path = cluster_path(&cluster.id, Some(action.path_segment())); let value: Value = client.post_empty(&path)?; diff --git a/src/commands/database.rs b/src/commands/database.rs index f8fd7d8..67fc139 100644 --- a/src/commands/database.rs +++ b/src/commands/database.rs @@ -2,7 +2,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::config; use crate::output; use crate::s3_storage::{format_storage, S3StorageArgs, S3StorageMetadata}; @@ -42,13 +42,7 @@ fn apply_database_create_config( } } -pub fn list( - client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn list(client: &ApiClient, json_mode: bool) -> Result<()> { let resp: ListDatabasesResponse = client.get("/v1/databases")?; output::print_result(&resp, json_mode, |resp| { if resp.databases.is_empty() { @@ -80,7 +74,6 @@ pub fn create( if let Some(storage) = s3_storage { body["s3_storage"] = storage; } - let client = client.with_scope(Scope::new(organization, cluster)); let resp: CreateDatabaseResponse = client.post("/v1/databases", &body)?; let _config_lock = config::lock()?; let mut cfg = config::load()?; @@ -114,14 +107,7 @@ struct DeleteDatabaseResponse { deleted: bool, } -pub fn delete( - client: &ApiClient, - name: &str, - organization: Option<&str>, - cluster: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn delete(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { let path = format!("/v1/databases/{}", urlencoding::encode(name)); let resp: DeleteDatabaseResponse = client.delete(&path)?; output::print_result( diff --git a/src/commands/federation_issuer.rs b/src/commands/federation_issuer.rs index f25ccd6..a348e8c 100644 --- a/src/commands/federation_issuer.rs +++ b/src/commands/federation_issuer.rs @@ -4,7 +4,10 @@ use serde::Serialize; use serde_json::Value; use super::service_account::{parse_description, parse_name}; -use crate::{client::ApiClient, org, output}; +use crate::{ + client::{ApiClient, Selector}, + org, output, +}; #[derive(Clone, Debug, Serialize, ValueEnum)] #[serde(rename_all = "snake_case")] @@ -64,7 +67,7 @@ impl Configuration { pub fn run( client: &ApiClient, - organization: Option<&str>, + organization: Option<&Selector>, action: Command, json: bool, ) -> Result<()> { diff --git a/src/commands/federation_rule.rs b/src/commands/federation_rule.rs index 7409933..1f0f237 100644 --- a/src/commands/federation_rule.rs +++ b/src/commands/federation_rule.rs @@ -6,10 +6,7 @@ use serde::Serialize; use serde_json::Value; use super::service_account::{parse_description, parse_name}; -use crate::{ - client::{ApiClient, Scope}, - output, -}; +use crate::{client::ApiClient, output}; #[derive(Clone, Debug, Serialize, ValueEnum)] #[serde(rename_all = "snake_case")] @@ -104,18 +101,16 @@ pub enum Command { }, } -pub fn run( - client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, - action: Command, - json: bool, -) -> Result<()> { - let organization = organization +pub fn run(client: &ApiClient, action: Command, json: bool) -> Result<()> { + let scope = client.scope(); + scope + .organization + .as_ref() .context("Select an organization with --org, RAWTREE_ORG or `rtree organization use`")?; - let cluster = cluster + scope + .cluster + .as_ref() .context("Select a cluster with --cluster, RAWTREE_CLUSTER or `rtree cluster use`")?; - let client = client.with_scope(Scope::new(Some(organization), Some(cluster))); let path = |id: Option<&str>| match id { Some(id) => format!("/v1/federation-rules/{}", urlencoding::encode(id)), None => "/v1/federation-rules".into(), diff --git a/src/commands/format.rs b/src/commands/format.rs index 64cf81c..b6117e7 100644 --- a/src/commands/format.rs +++ b/src/commands/format.rs @@ -6,10 +6,7 @@ use clap::Args; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::{ - client::{ApiClient, Scope}, - org, -}; +use crate::{client::ApiClient, org}; #[derive(Args)] pub struct FormatArgs { @@ -32,12 +29,9 @@ struct QueryFormatResponse { pub fn format( client: &ApiClient, database: Option<&str>, - organization: Option<&str>, - cluster: Option<&str>, sql: &str, json_mode: bool, ) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); let path = match database { Some(database) => org::database_path(database, "/query-format"), None => "/v1/query-format".to_string(), diff --git a/src/commands/insert.rs b/src/commands/insert.rs index 9ba2a46..eafb404 100644 --- a/src/commands/insert.rs +++ b/src/commands/insert.rs @@ -11,7 +11,7 @@ use indicatif::{ProgressBar, ProgressStyle}; use serde::Deserialize; use serde_json::{json, Value}; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::org; use crate::output; @@ -72,8 +72,6 @@ fn append_transform_param(path: &str, transform: Option<&str>) -> String { pub fn insert( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, table: &str, data: Option<&str>, file: Option<&str>, @@ -81,8 +79,6 @@ pub fn insert( transform: Option<&str>, json_mode: bool, ) -> Result<()> { - let scoped = client.with_scope(Scope::new(organization, cluster)); - let client = &scoped; let base_path = org::database_path(database, &format!("/tables/{table}")); let api_path = append_transform_param(&base_path, transform); diff --git a/src/commands/integration.rs b/src/commands/integration.rs index 9440549..9053a96 100644 --- a/src/commands/integration.rs +++ b/src/commands/integration.rs @@ -4,7 +4,7 @@ use serde_json::Value; use super::open; use super::table_output::new_cli_table; -use crate::client::ApiClient; +use crate::client::{ApiClient, Selector}; use crate::output; #[derive(Deserialize)] @@ -24,7 +24,7 @@ struct Integration { created_at: String, } -fn integrations_path(client: &ApiClient, organization: Option<&str>) -> Result { +fn integrations_path(client: &ApiClient, organization: Option<&Selector>) -> Result { Ok(format!( "{}/integrations", crate::org::organization_path(client, organization)? @@ -64,7 +64,7 @@ fn describe_settings(integration: &Integration) -> String { } } -pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Result<()> { +pub fn list(client: &ApiClient, organization: Option<&Selector>, json_mode: bool) -> Result<()> { let value: Value = client.get(&integrations_path(client, organization)?)?; print_response(value, json_mode, |resp: IntegrationsResponse| { if resp.integrations.is_empty() { diff --git a/src/commands/keys.rs b/src/commands/keys.rs index b44076e..24a8012 100644 --- a/src/commands/keys.rs +++ b/src/commands/keys.rs @@ -2,7 +2,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::org; use crate::output; @@ -59,13 +59,7 @@ struct DeleteApiKeyResponse { deleted: bool, } -pub fn list( - client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn list(client: &ApiClient, json_mode: bool) -> Result<()> { let resp: ListApiKeysResponse = client.get("/v1/api-keys")?; output::print_result(&resp, json_mode, |_| { if resp.keys.is_empty() { @@ -99,12 +93,9 @@ pub struct CreateApiKeyRequest<'a> { pub fn create( client: &ApiClient, database: Option<&str>, - organization: Option<&str>, - cluster: Option<&str>, request: CreateApiKeyRequest<'_>, json_mode: bool, ) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); let path = match database { Some(database) => org::database_path(database, "/api-keys"), None => "/v1/api-keys".to_string(), @@ -124,14 +115,7 @@ pub fn create( Ok(()) } -pub fn delete( - client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, - id: uuid::Uuid, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn delete(client: &ApiClient, id: uuid::Uuid, json_mode: bool) -> Result<()> { let path = format!("/v1/api-keys/{id}"); let resp: DeleteApiKeyResponse = client.delete(&path)?; output::print_result( diff --git a/src/commands/logs.rs b/src/commands/logs.rs index 5eca2bc..758e3de 100644 --- a/src/commands/logs.rs +++ b/src/commands/logs.rs @@ -3,7 +3,7 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::output; #[derive(Debug, Deserialize, Serialize)] @@ -280,8 +280,6 @@ fn format_log_line(entry: &LogEntry) -> String { #[allow(clippy::too_many_arguments)] fn fetch_logs( client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, start_time: &str, end_time: &str, search: Option<&str>, @@ -313,16 +311,12 @@ fn fetch_logs( limit, offset, ); - client - .with_scope(Scope::new(organization, cluster)) - .get(&format!("/v1/logs?{query_string}")) + client.get(&format!("/v1/logs?{query_string}")) } #[allow(clippy::too_many_arguments)] pub fn logs( client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, search: Option<&str>, methods: &[String], status_codes: &[u16], @@ -352,8 +346,6 @@ pub fn logs( let (resolved_start, resolved_end) = resolve_time_range(since, until, start_time, end_time)?; let resp = fetch_logs( client, - organization, - cluster, &resolved_start, &resolved_end, search, diff --git a/src/commands/organization.rs b/src/commands/organization.rs index bbee136..c82b868 100644 --- a/src/commands/organization.rs +++ b/src/commands/organization.rs @@ -2,7 +2,7 @@ use anyhow::Result; use serde::Deserialize; use serde_json::json; -use crate::client::{ApiClient, SavedIds, Scope}; +use crate::client::{ApiClient, Selector}; use crate::config::{self, Config}; use crate::org; use crate::output; @@ -89,12 +89,7 @@ pub fn create(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { } pub fn use_organization(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { - // Re-resolve by name: this command is how a rejected saved ID gets refreshed. - let id = client - .with_scope(Scope::default()) - .with_saved_ids(SavedIds::default()) - .organization_id(name) - .ok(); + let id = client.organization_id(&Selector::parse(name)).ok(); let _config_lock = config::lock()?; let mut cfg = config::load()?; if cfg.default_organization_id != id { @@ -110,7 +105,7 @@ pub fn use_organization(client: &ApiClient, name: &str, json_mode: bool) -> Resu } pub fn rename(client: &ApiClient, old: &str, new_name: &str, json_mode: bool) -> Result<()> { - let id = client.organization_id(old)?; + let id = client.organization_id(&Selector::parse(old))?; let resp: RenameOrganizationResponse = client.patch( &format!("/v1/organizations/{}", urlencoding::encode(&id)), &json!({"organization_name": new_name}), @@ -131,7 +126,7 @@ pub fn rename(client: &ApiClient, old: &str, new_name: &str, json_mode: bool) -> } pub fn delete(client: &ApiClient, name: &str, json_mode: bool) -> Result<()> { - let id = client.organization_id(name)?; + let id = client.organization_id(&Selector::parse(name))?; let resp: DeleteOrganizationResponse = client.delete(&format!("/v1/organizations/{}", urlencoding::encode(&id)))?; if resp.deleted && is_default_org(&config::load()?, name, &id) { diff --git a/src/commands/query.rs b/src/commands/query.rs index 1962ee4..352a277 100644 --- a/src/commands/query.rs +++ b/src/commands/query.rs @@ -6,7 +6,7 @@ use console::style; use serde_json::json; use serde_json::{Map, Value}; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::org; #[derive(Default)] @@ -21,8 +21,6 @@ struct QuerySummary { pub fn query( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, sql: &str, limit: Option, json_mode: bool, @@ -33,8 +31,6 @@ pub fn query( }; let body = json!({ "sql": sql }); - - let client = client.with_scope(Scope::new(organization, cluster)); let raw = client.post_raw(&org::database_path(database, "/query"), &body)?; if let Ok(value) = serde_json::from_str::(&raw) { diff --git a/src/commands/service_account.rs b/src/commands/service_account.rs index 0905509..96f6a8a 100644 --- a/src/commands/service_account.rs +++ b/src/commands/service_account.rs @@ -3,7 +3,10 @@ use clap::ValueEnum; use serde::{Deserialize, Serialize}; use serde_json::json; -use crate::{client::ApiClient, output}; +use crate::{ + client::{ApiClient, Selector}, + output, +}; #[derive(Clone, Copy, Debug, Deserialize, Serialize, ValueEnum)] #[serde(rename_all = "snake_case")] @@ -59,14 +62,14 @@ pub fn parse_description(description: &str) -> Result { Ok(description.to_string()) } -fn collection_path(client: &ApiClient, organization: Option<&str>) -> Result { +fn collection_path(client: &ApiClient, organization: Option<&Selector>) -> Result { Ok(format!( "{}/service-accounts", crate::org::organization_path(client, organization)? )) } -pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> Result<()> { +pub fn list(client: &ApiClient, organization: Option<&Selector>, json_mode: bool) -> Result<()> { let accounts: Vec = client.get(&collection_path(client, organization)?)?; output::print_result(&json!({ "service_accounts": accounts }), json_mode, |_| { if accounts.is_empty() { @@ -88,7 +91,7 @@ pub fn list(client: &ApiClient, organization: Option<&str>, json_mode: bool) -> pub fn create( client: &ApiClient, - organization: Option<&str>, + organization: Option<&Selector>, request: CreateServiceAccount, json_mode: bool, ) -> Result<()> { diff --git a/src/commands/table.rs b/src/commands/table.rs index 19b95f6..8018055 100644 --- a/src/commands/table.rs +++ b/src/commands/table.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use super::table_output::new_cli_table; -use crate::client::{ApiClient, Scope}; +use crate::client::ApiClient; use crate::org; use crate::output; @@ -55,14 +55,7 @@ struct TableMutationResponse { storage: Option, } -pub fn list( - client: &ApiClient, - database: &str, - organization: Option<&str>, - cluster: Option<&str>, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn list(client: &ApiClient, database: &str, json_mode: bool) -> Result<()> { let list_path = org::database_path(database, "/tables"); let resp: TablesResponse = client.get(&list_path)?; output::print_result( @@ -94,15 +87,7 @@ pub fn list( Ok(()) } -pub fn describe( - client: &ApiClient, - database: &str, - organization: Option<&str>, - cluster: Option<&str>, - table: &str, - json_mode: bool, -) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); +pub fn describe(client: &ApiClient, database: &str, table: &str, json_mode: bool) -> Result<()> { let describe_path = org::database_path(database, &format!("/tables/{table}")); let resp: DescribeTableResponse = client.get(&describe_path)?; let details = &resp.table; @@ -149,13 +134,10 @@ pub fn describe( pub fn create( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, table: &str, sorting_key: Option<&str>, json_mode: bool, ) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); let path = org::database_path(database, "/tables"); let body = match sorting_key { Some(key) => json!({ "name": table, "sorting_key": key }), @@ -179,13 +161,10 @@ pub fn create( pub fn update( client: &ApiClient, database: &str, - organization: Option<&str>, - cluster: Option<&str>, table: &str, sorting_key: &str, json_mode: bool, ) -> Result<()> { - let client = client.with_scope(Scope::new(organization, cluster)); let path = org::database_path(database, &format!("/tables/{table}")); let response: TableMutationResponse = client.patch(&path, &json!({ "sorting_key": sorting_key }))?; @@ -219,7 +198,7 @@ fn format_bytes(bytes: u64) -> String { #[cfg(test)] mod tests { use super::{create, update, DescribeTableResponse, TablesResponse}; - use crate::client::ApiClient; + use crate::client::{ApiClient, Scope}; use serde_json::json; use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpListener; @@ -346,12 +325,11 @@ mod tests { } }); - let client = ApiClient::new(format!("http://{address}"), None); + let client = ApiClient::new(format!("http://{address}"), None) + .with_scope(Scope::new(Some(ORG), Some(CLUSTER))); create( &client, "analytics", - Some(ORG), - Some(CLUSTER), "events", Some("region, ifNull(cityHash64(host, instanceId), 0)"), true, @@ -360,8 +338,6 @@ mod tests { update( &client, "analytics", - Some(ORG), - Some(CLUSTER), "events", "region, toStartOfHour(timestamp)", true, diff --git a/src/main.rs b/src/main.rs index a6d58c5..dc1a31c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod org; mod output; mod s3_storage; +use std::cell::Cell; use std::io::{self, IsTerminal, Read}; use std::process::ExitCode; @@ -21,7 +22,7 @@ use cli::{ IntegrationKind, OrganizationCommand, ServiceAccountCommand, ShellType, TableCommand, WorkflowCommand, WorkflowSinkCommand, }; -use client::{ApiClient, SavedIds}; +use client::{ApiClient, Scope, Selector}; use constants::DEFAULT_API_URL; fn resolve_url_from_sources( @@ -64,20 +65,6 @@ fn resolve_database(cli_database: Option) -> Result { }) } -fn resolve_cluster_from_sources( - cli_cluster: Option, - env_cluster: Option, - cfg_cluster: Option, -) -> Option { - cli_cluster.or(env_cluster).or(cfg_cluster) -} - -fn resolve_cluster(cli_cluster: Option) -> Option { - let env_cluster = std::env::var("RAWTREE_CLUSTER").ok(); - let cfg_cluster = config::load().ok().and_then(|c| c.default_cluster); - resolve_cluster_from_sources(cli_cluster, env_cluster, cfg_cluster) -} - fn resolve_login_cluster_from_sources( cli_cluster: Option, env_cluster: Option, @@ -92,83 +79,126 @@ fn resolve_login_cluster(cli_cluster: Option) -> Option { resolve_login_cluster_from_sources(cli_cluster, env_cluster) } -fn resolve_org_from_sources( - cli_org: Option, - env_org: Option, - cfg_org: Option, -) -> Option { - cli_org.or(env_org).or(cfg_org) +/// An organization or cluster chosen by flag, environment or config. Only a +/// config choice carries the ID saved next to its name. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Choice { + name: String, + saved_id: Option, } -fn resolve_explicit_org(cli_org: Option) -> Option { - let env_org = std::env::var("RAWTREE_ORG").ok(); - let cfg_org = config::load().ok().and_then(|c| c.default_organization); - resolve_org_from_sources(cli_org, env_org, cfg_org) +impl Choice { + fn name(&self) -> &str { + &self.name + } } -fn resolve_effective_org_with( - explicit_org: Option, - fetch_default_org: F, -) -> Option -where - F: FnOnce() -> Option, -{ - explicit_org.or_else(fetch_default_org) +fn choose( + explicit: Option, + configured: Option, + saved_id: Option, +) -> Option { + match explicit { + Some(name) => Some(Choice { + name, + saved_id: None, + }), + None => configured.map(|name| Choice { name, saved_id }), + } } -fn resolve_effective_org(client: &ApiClient, cli_org: Option) -> Option { - let explicit_org = resolve_explicit_org(cli_org); - resolve_effective_org_with(explicit_org, || org::first_organization_name(client)) +/// The organization and cluster commands act on unless they name their own. +/// Remembers whether a command used an ID saved in the config, because a +/// rejected saved ID is never replaced by a name lookup. +struct Selection { + organization: Option, + cluster: Option, + used_saved_ids: Cell, } -/// Saved IDs apply only to selections that come from the config. A flag or -/// environment variable names its target explicitly and is resolved by name. -fn saved_ids_from_sources( - cli_org: Option<&str>, - env_org: Option<&str>, - cli_cluster: Option<&str>, - env_cluster: Option<&str>, - cfg: &config::Config, -) -> SavedIds { - let pair = |name: &Option, id: &Option| name.clone().zip(id.clone()); - SavedIds { - organization: (cli_org.is_none() && env_org.is_none()) - .then(|| pair(&cfg.default_organization, &cfg.default_organization_id)) - .flatten(), - cluster: (cli_org.is_none() - && env_org.is_none() - && cli_cluster.is_none() - && env_cluster.is_none()) - .then(|| pair(&cfg.default_cluster, &cfg.default_cluster_id)) - .flatten(), +impl Selection { + fn from_sources( + cli_org: Option, + env_org: Option, + cli_cluster: Option, + env_cluster: Option, + cfg: config::Config, + ) -> Self { + let explicit_org = cli_org.or(env_org); + // A saved cluster ID belongs to the saved organization. + let cluster_id = cfg.default_cluster_id.filter(|_| explicit_org.is_none()); + Self { + organization: choose( + explicit_org, + cfg.default_organization, + cfg.default_organization_id, + ), + cluster: choose(cli_cluster.or(env_cluster), cfg.default_cluster, cluster_id), + used_saved_ids: Cell::new(false), + } } -} - -fn saved_ids(cli_org: Option<&str>, cli_cluster: Option<&str>) -> SavedIds { - let Ok(cfg) = config::load() else { - return SavedIds::default(); - }; - saved_ids_from_sources( - cli_org, - std::env::var("RAWTREE_ORG").ok().as_deref(), - cli_cluster, - std::env::var("RAWTREE_CLUSTER").ok().as_deref(), - &cfg, - ) -} -/// A rejected saved ID is never replaced by a name lookup, so say how to refresh it. -fn explain_rejected_saved_ids(client: &ApiClient, error: anyhow::Error) -> anyhow::Error { - let message = format!("{error:#}"); - if client.used_saved_ids() - && error.downcast_ref::().is_none() - && (message.contains("(403)") || message.contains("(404)")) - { - anyhow::anyhow!( - "{message}\nThe saved organization or cluster ID was rejected; it may have been deleted or your access may have changed. Run `rtree organization use ` and `rtree cluster use `, or `rtree login` again." + fn load(cli_org: Option, cli_cluster: Option) -> Self { + Self::from_sources( + cli_org, + std::env::var("RAWTREE_ORG").ok(), + cli_cluster, + std::env::var("RAWTREE_CLUSTER").ok(), + config::load().unwrap_or_default(), ) - } else { - error + } + + /// The chosen organization, or else the first one the credential can see. + fn effective_organization(&self, client: &ApiClient) -> Option { + self.organization.clone().or_else(|| { + org::first_organization_name(client).map(|name| Choice { + name, + saved_id: None, + }) + }) + } + + fn selector(&self, choice: &Choice) -> Selector { + match &choice.saved_id { + Some(id) => { + self.used_saved_ids.set(true); + Selector::Id(id.clone()) + } + None => Selector::parse(&choice.name), + } + } + + fn organization_selector(&self) -> Option { + self.organization + .as_ref() + .map(|choice| self.selector(choice)) + } + + fn scope(&self, organization: Option<&Choice>, cluster: Option<&Choice>) -> Scope { + Scope { + organization: organization.map(|choice| self.selector(choice)), + cluster: cluster.map(|choice| self.selector(choice)), + } + } + + /// A client acting on the effective organization and the chosen cluster. + fn scoped(&self, client: &ApiClient) -> ApiClient { + let organization = self.effective_organization(client); + client.with_scope(self.scope(organization.as_ref(), self.cluster.as_ref())) + } + + fn explain_rejected_saved_ids(&self, error: anyhow::Error) -> anyhow::Error { + let message = format!("{error:#}"); + if self.used_saved_ids.get() + && error.downcast_ref::().is_none() + && (message.contains("(403)") || message.contains("(404)")) + { + anyhow::anyhow!( + "{message}\nThe saved organization or cluster ID was rejected; it may have been deleted or your access may have changed. Run `rtree organization use ` and `rtree cluster use `, or `rtree login` again." + ) + } else { + error + } } } @@ -215,7 +245,7 @@ fn ensure_single_stdin_reader(sql: Option<&str>, sinks: &[String]) -> Result<()> Ok(()) } -fn require_organization(organization: Option<&str>) -> Result<&str> { +fn require_organization(organization: Option) -> Result { organization.ok_or_else(|| { anyhow::anyhow!( "No organization specified. Use --org, RAWTREE_ORG env, or `rtree organization use `" @@ -225,23 +255,18 @@ fn require_organization(organization: Option<&str>) -> Result<&str> { /// API keys are bound to a cluster, so the backend takes their tenant from the /// key; user credentials must select one. -fn require_workflow_scope( - client: &ApiClient, - organization: Option<&str>, - cluster: Option<&str>, -) -> Result { +fn require_workflow_scope(client: &ApiClient, scope: Scope) -> Result { if client.has_api_key()? { - return Ok(client::Scope::new(organization, cluster)); + return Ok(scope); } - if organization.is_none() && !cluster.is_some_and(client::is_uuid) { - require_organization(organization)?; + if !matches!(scope.cluster, Some(Selector::Id(_))) { + require_organization(scope.organization.as_ref())?; } - let cluster = cluster.ok_or_else(|| { - anyhow::anyhow!( - "No cluster specified. Use --cluster, RAWTREE_CLUSTER env, or `rtree cluster use `" - ) - })?; - Ok(client::Scope::new(organization, Some(cluster))) + anyhow::ensure!( + scope.cluster.is_some(), + "No cluster specified. Use --cluster, RAWTREE_CLUSTER env, or `rtree cluster use `" + ); + Ok(scope) } fn main() -> ExitCode { @@ -276,9 +301,8 @@ fn run(cli: Cli) -> Result { ApiClient::new(url.clone(), Some(key)) } else { ApiClient::from_saved_config(url.clone()) - } - .with_saved_ids(saved_ids(cli_org.as_deref(), cli_cluster.as_deref())); - let effective_cluster = resolve_cluster(cli_cluster.clone()); + }; + let selection = Selection::load(cli_org.clone(), cli_cluster.clone()); let login_cluster = resolve_login_cluster(cli_cluster); let result = (|| -> Result { @@ -323,57 +347,40 @@ fn run(cli: Cli) -> Result { } Command::Logout => commands::auth::logout(json), Command::Database { action } => match action { - DatabaseCommand::List => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::database::list( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ) - } + DatabaseCommand::List => commands::database::list(&selection.scoped(&client), json), DatabaseCommand::Create { name, s3_storage } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); + let organization = selection.effective_organization(&client); + let cluster = selection.cluster.as_ref(); commands::database::create( - &client, + &client.with_scope(selection.scope(organization.as_ref(), cluster)), &name, - effective_org.as_deref(), - effective_cluster.as_deref(), + organization.as_ref().map(Choice::name), + cluster.map(Choice::name), s3_storage, json, ) } DatabaseCommand::Use { name } => commands::database::use_database(&name, json), DatabaseCommand::Delete { name } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::database::delete( - &client, - &name, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ) + commands::database::delete(&selection.scoped(&client), &name, json) } }, - Command::FederationIssuer { action } => { - let organization = resolve_explicit_org(cli_org); - commands::federation_issuer::run(&client, organization.as_deref(), action, json) - } + Command::FederationIssuer { action } => commands::federation_issuer::run( + &client, + selection.organization_selector().as_ref(), + action, + json, + ), Command::FederationRule { action } => { - let organization = resolve_explicit_org(cli_org); - commands::federation_rule::run( - &client, - organization.as_deref(), - effective_cluster.as_deref(), - action, - json, - ) + let scope = + selection.scope(selection.organization.as_ref(), selection.cluster.as_ref()); + commands::federation_rule::run(&client.with_scope(scope), action, json) } Command::ServiceAccount { action } => { - let organization = resolve_explicit_org(cli_org); + let organization = selection.organization_selector(); match action { ServiceAccountCommand::List => { - commands::service_account::list(&client, organization.as_deref(), json) + commands::service_account::list(&client, organization.as_ref(), json) } ServiceAccountCommand::Create { name, @@ -381,7 +388,7 @@ fn run(cli: Cli) -> Result { role, } => commands::service_account::create( &client, - organization.as_deref(), + organization.as_ref(), commands::service_account::CreateServiceAccount { name, description, @@ -407,23 +414,24 @@ fn run(cli: Cli) -> Result { } }, Command::Cluster { action } => { - let effective_org = match &action { + let organization = match &action { ClusterCommand::Use { .. } | ClusterCommand::Sizes => None, - _ => resolve_effective_org(&client, cli_org.clone()), + _ => selection.effective_organization(&client), }; + let scoped = client.with_scope(selection.scope(organization.as_ref(), None)); match action { ClusterCommand::Use { name } => commands::cluster::use_cluster( &client, &name, - resolve_explicit_org(cli_org.clone()).as_deref(), + selection.organization.as_ref().map(Choice::name), json, ), - ClusterCommand::List => { - commands::cluster::list(&client, effective_org.as_deref(), json) - } - ClusterCommand::Regions => { - commands::cluster::regions(&client, effective_org.as_deref(), json) - } + ClusterCommand::List => commands::cluster::list( + &scoped, + organization.as_ref().map(Choice::name), + json, + ), + ClusterCommand::Regions => commands::cluster::regions(&scoped, json), ClusterCommand::Sizes => commands::cluster::sizes(&client, json), ClusterCommand::Create { region_id, @@ -435,10 +443,9 @@ fn run(cli: Cli) -> Result { s3_storage, identity, } => commands::cluster::create( - &client, + &scoped, commands::cluster::ClusterCreateOptions { region_id: ®ion_id, - organization: effective_org.as_deref(), name: &name, replicas, min_size, @@ -449,53 +456,35 @@ fn run(cli: Cli) -> Result { }, json, ), - ClusterCommand::Status { name_or_id } => commands::cluster::status( - &client, - &name_or_id, - effective_org.as_deref(), - json, - ), + ClusterCommand::Status { name_or_id } => { + commands::cluster::status(&scoped, &name_or_id, json) + } ClusterCommand::Update { name_or_id, name, idle_timeout_minutes, } => commands::cluster::update( - &client, + &scoped, &name_or_id, - effective_org.as_deref(), name.as_deref(), idle_timeout_minutes, json, ), - ClusterCommand::Stop { name_or_id } => commands::cluster::stop( - &client, - &name_or_id, - effective_org.as_deref(), - json, - ), - ClusterCommand::Resume { name_or_id } => commands::cluster::resume( - &client, - &name_or_id, - effective_org.as_deref(), - json, - ), - ClusterCommand::Delete { name_or_id } => commands::cluster::delete( - &client, - &name_or_id, - effective_org.as_deref(), - json, - ), + ClusterCommand::Stop { name_or_id } => { + commands::cluster::stop(&scoped, &name_or_id, json) + } + ClusterCommand::Resume { name_or_id } => { + commands::cluster::resume(&scoped, &name_or_id, json) + } + ClusterCommand::Delete { name_or_id } => { + commands::cluster::delete(&scoped, &name_or_id, json) + } } } Command::ApiKey { action } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); + let client = selection.scoped(&client); match action { - ApiKeyCommand::List => commands::keys::list( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ), + ApiKeyCommand::List => commands::keys::list(&client, json), ApiKeyCommand::Create { database, name, @@ -506,8 +495,6 @@ fn run(cli: Cli) -> Result { commands::keys::create( &client, database.as_deref(), - effective_org.as_deref(), - effective_cluster.as_deref(), commands::keys::CreateApiKeyRequest { name: &name, permission: &permission, @@ -516,100 +503,71 @@ fn run(cli: Cli) -> Result { json, ) } - ApiKeyCommand::Delete { id } => commands::keys::delete( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - id, - json, - ), + ApiKeyCommand::Delete { id } => commands::keys::delete(&client, id, json), } } Command::Table { action } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); + let client = selection.scoped(&client); match action { TableCommand::List { database } => { - let database = resolve_database(database)?; - commands::table::list( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - json, - ) - } - TableCommand::Describe { database, table } => { - let database = resolve_database(database)?; - commands::table::describe( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &table, - json, - ) + commands::table::list(&client, &resolve_database(database)?, json) } + TableCommand::Describe { database, table } => commands::table::describe( + &client, + &resolve_database(database)?, + &table, + json, + ), TableCommand::Create { database, table, sorting_key, - } => { - let database = resolve_database(database)?; - commands::table::create( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &table, - sorting_key.as_deref(), - json, - ) - } + } => commands::table::create( + &client, + &resolve_database(database)?, + &table, + sorting_key.as_deref(), + json, + ), TableCommand::Update { database, table, sorting_key, - } => { - let database = resolve_database(database)?; - commands::table::update( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &table, - &sorting_key, - json, - ) - } + } => commands::table::update( + &client, + &resolve_database(database)?, + &table, + &sorting_key, + json, + ), } } Command::Integration { action } => match action { - IntegrationCommand::List => { - let organization = resolve_explicit_org(cli_org); - commands::integration::list(&client, organization.as_deref(), json) - } + IntegrationCommand::List => commands::integration::list( + &client, + selection.organization_selector().as_ref(), + json, + ), IntegrationCommand::Add { kind: IntegrationKind::Slack, } => { - let effective_org = resolve_effective_org(&client, cli_org); - let organization = require_organization(effective_org.as_deref())?; + let organization = selection.effective_organization(&client); commands::integration::add_slack( &commands::open::resolve_ui_base_url(&url), - organization, + require_organization(organization.as_ref())?.name(), json, ) } }, Command::Workflow { action } => { - let effective_org = if client.has_api_key()? { - resolve_explicit_org(cli_org.clone()) + let organization = if client.has_api_key()? { + selection.organization.clone() } else { - resolve_effective_org(&client, cli_org.clone()) + selection.effective_organization(&client) }; let scope = require_workflow_scope( &client, - effective_org.as_deref(), - effective_cluster.as_deref(), + selection.scope(organization.as_ref(), selection.cluster.as_ref()), )?; let client = client.with_scope(scope); match action { @@ -729,59 +687,43 @@ fn run(cli: Cli) -> Result { until, start_time, end_time, - } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - commands::logs::logs( - &client, - effective_org.as_deref(), - effective_cluster.as_deref(), - search.as_deref(), - &methods, - &status_codes, - &levels, - &sources, - user_agent.as_deref(), - host.as_deref(), - &paths, - min_duration_ms, - max_duration_ms, - limit, - offset, - since.as_deref(), - until.as_deref(), - start_time.as_deref(), - end_time.as_deref(), - json, - ) - } + } => commands::logs::logs( + &selection.scoped(&client), + search.as_deref(), + &methods, + &status_codes, + &levels, + &sources, + user_agent.as_deref(), + host.as_deref(), + &paths, + min_duration_ms, + max_duration_ms, + limit, + offset, + since.as_deref(), + until.as_deref(), + start_time.as_deref(), + end_time.as_deref(), + json, + ), Command::Query { database, sql_positional, sql, limit, } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); + let client = selection.scoped(&client); let database = resolve_database(database)?; let sql = resolve_sql(sql_positional, sql)?; - commands::query::query( - &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), - &sql, - limit, - json, - ) + commands::query::query(&client, &database, &sql, limit, json) } Command::Format(args) => { let database = resolve_optional_database(args.database); let sql = resolve_sql(args.sql_positional, args.sql)?; - let effective_org = resolve_effective_org(&client, cli_org.clone()); commands::format::format( - &client, + &selection.scoped(&client), database.as_deref(), - effective_org.as_deref(), - effective_cluster.as_deref(), &sql, json, ) @@ -794,14 +736,10 @@ fn run(cli: Cli) -> Result { url, transform, } => { - let effective_org = resolve_effective_org(&client, cli_org.clone()); - let database = resolve_database(database)?; - + let client = selection.scoped(&client); commands::insert::insert( &client, - &database, - effective_org.as_deref(), - effective_cluster.as_deref(), + &resolve_database(database)?, &table, data.as_deref(), file.as_deref(), @@ -817,12 +755,12 @@ fn run(cli: Cli) -> Result { Command::Update => commands::update::update(json), Command::Open { database } => { let ui_base_url = commands::open::resolve_ui_base_url(&url); - let effective_org = resolve_effective_org(&client, cli_org); + let organization = selection.effective_organization(&client); let database = resolve_optional_database(database); commands::open::open( &ui_base_url, - effective_org.as_deref(), - effective_cluster.as_deref(), + organization.as_ref().map(Choice::name), + selection.cluster.as_ref().map(Choice::name), database.as_deref(), json, ) @@ -839,7 +777,7 @@ fn run(cli: Cli) -> Result { }?; Ok(ExitCode::SUCCESS) })(); - result.map_err(|error| explain_rejected_saved_ids(&client, error)) + result.map_err(|error| selection.explain_rejected_saved_ids(error)) } #[cfg(test)] @@ -848,10 +786,10 @@ mod tests { use super::constants::DEFAULT_API_URL; use super::{ - effective_json_mode, resolve_cluster_from_sources, resolve_database_from_sources, - resolve_effective_org_with, resolve_login_cluster_from_sources, resolve_org_from_sources, - resolve_url_from_sources, saved_ids_from_sources, Cli, + effective_json_mode, resolve_database_from_sources, resolve_login_cluster_from_sources, + resolve_url_from_sources, Choice, Cli, Selection, }; + use crate::client::{Scope, Selector}; fn config_with_ids() -> super::config::Config { super::config::Config { @@ -863,36 +801,96 @@ mod tests { } } + fn choice(name: &str, saved_id: Option<&str>) -> Option { + Some(Choice { + name: name.into(), + saved_id: saved_id.map(str::to_owned), + }) + } + + fn select( + cli_org: Option<&str>, + env_org: Option<&str>, + cli_cluster: Option<&str>, + env_cluster: Option<&str>, + cfg: super::config::Config, + ) -> Selection { + Selection::from_sources( + cli_org.map(str::to_owned), + env_org.map(str::to_owned), + cli_cluster.map(str::to_owned), + env_cluster.map(str::to_owned), + cfg, + ) + } + #[test] - fn saved_ids_apply_only_to_config_selections() { - let cfg = config_with_ids(); - let saved = saved_ids_from_sources(None, None, None, None, &cfg); - assert_eq!(saved.organization, Some(("team".into(), "org-id".into()))); - assert_eq!(saved.cluster, Some(("prod".into(), "cluster-id".into()))); + fn flags_win_over_environment_which_wins_over_config() { + let selection = select( + Some("cli"), + Some("env"), + Some("cli"), + Some("env"), + config_with_ids(), + ); + assert_eq!(selection.organization, choice("cli", None)); + assert_eq!(selection.cluster, choice("cli", None)); + + let selection = select(None, Some("env"), None, Some("env"), config_with_ids()); + assert_eq!(selection.organization, choice("env", None)); + assert_eq!(selection.cluster, choice("env", None)); - let saved = saved_ids_from_sources(Some("team"), None, None, Some("prod"), &cfg); - assert!( - saved.organization.is_none(), - "an --org flag is resolved by name" + let selection = select(None, None, None, None, Default::default()); + assert_eq!(selection.organization, None); + assert_eq!(selection.cluster, None); + } + + #[test] + fn saved_ids_apply_only_to_config_selections() { + let selection = select(None, None, None, None, config_with_ids()); + assert_eq!(selection.organization, choice("team", Some("org-id"))); + assert_eq!(selection.cluster, choice("prod", Some("cluster-id"))); + assert!(!selection.used_saved_ids.get()); + assert_eq!( + selection.scope(selection.organization.as_ref(), selection.cluster.as_ref()), + Scope { + organization: Some(Selector::Id("org-id".into())), + cluster: Some(Selector::Id("cluster-id".into())), + } ); - assert!( - saved.cluster.is_none(), + assert!(selection.used_saved_ids.get()); + + let selection = select(None, None, None, Some("prod"), config_with_ids()); + assert_eq!(selection.organization, choice("team", Some("org-id"))); + assert_eq!( + selection.cluster, + choice("prod", None), "RAWTREE_CLUSTER is resolved by name" ); + } - let saved = saved_ids_from_sources(None, Some("team"), Some("prod"), None, &cfg); - assert!(saved.organization.is_none() && saved.cluster.is_none()); + #[test] + fn overriding_the_organization_drops_the_saved_cluster_id() { + for (cli_org, env_org) in [(Some("other"), None), (None, Some("other"))] { + let selection = select(cli_org, env_org, None, None, config_with_ids()); + assert_eq!(selection.organization, choice("other", None)); + assert_eq!(selection.cluster, choice("prod", None)); + } } #[test] - fn configs_without_ids_have_nothing_saved() { + fn configs_without_ids_select_by_name() { let cfg = super::config::Config { default_organization: Some("team".into()), default_cluster: Some("prod".into()), ..Default::default() }; - let saved = saved_ids_from_sources(None, None, None, None, &cfg); - assert!(saved.organization.is_none() && saved.cluster.is_none()); + let selection = select(None, None, None, None, cfg); + assert_eq!( + selection.scope(selection.organization.as_ref(), selection.cluster.as_ref()), + Scope::new(Some("team"), Some("prod")) + ); + assert!(!selection.used_saved_ids.get()); } #[test] @@ -909,32 +907,6 @@ mod tests { } } - #[test] - fn resolve_cluster_uses_cli_first() { - let resolved = resolve_cluster_from_sources( - Some("cli-cluster".to_string()), - Some("env-cluster".to_string()), - Some("cfg-cluster".to_string()), - ); - assert_eq!(resolved.as_deref(), Some("cli-cluster")); - } - - #[test] - fn resolve_cluster_uses_env_when_cli_missing() { - let resolved = resolve_cluster_from_sources( - None, - Some("env-cluster".to_string()), - Some("cfg-cluster".to_string()), - ); - assert_eq!(resolved.as_deref(), Some("env-cluster")); - } - - #[test] - fn resolve_cluster_uses_config_when_cli_and_env_missing() { - let resolved = resolve_cluster_from_sources(None, None, Some("cfg-cluster".to_string())); - assert_eq!(resolved.as_deref(), Some("cfg-cluster")); - } - #[test] fn login_cluster_uses_cli_then_env_without_saved_config() { let cli = resolve_login_cluster_from_sources( @@ -949,58 +921,6 @@ mod tests { assert_eq!(resolve_login_cluster_from_sources(None, None), None); } - #[test] - fn resolve_org_uses_cli_first() { - let resolved = resolve_org_from_sources( - Some("cli-org".to_string()), - Some("env-org".to_string()), - Some("cfg-org".to_string()), - ); - assert_eq!(resolved.as_deref(), Some("cli-org")); - } - - #[test] - fn resolve_org_uses_env_when_cli_missing() { - let resolved = resolve_org_from_sources( - None, - Some("env-org".to_string()), - Some("cfg-org".to_string()), - ); - assert_eq!(resolved.as_deref(), Some("env-org")); - } - - #[test] - fn resolve_org_uses_config_when_cli_and_env_missing() { - let resolved = resolve_org_from_sources(None, None, Some("cfg-org".to_string())); - assert_eq!(resolved.as_deref(), Some("cfg-org")); - } - - #[test] - fn resolve_org_returns_none_when_no_sources() { - let resolved = resolve_org_from_sources(None, None, None); - assert_eq!(resolved, None); - } - - #[test] - fn explicit_org_wins_over_auto_default_fetch() { - let resolved = resolve_effective_org_with(Some("explicit-org".to_string()), || { - Some("fetched-org".to_string()) - }); - assert_eq!(resolved.as_deref(), Some("explicit-org")); - } - - #[test] - fn auto_default_org_is_used_when_explicit_is_missing() { - let resolved = resolve_effective_org_with(None, || Some("fetched-org".to_string())); - assert_eq!(resolved.as_deref(), Some("fetched-org")); - } - - #[test] - fn auto_default_org_can_fall_back_to_none() { - let resolved = resolve_effective_org_with(None, || None); - assert_eq!(resolved, None); - } - #[test] fn resolve_url_uses_cli_first() { let resolved = resolve_url_from_sources( diff --git a/src/org.rs b/src/org.rs index a3536e4..e26ca77 100644 --- a/src/org.rs +++ b/src/org.rs @@ -1,7 +1,7 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; -use crate::client::ApiClient; +use crate::client::{ApiClient, Selector}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OrganizationItem { @@ -49,6 +49,31 @@ pub fn database_path(database: &str, suffix: &str) -> String { ) } +pub fn organization_path(client: &ApiClient, organization: Option<&Selector>) -> Result { + let id = match organization { + Some(Selector::Id(id)) => id.clone(), + Some(Selector::Name(name)) => { + list_organizations(client)? + .into_iter() + .find(|item| item.name == *name) + .with_context(|| { + format!("Organization '{name}' was not found. Run `rtree organization list`.") + })? + .organization_id + } + None => { + list_organizations(client)? + .into_iter() + .next() + .context( + "No organization available. Run `rtree organization list` or select one with --org.", + )? + .organization_id + } + }; + Ok(format!("/v1/organizations/{}", urlencoding::encode(&id))) +} + #[cfg(test)] mod tests { use super::database_path; @@ -77,37 +102,3 @@ mod tests { ); } } - -#[derive(Deserialize)] -struct Organization { - organization_id: String, - name: String, -} - -#[derive(Deserialize)] -struct OrganizationsResponse { - organizations: Vec, -} - -pub fn organization_path(client: &ApiClient, organization: Option<&str>) -> Result { - if let Some(id) = organization.and_then(|name| client.saved_organization_id(name)) { - return Ok(format!("/v1/organizations/{}", urlencoding::encode(&id))); - } - let response: OrganizationsResponse = client.get("/v1/organizations")?; - let selected = match organization { - Some(name) => response - .organizations - .into_iter() - .find(|item| item.name == name || item.organization_id == name) - .with_context(|| { - format!("Organization '{name}' was not found. Run `rtree organization list`.") - })?, - None => response.organizations.into_iter().next().context( - "No organization available. Run `rtree organization list` or select one with --org.", - )?, - }; - Ok(format!( - "/v1/organizations/{}", - urlencoding::encode(&selected.organization_id) - )) -} From 875a30875ab8697f58dddfdd2f630a080c3f067f Mon Sep 17 00:00:00 2001 From: jordiori Date: Thu, 26 Nov 2026 11:38:46 +0100 Subject: [PATCH 6/7] Show the saved-ID refresh hint only when the saved IDs are rejected The hint was added to any 403 or 404 after a command used saved IDs, so a missing table or a non-admin API key was reported as a stale ID. Server errors now carry their status, and on a refusal the CLI checks whether the credential can still see the saved organization and cluster before adding the hint. --- src/client.rs | 42 +++++++++++++----- src/client/routing.rs | 38 +++++++++++++++- src/client/routing_tests.rs | 28 ++++++++++++ src/main.rs | 44 +++++++++++++------ tests/api_contracts.rs | 88 +++++++++++++++++++++++++++++++------ 5 files changed, 202 insertions(+), 38 deletions(-) diff --git a/src/client.rs b/src/client.rs index 496c358..1b022b1 100644 --- a/src/client.rs +++ b/src/client.rs @@ -347,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::(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::(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)] diff --git a/src/client/routing.rs b/src/client/routing.rs index 1ec5cd0..3674669 100644 --- a/src/client/routing.rs +++ b/src/client/routing.rs @@ -1,5 +1,5 @@ use super::{ - discovery::UnavailableRegion, handle_response, ApiClient, Selector, CLUSTER_ID_HEADER, + discovery::UnavailableRegion, handle_response, ApiClient, Scope, Selector, CLUSTER_ID_HEADER, ORGANIZATION_ID_HEADER, }; use anyhow::{Context, Result}; @@ -410,6 +410,42 @@ impl ApiClient { } } + /// Whether this credential can still see the scope's organization and + /// cluster. Fails when that cannot be told, such as during a regional outage. + pub fn can_access(&self, scope: &Scope) -> Result { + let organization = match &scope.organization { + Some(selector) => { + let found = self + .organizations(None)? + .into_iter() + .find(|item| match selector { + Selector::Id(id) => item.organization_id == *id, + Selector::Name(name) => item.name == *name, + }); + let Some(organization) = found else { + return Ok(false); + }; + Some(organization) + } + None => None, + }; + let Some(Selector::Id(cluster_id)) = &scope.cluster else { + return Ok(true); + }; + if !self.has_user_credential()? { + return Ok(self.bound_cluster(None)?.id == *cluster_id); + } + let organization = + organization.context("A cluster ID is checked within its organization.")?; + let clusters = self.organization_clusters(&organization, None)?; + let found = clusters.clusters.iter().any(|item| item.id == *cluster_id); + anyhow::ensure!( + found || clusters.unavailable_regions.is_empty(), + "Some regions are unavailable." + ); + Ok(found) + } + /// The organization and cluster IDs this client's scope resolves to, for /// saving in the config. pub fn resolve_scope_ids(&self) -> Result<(Option, Option)> { diff --git a/src/client/routing_tests.rs b/src/client/routing_tests.rs index c97cc8a..9694912 100644 --- a/src/client/routing_tests.rs +++ b/src/client/routing_tests.rs @@ -939,3 +939,31 @@ fn id_selectors_skip_the_organization_listing_but_keep_regional_routing() { assert_eq!(requests[2].headers["x-rawtree-cluster-id"], CLUSTER); assert_eq!(requests[2].headers["x-rawtree-deployment-id"], "12abcdef"); } + +#[test] +fn user_credentials_check_saved_ids_against_the_listing_and_cached_discovery() { + let (base, server) = server(vec![ + ( + "200 OK", + json!({"organizations":[{"organization_id":ORG,"name":"acme","role":null}]}), + ), + ( + "200 OK", + json!({"regions":[{"id":"legacy","name":"Virginia","cloud_region":"us-east-1","deployment_id":null,"enabled":true,"organization_id":null}]}), + ), + ( + "200 OK", + json!({"clusters":[{"id":CLUSTER,"name":"production"}]}), + ), + ]); + let client = ApiClient::new(base, Some("session.fixture".to_string())); + let scope = |organization: &str, cluster: &str| Scope { + organization: Some(Selector::Id(organization.into())), + cluster: Some(Selector::Id(cluster.into())), + }; + const GONE: &str = "00000000-0000-4000-8000-000000000009"; + assert!(client.can_access(&scope(ORG, CLUSTER)).unwrap()); + assert!(!client.can_access(&scope(ORG, GONE)).unwrap()); + assert!(!client.can_access(&scope(GONE, CLUSTER)).unwrap()); + assert_eq!(server.join().unwrap().len(), 3); +} diff --git a/src/main.rs b/src/main.rs index dc1a31c..8ebf6c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,7 +22,7 @@ use cli::{ IntegrationKind, OrganizationCommand, ServiceAccountCommand, ShellType, TableCommand, WorkflowCommand, WorkflowSinkCommand, }; -use client::{ApiClient, Scope, Selector}; +use client::{ApiClient, Scope, Selector, ServerError}; use constants::DEFAULT_API_URL; fn resolve_url_from_sources( @@ -187,18 +187,36 @@ impl Selection { client.with_scope(self.scope(organization.as_ref(), self.cluster.as_ref())) } - fn explain_rejected_saved_ids(&self, error: anyhow::Error) -> anyhow::Error { - let message = format!("{error:#}"); - if self.used_saved_ids.get() - && error.downcast_ref::().is_none() - && (message.contains("(403)") || message.contains("(404)")) - { - anyhow::anyhow!( - "{message}\nThe saved organization or cluster ID was rejected; it may have been deleted or your access may have changed. Run `rtree organization use ` and `rtree cluster use `, or `rtree login` again." - ) - } else { - error + /// A rejected saved ID is never replaced by a name lookup, so when the + /// server refuses a command that used one, check whether the ID is still + /// visible and say how to refresh it if not. + fn explain_rejected_saved_ids( + &self, + client: &ApiClient, + error: anyhow::Error, + ) -> anyhow::Error { + let refused = + ServerError::of(&error).is_some_and(|error| (400..500).contains(&error.status)); + if !(self.used_saved_ids.get() && refused) { + return error; } + let saved = Scope { + organization: self + .organization + .as_ref() + .map(|choice| self.selector(choice)), + cluster: self + .cluster + .as_ref() + .and_then(|choice| choice.saved_id.clone()) + .map(Selector::Id), + }; + if !matches!(client.can_access(&saved), Ok(false)) { + return error; + } + anyhow::anyhow!( + "{error:#}\nThe saved organization or cluster ID was rejected; it may have been deleted or your access may have changed. Run `rtree organization use ` and `rtree cluster use `, or `rtree login` again." + ) } } @@ -777,7 +795,7 @@ fn run(cli: Cli) -> Result { }?; Ok(ExitCode::SUCCESS) })(); - result.map_err(|error| selection.explain_rejected_saved_ids(error)) + result.map_err(|error| selection.explain_rejected_saved_ids(&client, error)) } #[cfg(test)] diff --git a/tests/api_contracts.rs b/tests/api_contracts.rs index dbff1da..4a78f40 100644 --- a/tests/api_contracts.rs +++ b/tests/api_contracts.rs @@ -1004,22 +1004,82 @@ fn an_org_flag_ignores_both_saved_ids_and_resolves_by_name() { ); } +const REFRESH_HINT: &str = "saved organization or cluster ID was rejected"; + +fn cluster_not_found() -> (String, &'static str, Value) { + ( + "GET /v1/databases".to_string(), + "404 Not Found", + json!({"message": "Cluster not found."}), + ) +} + #[test] -fn a_rejected_saved_id_fails_with_a_refresh_hint_and_never_falls_back_to_names() { - let (output, saved, _) = common::run_cli( - &[( - "GET /v1/databases".to_string(), - "404 Not Found", - json!({"message": "Cluster not found."}), - )], - &["--json", "database", "list"], - &config_with_saved_ids(), +fn a_saved_id_the_credential_can_no_longer_see_fails_with_a_refresh_hint() { + let other_organization = ( + "GET /v1/organizations".to_string(), + "200 OK", + json!({"organizations": [{"organization_id": "00000000-0000-4000-8000-000000000002", "name": "other", "role": null}]}), ); - assert_eq!(output.status.code(), Some(4)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("saved organization or cluster ID was rejected")); - assert!(stderr.contains("rtree organization use")); - assert_eq!(saved, config_with_saved_ids()); + let other_cluster = ( + "GET /v1/clusters".to_string(), + "200 OK", + json!({"clusters": [{"id": "00000000-0000-4000-8000-0000000000c2", "name": "other"}]}), + ); + for responses in [ + vec![cluster_not_found(), other_organization], + vec![ + cluster_not_found(), + common::key_organization("team"), + other_cluster, + ], + ] { + let (output, saved, _) = common::run_cli( + &responses, + &["--json", "database", "list"], + &config_with_saved_ids(), + ); + assert_eq!(output.status.code(), Some(4)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains(REFRESH_HINT), "{stderr}"); + assert!(stderr.contains("rtree organization use")); + assert_eq!(saved, config_with_saved_ids()); + } +} + +#[test] +fn other_refusals_with_valid_saved_ids_get_no_refresh_hint() { + for (args, refusal) in [ + ( + vec!["--json", "table", "describe", "--database", "db", "missing"], + ( + "GET /v1/tables/missing?database=db".to_string(), + "404 Not Found", + json!({"message": "Table not found."}), + ), + ), + ( + vec!["--json", "workflow", "list"], + ( + "GET /v1/workflows".to_string(), + "403 Forbidden", + json!({"message": "Forbidden", "hint": "Workflow API access requires an admin API key."}), + ), + ), + ] { + let (output, _, _) = common::run_cli( + &[ + refusal, + common::key_organization("team"), + common::bound_cluster("prod"), + ], + &args, + &config_with_saved_ids(), + ); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains(REFRESH_HINT), "{stderr}"); + } } #[test] From 7a4260658ed8830ad0e41866f0b45a5c88715bb5 Mon Sep 17 00:00:00 2001 From: jordiori Date: Thu, 26 Nov 2026 12:04:07 +0100 Subject: [PATCH 7/7] Check rejected saved IDs against the effective organization --- src/main.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8ebf6c0..6e04547 100644 --- a/src/main.rs +++ b/src/main.rs @@ -200,11 +200,9 @@ impl Selection { if !(self.used_saved_ids.get() && refused) { return error; } + let organization = self.effective_organization(client); let saved = Scope { - organization: self - .organization - .as_ref() - .map(|choice| self.selector(choice)), + organization: organization.as_ref().map(|choice| self.selector(choice)), cluster: self .cluster .as_ref()