Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Move the CLI onto the core HTTP client

Manav Rathiac1e243dcfe2
diff --git a/rust/apps/cli/src/api/auth.rs b/rust/apps/cli/src/api/auth.rs
deleted file mode 100644
index 4c75b06278..0000000000
--- a/rust/apps/cli/src/api/auth.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use crate::{
- api::{ApiClient, client::USER_AGENT, models::*},
- models::error::{Error, Result},
-};
-use ente_accounts::{AccountsClient, AccountsClientConfig};
-use ente_core::crypto::SecretVec;
-use serde::{Serialize, de::DeserializeOwned};
-use uuid::Uuid;
-
-fn convert<T, U>(value: T) -> Result<U>
-where
- T: Serialize,
- U: DeserializeOwned,
-{
- serde_json::from_value(serde_json::to_value(value)?).map_err(Error::from)
-}
-
-fn shared_client(api: &ApiClient, account_id: Option<&str>) -> Result<AccountsClient> {
- let mut config = AccountsClientConfig::new(api.client_package())
- .with_base_url(api.base_url().to_string())
- .with_user_agent(USER_AGENT);
- if let Some(token) = account_id.and_then(|id| api.get_token(id)) {
- config = config.with_auth_token(token);
- }
- AccountsClient::new(config).map_err(Error::from)
-}
-
-/// Compatibility wrapper over `ente_accounts::AccountsClient`.
-pub struct AuthClient<'a> {
- api: &'a ApiClient,
-}
-
-impl<'a> AuthClient<'a> {
- pub fn new(api: &'a ApiClient) -> Self {
- Self { api }
- }
-
- pub async fn get_srp_attributes(&self, email: &str) -> Result<SrpAttributes> {
- let client = shared_client(self.api, None)?;
- convert(client.get_srp_attributes(email).await?)
- }
-
- pub async fn create_srp_session(
- &self,
- srp_user_id: &Uuid,
- client_public: &[u8],
- ) -> Result<CreateSrpSessionResponse> {
- let client = shared_client(self.api, None)?;
- convert(
- client
- .create_srp_session(srp_user_id, client_public)
- .await?,
- )
- }
-
- pub async fn verify_srp_session(
- &self,
- srp_user_id: &Uuid,
- session_id: &Uuid,
- client_proof: &[u8],
- ) -> Result<AuthResponse> {
- let client = shared_client(self.api, None)?;
- convert(
- client
- .verify_srp_session(srp_user_id, session_id, client_proof)
- .await?,
- )
- }
-
- pub async fn login_with_srp(
- &self,
- email: &str,
- password: &str,
- ) -> Result<(AuthResponse, SecretVec)> {
- let client = shared_client(self.api, None)?;
- let (response, kek) = client.login_with_srp(email, password).await?;
- Ok((convert(response)?, kek))
- }
-
- pub async fn send_otp(&self, email: &str, purpose: &str) -> Result<()> {
- let client = shared_client(self.api, None)?;
- client.send_otp(email, purpose).await.map_err(Error::from)
- }
-
- pub async fn verify_email(
- &self,
- email: &str,
- otp: &str,
- source: Option<&str>,
- ) -> Result<AuthResponse> {
- let client = shared_client(self.api, None)?;
- convert(client.verify_email(email, otp, source).await?)
- }
-
- pub async fn set_user_key_attributes(
- &self,
- account_id: &str,
- key_attributes: KeyAttributes,
- ) -> Result<()> {
- let client = shared_client(self.api, Some(account_id))?;
- client
- .set_user_key_attributes(convert(key_attributes)?)
- .await
- .map_err(Error::from)
- }
-
- pub async fn setup_srp(
- &self,
- account_id: &str,
- request: &SetupSrpRequest,
- ) -> Result<SetupSrpResponse> {
- let client = shared_client(self.api, Some(account_id))?;
- let request = ente_accounts::models::SetupSrpRequest {
- srp_user_id: request.srp_user_id.clone(),
- srp_salt: request.srp_salt.clone(),
- srp_verifier: request.srp_verifier.clone(),
- srp_a: request.srp_a.clone(),
- };
- convert(client.setup_srp(&request).await?)
- }
-
- pub async fn complete_srp_setup(
- &self,
- account_id: &str,
- setup_id: &Uuid,
- srp_m1: &str,
- ) -> Result<CompleteSrpSetupResponse> {
- let client = shared_client(self.api, Some(account_id))?;
- convert(client.complete_srp_setup(setup_id, srp_m1).await?)
- }
-
- pub async fn verify_totp(&self, session_id: &str, code: &str) -> Result<AuthResponse> {
- let client = shared_client(self.api, None)?;
- convert(client.verify_totp(session_id, code).await?)
- }
-
- pub async fn check_passkey_status(&self, session_id: &str) -> Result<AuthResponse> {
- let client = shared_client(self.api, None)?;
- convert(client.check_passkey_status(session_id).await?)
- }
-
- pub async fn get_session_validity(&self, account_id: &str) -> Result<SessionValidityResponse> {
- let client = shared_client(self.api, Some(account_id))?;
- convert(client.get_session_validity().await?)
- }
-
- pub async fn setup_two_factor(&self, account_id: &str) -> Result<TwoFactorSecret> {
- let client = shared_client(self.api, Some(account_id))?;
- convert(client.setup_two_factor().await?)
- }
-
- pub async fn enable_two_factor(
- &self,
- account_id: &str,
- request: &EnableTwoFactorRequest,
- ) -> Result<()> {
- let client = shared_client(self.api, Some(account_id))?;
- let request = ente_accounts::models::EnableTwoFactorRequest {
- code: request.code.clone(),
- encrypted_two_factor_secret: request.encrypted_two_factor_secret.clone(),
- two_factor_secret_decryption_nonce: request.two_factor_secret_decryption_nonce.clone(),
- };
- client
- .enable_two_factor(&request)
- .await
- .map_err(Error::from)
- }
-}
diff --git a/rust/apps/cli/src/api/client.rs b/rust/apps/cli/src/api/client.rs
index 22c790f2f7..fac27bfd99 100644
--- a/rust/apps/cli/src/api/client.rs
+++ b/rust/apps/cli/src/api/client.rs
@@ -1,76 +1,19 @@
-#![allow(dead_code)]
-
-use crate::api::retry::RetryConfig;
-use crate::models::error::{Error, Result};
+use crate::models::error::Result;
+use ente_core::http::{self, Api, ApiConfig, Auth, Http, RetryProfile};
use ente_core::urls::PRODUCTION_API_BASE_URL;
-use reqwest::{Client, RequestBuilder, Response, StatusCode};
-use serde::{Deserialize, Serialize};
+use serde::Serialize;
+use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
-use std::time::Duration;
-use tokio::time::sleep;
-const TOKEN_HEADER: &str = "X-Auth-Token";
-const CLIENT_PKG_HEADER: &str = "X-Client-Package";
const DEFAULT_CLIENT_PACKAGE: &str = "io.ente.photos";
pub(crate) const USER_AGENT: &str = concat!("ente-rs/", env!("CARGO_PKG_VERSION"));
-/// Maximum number of retry attempts for failed requests
-const MAX_RETRIES: u32 = 3;
-/// Initial retry delay in milliseconds
-const INITIAL_RETRY_DELAY_MS: u64 = 1000;
-/// Maximum retry delay in milliseconds
-const MAX_RETRY_DELAY_MS: u64 = 20000;
-
-#[derive(Debug, Deserialize)]
-pub struct ApiError {
- pub code: Option<String>,
- pub message: Option<String>,
-}
-
-fn make_api_error(method: &str, path: &str, status: StatusCode, body: String) -> Error {
- if status.is_server_error() {
- log::error!("API request failed: status={status}");
- } else if status == StatusCode::TOO_MANY_REQUESTS {
- log::warn!("API request failed: status={status}");
- } else {
- log::debug!("API request failed: status={status}");
- }
-
- log::debug!("API request: {method} {path}");
-
- if let Ok(error_json) = serde_json::from_str::<serde_json::Value>(&body) {
- log::debug!(
- "API error body: {}",
- serde_json::to_string_pretty(&error_json).unwrap_or(body.clone())
- );
- } else {
- log::debug!("API error body: {body}");
- }
-
- let message = serde_json::from_str::<ApiError>(&body)
- .ok()
- .and_then(|e| e.code.or(e.message))
- .unwrap_or_else(|| status.to_string());
-
- Error::ApiError {
- status: status.as_u16(),
- code: serde_json::from_str::<ApiError>(&body)
- .ok()
- .and_then(|e| e.code),
- message,
- }
-}
-
pub struct ApiClient {
- client: Client,
- download_client: Client,
+ http: Http,
pub(crate) base_url: String,
client_package: String,
- /// Token storage for multi-account support: account_id -> token
tokens: Arc<RwLock<HashMap<String, String>>>,
- /// Retry configuration
- retry_config: RetryConfig,
}
impl ApiClient {
@@ -82,304 +25,171 @@ impl ApiClient {
where
S: Into<String>,
{
- let client = Client::builder()
- .timeout(Duration::from_secs(30))
- .user_agent(USER_AGENT)
- .build()?;
-
- let download_client = Client::builder()
- .timeout(Duration::from_secs(300))
- .pool_idle_timeout(Duration::from_secs(90))
- .pool_max_idle_per_host(10)
- .user_agent(USER_AGENT)
- .build()?;
-
Ok(Self {
- client,
- download_client,
+ http: Http::new()?,
base_url: base_url.unwrap_or_else(|| PRODUCTION_API_BASE_URL.to_string()),
client_package: client_package.into(),
tokens: Arc::new(RwLock::new(HashMap::new())),
- retry_config: RetryConfig::default(),
})
}
- /// Add or update authentication token for an account
pub fn add_token(&self, account_id: &str, token: &str) {
let mut tokens = self.tokens.write().unwrap();
tokens.insert(account_id.to_string(), token.to_string());
}
- /// Remove authentication token for an account
pub fn remove_token(&self, account_id: &str) {
let mut tokens = self.tokens.write().unwrap();
tokens.remove(account_id);
}
- /// Get authentication token for an account
pub fn get_token(&self, account_id: &str) -> Option<String> {
let tokens = self.tokens.read().unwrap();
tokens.get(account_id).cloned()
}
- /// Set retry configuration
- pub fn set_retry_config(&mut self, config: RetryConfig) {
- self.retry_config = config;
- }
-
- /// Return the configured base URL.
pub fn base_url(&self) -> &str {
&self.base_url
}
- /// Return the configured client package.
pub fn client_package(&self) -> &str {
&self.client_package
}
- /// Build a request with common headers
- fn build_request(&self, builder: RequestBuilder, account_id: Option<&str>) -> RequestBuilder {
- let mut req = builder.header(CLIENT_PKG_HEADER, &self.client_package);
-
- if let Some(id) = account_id {
- if let Some(token) = self.get_token(id) {
- log::debug!("Adding auth token for account {id}");
- req = req.header(TOKEN_HEADER, token);
- } else {
+ fn api(&self, account_id: Option<&str>) -> Api {
+ let auth = account_id.and_then(|id| {
+ let token = self.get_token(id);
+ if token.is_none() {
log::warn!("No token found for account {id}");
}
- }
-
- req
- }
-
- /// Execute request with retry logic
- async fn execute_with_retry(&self, request_builder: RequestBuilder) -> Result<Response> {
- let mut retry_count = 0;
- let mut delay_ms = INITIAL_RETRY_DELAY_MS;
-
- loop {
- let req = request_builder
- .try_clone()
- .ok_or_else(|| Error::Generic("Failed to clone request for retry".to_string()))?;
-
- match req.send().await {
- Ok(response) => {
- if (response.status() == StatusCode::TOO_MANY_REQUESTS
- || response.status().is_server_error())
- && retry_count < MAX_RETRIES
- {
- retry_count += 1;
- log::warn!(
- "Request failed with status {}, retry attempt {}/{}",
- response.status(),
- retry_count,
- MAX_RETRIES
- );
-
- sleep(Duration::from_millis(delay_ms)).await;
- delay_ms = (delay_ms * 2).min(MAX_RETRY_DELAY_MS);
- continue;
- }
-
- return Ok(response);
- }
- Err(e) => {
- if retry_count < MAX_RETRIES {
- retry_count += 1;
- log::warn!(
- "Request failed with error: {e}, retry attempt {retry_count}/{MAX_RETRIES}"
- );
-
- sleep(Duration::from_millis(delay_ms)).await;
- delay_ms = (delay_ms * 2).min(MAX_RETRY_DELAY_MS);
- continue;
- }
- return Err(e.into());
- }
- }
- }
- }
-
- /// Make a GET request
- pub async fn get<T>(&self, path: &str, account_id: Option<&str>) -> Result<T>
- where
- T: for<'de> Deserialize<'de>,
- {
- let url = format!("{}{}", self.base_url, path);
- let request = self.client.get(&url);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
+ token.map(Auth::User)
+ });
+ Api::new(
+ self.http.clone(),
+ ApiConfig {
+ origin: self.base_url.clone(),
+ client_package: Some(self.client_package.clone()),
+ client_version: None,
+ user_agent: Some(USER_AGENT.to_string()),
+ auth,
+ },
+ )
+ }
+
+ pub async fn get<T: DeserializeOwned>(
+ &self,
+ path: &str,
+ account_id: Option<&str>,
+ ) -> Result<T> {
+ let api = self.api(account_id);
+ Ok(http::retry(|| async {
+ api.get(path)
+ .send()
+ .await?
+ .error_for_code()
+ .await?
+ .json()
.await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("GET", path, status, body));
- }
-
- let text = response.text().await?;
- serde_json::from_str(&text).map_err(|e| {
- log::error!("Failed to deserialize response: {e}");
- log::debug!(
- "Response text (first 1000 chars): {}",
- &text[..1000.min(text.len())]
- );
- Error::Generic(format!("Deserialization failed: {e}"))
})
+ .await?)
}
- /// Make a POST request
pub async fn post<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>
where
- T: for<'de> Deserialize<'de>,
+ T: DeserializeOwned,
B: Serialize,
{
- let url = format!("{}{}", self.base_url, path);
-
- let request = self.client.post(&url).json(body);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
+ let api = self.api(account_id);
+ Ok(http::retry(|| async {
+ api.post(path)
+ .json(body)
+ .send()
+ .await?
+ .error_for_code()
+ .await?
+ .json()
.await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("POST", path, status, body));
- }
-
- let text = response.text().await?;
- serde_json::from_str(&text).map_err(|e| {
- log::error!("Failed to deserialize response: {e}");
- log::debug!(
- "Response text (first 1000 chars): {}",
- &text[..1000.min(text.len())]
- );
- Error::Generic(format!("Deserialization failed: {e}"))
})
+ .await?)
}
- /// Make a POST request that expects no response body
pub async fn post_empty<B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<()>
where
B: Serialize,
{
- let url = format!("{}{}", self.base_url, path);
-
- let request = self.client.post(&url).json(body);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
- .await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("POST", path, status, body));
- }
-
+ let api = self.api(account_id);
+ http::retry(|| async {
+ api.post(path)
+ .json(body)
+ .send()
+ .await?
+ .error_for_code()
+ .await?;
+ Ok(())
+ })
+ .await?;
Ok(())
}
- /// Make a PUT request
pub async fn put<T, B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<T>
where
- T: for<'de> Deserialize<'de>,
+ T: DeserializeOwned,
B: Serialize,
{
- let url = format!("{}{}", self.base_url, path);
- let request = self.client.put(&url).json(body);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
+ let api = self.api(account_id);
+ Ok(http::retry(|| async {
+ api.put(path)
+ .json(body)
+ .send()
+ .await?
+ .error_for_code()
+ .await?
+ .json()
.await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("PUT", path, status, body));
- }
-
- let text = response.text().await?;
- serde_json::from_str(&text).map_err(|e| {
- log::error!("Failed to deserialize response: {e}");
- log::debug!(
- "Response text (first 1000 chars): {}",
- &text[..1000.min(text.len())]
- );
- Error::Generic(format!("Deserialization failed: {e}"))
})
+ .await?)
}
- /// Make a PUT request that expects no response body
pub async fn put_empty<B>(&self, path: &str, body: &B, account_id: Option<&str>) -> Result<()>
where
B: Serialize,
{
- let url = format!("{}{}", self.base_url, path);
- let request = self.client.put(&url).json(body);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
- .await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("PUT", path, status, body));
- }
-
+ let api = self.api(account_id);
+ http::retry(|| async {
+ api.put(path)
+ .json(body)
+ .send()
+ .await?
+ .error_for_code()
+ .await?;
+ Ok(())
+ })
+ .await?;
Ok(())
}
- /// Make a DELETE request
pub async fn delete(&self, path: &str, account_id: Option<&str>) -> Result<()> {
- let url = format!("{}{}", self.base_url, path);
- let request = self.client.delete(&url);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
- .await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("DELETE", path, status, body));
- }
-
+ let api = self.api(account_id);
+ http::retry(|| async {
+ api.delete(path).send().await?.error_for_code().await?;
+ Ok(())
+ })
+ .await?;
Ok(())
}
- /// Download a file with the download client
pub async fn download_file(&self, url: &str, account_id: Option<&str>) -> Result<Vec<u8>> {
- let request = self.download_client.get(url);
- let request = self.build_request(request, account_id);
-
- let response = self.execute_with_retry(request).await?;
-
- if !response.status().is_success() {
- let status = response.status();
- let body = response
- .text()
- .await
- .unwrap_or_else(|_| "Unknown error".to_string());
- return Err(make_api_error("GET", url, status, body));
- }
-
- Ok(response.bytes().await?.to_vec())
+ let token = account_id.and_then(|id| self.get_token(id));
+ Ok(
+ http::retry_with_profile(RetryProfile::Background, || async {
+ let mut request = self.http.get(url);
+ if let Some(token) = &token {
+ // A header would ride the redirect to presigned storage; a query does not.
+ request = request.query(&[("token", token)]);
+ }
+ request.send().await?.error_for_status()?.bytes().await
+ })
+ .await?,
+ )
}
}
diff --git a/rust/apps/cli/src/api/methods.rs b/rust/apps/cli/src/api/methods.rs
index a90dc6baca..b2f52fde1a 100644
--- a/rust/apps/cli/src/api/methods.rs
+++ b/rust/apps/cli/src/api/methods.rs
@@ -6,7 +6,6 @@ use crate::api::models::{
use crate::models::error::Result;
use ente_core::urls::file_download_url;
-/// API methods for interacting with Ente services
pub struct ApiMethods<'a> {
api: &'a ApiClient,
}
@@ -18,18 +17,12 @@ impl<'a> ApiMethods<'a> {
// ========== User Methods ==========
- /// Get user details including subscription and storage info
pub async fn get_user_details(&self, account_id: &str) -> Result<UserDetails> {
self.api.get("/users/details", Some(account_id)).await
}
// ========== Collection Methods ==========
- /// Get all collections (albums) for the authenticated user
- ///
- /// # Arguments
- /// * `account_id` - The account identifier for authentication
- /// * `since_time` - Unix timestamp in microseconds to get collections modified after this time (0 for all)
pub async fn get_collections(
&self,
account_id: &str,
@@ -40,7 +33,6 @@ impl<'a> ApiMethods<'a> {
Ok(response.collections)
}
- /// Get a specific collection by ID
pub async fn get_collection(&self, account_id: &str, collection_id: i64) -> Result<Collection> {
let url = format!("/collections/{collection_id}");
self.api.get(&url, Some(account_id)).await
@@ -48,15 +40,6 @@ impl<'a> ApiMethods<'a> {
// ========== File Methods ==========
- /// Get files from a specific collection with pagination
- ///
- /// # Arguments
- /// * `account_id` - The account identifier for authentication
- /// * `collection_id` - The collection ID to fetch files from
- /// * `since_time` - Unix timestamp in microseconds to get files modified after this time
- ///
- /// # Returns
- /// A tuple of (files, has_more) where has_more indicates if there are more files to fetch
pub async fn get_collection_files(
&self,
account_id: &str,
@@ -69,7 +52,6 @@ impl<'a> ApiMethods<'a> {
Ok((response.diff, response.has_more))
}
- /// Get a specific file by ID
pub async fn get_file(
&self,
account_id: &str,
@@ -81,15 +63,6 @@ impl<'a> ApiMethods<'a> {
Ok(response.file)
}
- /// Get all files across all collections (for incremental sync)
- ///
- /// # Arguments
- /// * `account_id` - The account identifier for authentication
- /// * `since_time` - Unix timestamp in microseconds to get files modified after this time
- /// * `limit` - Maximum number of files to return (typically 500)
- ///
- /// # Returns
- /// A tuple of (files, has_more) where has_more indicates if there are more files to fetch
pub async fn get_diff(
&self,
account_id: &str,
@@ -101,25 +74,21 @@ impl<'a> ApiMethods<'a> {
Ok((response.diff, response.has_more))
}
- /// Get download URL for a file
pub async fn get_file_url(&self, _account_id: &str, file_id: i64) -> Result<String> {
Ok(file_download_url(&self.api.base_url, file_id))
}
- /// Get thumbnail URL for a file
pub async fn get_thumbnail_url(&self, account_id: &str, file_id: i64) -> Result<String> {
let url = format!("/files/preview/{file_id}");
let response: GetThumbnailUrlResponse = self.api.get(&url, Some(account_id)).await?;
Ok(response.url)
}
- /// Download file content
pub async fn download_file(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {
let url = self.get_file_url(account_id, file_id).await?;
self.api.download_file(&url, Some(account_id)).await
}
- /// Download thumbnail content
pub async fn download_thumbnail(&self, account_id: &str, file_id: i64) -> Result<Vec<u8>> {
let url = self.get_thumbnail_url(account_id, file_id).await?;
self.api.download_file(&url, Some(account_id)).await
@@ -127,14 +96,12 @@ impl<'a> ApiMethods<'a> {
// ========== Trash Methods ==========
- /// Get deleted files
pub async fn get_trash(&self, account_id: &str, since_time: i64) -> Result<(Vec<File>, bool)> {
let url = format!("/trash/v2?sinceTime={since_time}");
let response: GetDiffResponse = self.api.get(&url, Some(account_id)).await?;
Ok((response.diff, response.has_more))
}
- /// Permanently delete files from trash
pub async fn delete_from_trash(&self, account_id: &str, file_ids: &[i64]) -> Result<()> {
let body = serde_json::json!({
"fileIDs": file_ids
@@ -146,7 +113,6 @@ impl<'a> ApiMethods<'a> {
Ok(())
}
- /// Empty all trash
pub async fn empty_trash(&self, account_id: &str) -> Result<()> {
self.api.delete("/trash/empty", Some(account_id)).await
}
diff --git a/rust/apps/cli/src/api/mod.rs b/rust/apps/cli/src/api/mod.rs
index 6026f0ae7f..83308175bb 100644
--- a/rust/apps/cli/src/api/mod.rs
+++ b/rust/apps/cli/src/api/mod.rs
@@ -1,10 +1,7 @@
-pub mod auth;
pub mod client;
pub mod methods;
pub mod models;
-pub mod retry;
-pub use auth::AuthClient;
pub use client::ApiClient;
pub use methods::ApiMethods;
pub use models::*;
diff --git a/rust/apps/cli/src/api/retry.rs b/rust/apps/cli/src/api/retry.rs
deleted file mode 100644
index 2a40add9ed..0000000000
--- a/rust/apps/cli/src/api/retry.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-use crate::Result;
-use reqwest::{Response, StatusCode};
-use std::time::Duration;
-use tokio::time::sleep;
-
-/// Retry configuration
-pub struct RetryConfig {
- pub max_retries: u32,
- pub initial_delay: Duration,
- pub max_delay: Duration,
- pub exponential_base: f64,
-}
-
-impl Default for RetryConfig {
- fn default() -> Self {
- Self {
- max_retries: 3,
- initial_delay: Duration::from_millis(500),
- max_delay: Duration::from_secs(30),
- exponential_base: 2.0,
- }
- }
-}
-
-/// Execute a request with retry logic
-pub async fn with_retry<F, Fut>(config: &RetryConfig, mut operation: F) -> Result<Response>
-where
- F: FnMut() -> Fut,
- Fut: std::future::Future<Output = Result<Response>>,
-{
- let mut attempt = 0;
- let mut delay = config.initial_delay;
-
- loop {
- match operation().await {
- Ok(response) => {
- // Check if we should retry based on status code
- let status = response.status();
-
- if status.is_success() {
- return Ok(response);
- }
-
- // Don't retry on client errors (except 429)
- if status.is_client_error() && status != StatusCode::TOO_MANY_REQUESTS {
- return Ok(response);
- }
-
- // Retry on 429 (rate limited) or 5xx errors
- if status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error() {
- attempt += 1;
-
- if attempt > config.max_retries {
- log::warn!("Max retries ({}) exceeded for request", config.max_retries);
- return Ok(response);
- }
-
- // Check for Retry-After header on 429 responses
- if status == StatusCode::TOO_MANY_REQUESTS
- && let Some(retry_after) = response.headers().get("retry-after")
- && let Ok(retry_str) = retry_after.to_str()
- && let Ok(seconds) = retry_str.parse::<u64>()
- {
- delay = Duration::from_secs(seconds);
- log::info!("Rate limited, retrying after {} seconds", seconds);
- }
-
- log::info!(
- "Request failed with status {}, retrying in {:?} (attempt {}/{})",
- status,
- delay,
- attempt,
- config.max_retries
- );
-
- sleep(delay).await;
-
- // Calculate next delay with exponential backoff
- delay = Duration::from_secs_f64(
- (delay.as_secs_f64() * config.exponential_base)
- .min(config.max_delay.as_secs_f64()),
- );
-
- continue;
- }
-
- // For other status codes, don't retry
- return Ok(response);
- }
- Err(e) => {
- // Network errors should be retried
- attempt += 1;
-
- if attempt > config.max_retries {
- log::error!("Max retries ({}) exceeded: {}", config.max_retries, e);
- return Err(e);
- }
-
- log::warn!(
- "Request failed: {}, retrying in {:?} (attempt {}/{})",
- e,
- delay,
- attempt,
- config.max_retries
- );
-
- sleep(delay).await;
-
- // Calculate next delay with exponential backoff
- delay = Duration::from_secs_f64(
- (delay.as_secs_f64() * config.exponential_base)
- .min(config.max_delay.as_secs_f64()),
- );
- }
- }
- }
-}
diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rs
index d7f8870f88..f30b15a081 100644
--- a/rust/apps/cli/src/models/error.rs
+++ b/rust/apps/cli/src/models/error.rs
@@ -51,6 +51,30 @@ pub enum Error {
Generic(String),
}
+impl From<ente_core::http::Error> for Error {
+ fn from(error: ente_core::http::Error) -> Self {
+ let message = error.to_string();
+ match error {
+ ente_core::http::Error::Http { status, .. } => Error::ApiError {
+ status,
+ code: None,
+ message,
+ },
+ ente_core::http::Error::Api { status, code, .. } => Error::ApiError {
+ status,
+ code: Some(code),
+ message,
+ },
+ ente_core::http::Error::Network(_) => {
+ Error::Generic(format!("Network error: {message}"))
+ }
+ ente_core::http::Error::Parse(_) => {
+ Error::Generic(format!("JSON parse error: {message}"))
+ }
+ }
+ }
+}
+
impl From<crypto::Error> for Error {
fn from(err: crypto::Error) -> Self {
match err {
@@ -84,27 +108,7 @@ impl From<AuthError> for Error {
impl From<AccountsError> for Error {
fn from(err: AccountsError) -> Self {
match err {
- AccountsError::Http(error) => {
- let message = error.to_string();
- match error {
- ente_core::http::Error::Http { status, .. } => Error::ApiError {
- status,
- code: None,
- message,
- },
- ente_core::http::Error::Api { status, code, .. } => Error::ApiError {
- status,
- code: Some(code),
- message,
- },
- ente_core::http::Error::Network(_) => {
- Error::Generic(format!("Network error: {message}"))
- }
- ente_core::http::Error::Parse(_) => {
- Error::Generic(format!("JSON parse error: {message}"))
- }
- }
- }
+ AccountsError::Http(error) => Error::from(error),
AccountsError::Serialization(source) => Error::Serialization(source),
AccountsError::Crypto(message) => Error::Crypto(message),
AccountsError::AuthenticationFailed(message) => Error::AuthenticationFailed(message),