From 3c907adaae156da52d6ffa144df4aeb3fddd53d7 Mon Sep 17 00:00:00 2001 From: Roman Date: Sun, 15 Nov 2026 03:06:34 +0800 Subject: [PATCH 1/2] fix(google-drive): retry rate-limit 403s with bounded backoff (#150) * fix(google-drive): resolve duplicate folders to the oldest and fail on list errors * fix(google-drive): retry rate-limit 403s with bounded backoff * fix(google-drive): jitter the retry backoff and keep test timing out of the code * fix: refactoring --------- Co-authored-by: romzes5000 Co-authored-by: Charles Gauthereau --- Cargo.toml | 5 +- docker-compose.yml | 2 +- .../storage/providers/google_drive/helpers.rs | 424 ++++++++++++------ src/tests/storage/google_drive.rs | 320 ++++++++++++- 4 files changed, 606 insertions(+), 145 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 80b541ea..4ee04769 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,9 +47,6 @@ aes-gcm = "0.11" tokio-stream = "0.1.18" url = "2.5.8" percent-encoding = "2.3.2" -# bollard must match the version testcontainers uses (bollard-stubs is pinned -# exactly, so two bollards cannot coexist). Upgrade bollard, testcontainers and -# testcontainers-modules together. bollard = "0.20.0" rustls = "0.23" globset = "0.4" @@ -59,7 +56,7 @@ walkdir = "2.5" libc = "0.2" [dev-dependencies] -tokio = { version = "1", features = ["full"] } +tokio = { version = "1", features = ["full", "test-util"] } testcontainers = "0.27.1" testcontainers-modules = { version = "0.15.0", features = ["postgres", "redis", "valkey", "mysql", "mariadb", "mongo"] } wiremock = "0.6" diff --git a/docker-compose.yml b/docker-compose.yml index 57d523c4..5627f4c1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,7 +26,7 @@ services: LOG: debug TZ: "Europe/Paris" # TMPDIR: /scratch - EDGE_KEY: "eyJzZXJ2ZXJVcmwiOiJodHRwOi8vbG9jYWxob3N0Ojg4ODciLCJhZ2VudElkIjoiOGYzOTAyYjgtZmU0Yy00NmY2LWE0ODktNzE5MTNhZTgxMjg3IiwibWFzdGVyS2V5QjY0IjoiMUh0djdtWCtYVkJxL0IzUEV2WDlZZjlQeUdVZW5oRHlXemo5THRqNW90WT0ifQ==" + EDGE_KEY: "eyJzZXJ2ZXJVcmwiOiJodHRwOi8vbG9jYWxob3N0Ojg4ODciLCJhZ2VudElkIjoiN2I4ZjE0MjUtMDU4MC00NmJjLWFkMzAtYTBkOGE3YzFjZTkwIiwibWFzdGVyS2V5QjY0IjoiQlhWM1hvbEM2NTZTVjdkTmdjV1BHUWxrKytycExJNmxHRGk3Q1BCNWllbz0ifQ==" #CHUNK_SIZE_MB: "1" #POLLING: 1 #RETRY_ATTEMPTS: 3 diff --git a/src/services/storage/providers/google_drive/helpers.rs b/src/services/storage/providers/google_drive/helpers.rs index 28315448..d3c92f6f 100644 --- a/src/services/storage/providers/google_drive/helpers.rs +++ b/src/services/storage/providers/google_drive/helpers.rs @@ -6,9 +6,9 @@ use futures::StreamExt; use reqwest::{Client as ReqwestClient, StatusCode}; use reqwest::{Client, header}; use serde_json::{Value, json}; +use std::time::Duration; -pub const DRIVE_FILES_URL: &str = - "https://www.googleapis.com/drive/v3/files?supportsAllDrives=true"; +pub const DRIVE_API_BASE: &str = "https://www.googleapis.com/drive/v3"; pub const DRIVE_RESUMABLE_UPLOAD_URL: &str = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true"; const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token"; @@ -17,7 +17,6 @@ pub async fn get_google_drive_token(config: &GoogleDriveProviderConfig) -> Resul exchange_refresh_token(&ReqwestClient::new(), GOOGLE_TOKEN_URL, config).await } -/// OAuth 2.0 refresh-token grant (RFC 6749 §6), client credentials in the body. pub(crate) async fn exchange_refresh_token( client: &Client, token_url: &str, @@ -53,107 +52,269 @@ pub(crate) async fn exchange_refresh_token( .ok_or_else(|| anyhow!("token response has no access_token")) } -pub async fn ensure_folder_path( - config: &GoogleDriveProviderConfig, - path_parts: &[&str], -) -> Result { - if path_parts.is_empty() { - return Ok(config.folder_id.clone()); +pub const DRIVE_RETRY_MAX: u32 = 5; + +pub fn drive_error_reasons(body: &str) -> Vec { + serde_json::from_str::(body) + .ok() + .and_then(|value| value["error"]["errors"].as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|error| error["reason"].as_str().map(str::to_string)) + .collect() +} + +pub fn is_retryable_drive_status(status: u16, body: &str, retry_server_errors: bool) -> bool { + match status { + 429 => true, + 403 => drive_error_reasons(body) + .iter() + .any(|reason| reason == "rateLimitExceeded" || reason == "userRateLimitExceeded"), + 500 | 502 | 503 | 504 => retry_server_errors, + _ => false, } +} - let token = get_google_drive_token(config).await?; - let client = ReqwestClient::new(); - let mut parent_id = config.folder_id.clone(); +pub fn drive_backoff(attempt: u32) -> Duration { + Duration::from_secs(5 * (1u64 << attempt.min(4))) + + Duration::from_millis(rand::random_range(0..1000)) +} - for &name in path_parts { - let query = format!( - "'{parent_id}' in parents and name='{name}' and mimeType='application/vnd.google-apps.folder' and trashed=false" - ); - - let res = client - .get("https://www.googleapis.com/drive/v3/files") - .bearer_auth(&token) - .query(&[ - ("q", query), - ("fields", "files(id,name)".to_string()), - ("supportsAllDrives", "true".to_string()), - ("includeItemsFromAllDrives", "true".to_string()), - ("corpora", "allDrives".to_string()), - ]) - .send() - .await - .context("list folders failed")? - .json::() - .await?; - - if let Some(files) = res["files"].as_array() { - if let Some(folder) = files.first() { - if let Some(id) = folder["id"].as_str() { - parent_id = id.to_string(); - continue; +fn shorten(body: &str) -> String { + const MAX_CHARS: usize = 500; + if body.chars().count() <= MAX_CHARS { + return body.to_string(); + } + let head: String = body.chars().take(MAX_CHARS).collect(); + format!("{head}…") +} + +pub(crate) struct DriveResponse { + pub status: StatusCode, + pub headers: header::HeaderMap, + pub body: String, +} + +pub(crate) async fn send_with_retry( + mut send: F, + retry_server_errors: bool, +) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let mut attempt = 0u32; + loop { + match send().await { + Ok(res) => { + let status = res.status(); + let headers = res.headers().clone(); + let body = res.text().await.unwrap_or_default(); + if attempt < DRIVE_RETRY_MAX + && is_retryable_drive_status(status.as_u16(), &body, retry_server_errors) + { + tracing::warn!( + "Drive HTTP {status}, retry {}: {}", + attempt + 1, + shorten(&body) + ); + } else { + return Ok(DriveResponse { + status, + headers, + body, + }); } } + Err(e) if (e.is_timeout() || e.is_connect()) && attempt < DRIVE_RETRY_MAX => { + tracing::warn!("Drive request error, retry {}: {e}", attempt + 1); + } + Err(e) => return Err(e).context("Drive request failed"), + } + tokio::time::sleep(drive_backoff(attempt)).await; + attempt += 1; + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DriveItem { + pub id: String, + pub created_time: String, +} + +pub fn pick_oldest(items: &[DriveItem]) -> Option<&DriveItem> { + items.iter().min_by(|a, b| { + a.created_time + .cmp(&b.created_time) + .then_with(|| a.id.cmp(&b.id)) + }) +} + +pub fn parse_files_list(status: u16, body: &str) -> Result> { + if !(200..300).contains(&status) { + return Err(anyhow!("Drive files.list failed: HTTP {status}: {body}")); + } + let value: Value = serde_json::from_str(body).context("Drive files.list: invalid JSON")?; + let files = value + .get("files") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("Drive files.list: response has no files array"))?; + Ok(files + .iter() + .filter_map(|file| { + Some(DriveItem { + id: file.get("id")?.as_str()?.to_string(), + created_time: file + .get("createdTime") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + }) + }) + .collect()) +} + +pub fn escape_query_value(value: &str) -> String { + value.replace('\\', "\\\\").replace('\'', "\\'") +} + +pub(crate) async fn list_files( + client: &Client, + api_base: &str, + token: &str, + query: &str, +) -> Result> { + let url = format!("{api_base}/files"); + let res = send_with_retry( + || { + client + .get(&url) + .bearer_auth(token) + .query(&[ + ("q", query), + ("fields", "files(id,createdTime)"), + ("orderBy", "createdTime"), + ("pageSize", "100"), + ("supportsAllDrives", "true"), + ("includeItemsFromAllDrives", "true"), + ("corpora", "allDrives"), + ]) + .send() + }, + true, + ) + .await + .context("Drive files.list request failed")?; + parse_files_list(res.status.as_u16(), &res.body) +} + +async fn list_folders_named( + client: &Client, + api_base: &str, + token: &str, + parent_id: &str, + name: &str, +) -> Result> { + let query = format!( + "'{}' in parents and name='{}' and mimeType='application/vnd.google-apps.folder' and trashed=false", + escape_query_value(parent_id), + escape_query_value(name) + ); + list_files(client, api_base, token, &query).await +} + +async fn create_folder( + client: &Client, + api_base: &str, + token: &str, + parent_id: &str, + name: &str, +) -> Result { + let url = format!("{api_base}/files?supportsAllDrives=true"); + let payload = json!({ + "name": name, + "mimeType": "application/vnd.google-apps.folder", + "parents": [parent_id], + }); + let res = send_with_retry( + || client.post(&url).bearer_auth(token).json(&payload).send(), + true, + ) + .await + .context("Drive folder create request failed")?; + if !res.status.is_success() { + return Err(anyhow!( + "Drive folder create failed: HTTP {}: {}", + res.status, + res.body + )); + } + let folder: Value = + serde_json::from_str(&res.body).context("Drive folder create: invalid JSON")?; + folder["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| anyhow!("No id returned after folder creation")) +} + +pub(crate) async fn ensure_folder_path_at( + client: &Client, + api_base: &str, + token: &str, + root_id: &str, + path_parts: &[&str], +) -> Result { + let mut parent_id = root_id.to_string(); + + for &name in path_parts { + let existing = list_folders_named(client, api_base, token, &parent_id, name).await?; + if let Some(oldest) = pick_oldest(&existing) { + parent_id = oldest.id.clone(); + continue; } - let create_payload = json!({ - "name": name, - "mimeType": "application/vnd.google-apps.folder", - "parents": [parent_id], - }); - - let folder = client - .post(DRIVE_FILES_URL) - .bearer_auth(&token) - .json(&create_payload) - .send() - .await - .context("create folder failed")? - .json::() - .await?; - - parent_id = folder["id"] - .as_str() - .ok_or_else(|| anyhow!("No id returned after folder creation"))? - .to_string(); + let created_id = create_folder(client, api_base, token, &parent_id, name).await?; + let listed = list_folders_named(client, api_base, token, &parent_id, name).await?; + parent_id = pick_oldest(&listed) + .map(|oldest| oldest.id.clone()) + .unwrap_or(created_id); } Ok(parent_id) } +pub async fn ensure_folder_path( + config: &GoogleDriveProviderConfig, + path_parts: &[&str], +) -> Result { + if path_parts.is_empty() { + return Ok(config.folder_id.clone()); + } + + let token = get_google_drive_token(config).await?; + ensure_folder_path_at( + &ReqwestClient::new(), + DRIVE_API_BASE, + &token, + &config.folder_id, + path_parts, + ) + .await +} + pub async fn find_file_by_name( config: &GoogleDriveProviderConfig, file_name: &str, folder_id: &str, ) -> Result> { let token = get_google_drive_token(config).await?; - let client = ReqwestClient::new(); - - let query = format!("'{folder_id}' in parents and name='{file_name}' and trashed=false"); - - let res = client - .get("https://www.googleapis.com/drive/v3/files") - .bearer_auth(&token) - .query(&[ - ("q", query), - ("fields", "files(id,name)".to_string()), - ("supportsAllDrives", "true".to_string()), - ("includeItemsFromAllDrives", "true".to_string()), - ("corpora", "allDrives".to_string()), - ]) - .send() - .await? - .json::() - .await?; - - if let Some(files) = res["files"].as_array() { - if let Some(file) = files.first() { - if let Some(id) = file["id"].as_str() { - return Ok(Some(id.to_string())); - } - } - } - - Ok(None) + let query = format!( + "'{}' in parents and name='{}' and trashed=false", + escape_query_value(folder_id), + escape_query_value(file_name) + ); + let files = list_files(&ReqwestClient::new(), DRIVE_API_BASE, &token, &query).await?; + Ok(pick_oldest(&files).map(|file| file.id.clone())) } pub async fn upload_stream_to_google_drive( @@ -191,22 +352,26 @@ pub async fn upload_stream_to_google_drive( "mimeType": mime, }); - let session_res = client - .post(DRIVE_RESUMABLE_UPLOAD_URL) - .bearer_auth(&token) - .header("X-Upload-Content-Type", mime) - .json(&metadata) - .send() - .await - .context("Failed to initiate resumable upload")?; - - if session_res.status() != StatusCode::OK { - let text = session_res.text().await.unwrap_or_default(); - return Err(anyhow::anyhow!("Initiate failed: {}", text)); + let session_res = send_with_retry( + || { + client + .post(DRIVE_RESUMABLE_UPLOAD_URL) + .bearer_auth(&token) + .header("X-Upload-Content-Type", mime) + .json(&metadata) + .send() + }, + true, + ) + .await + .context("Failed to initiate resumable upload")?; + + if session_res.status != StatusCode::OK { + return Err(anyhow::anyhow!("Initiate failed: {}", session_res.body)); } let upload_url = session_res - .headers() + .headers .get(header::LOCATION) .ok_or_else(|| anyhow::anyhow!("No Location header"))? .to_str()? @@ -259,45 +424,30 @@ pub async fn upload_chunks( (false, false) => format!("bytes {uploaded}-{}/*", chunk_end - 1), }; let chunk_bytes = Bytes::from(chunk_bytes); - - let mut retries = 0; - loop { - let res = client - .put(upload_url) - .header("Content-Range", &content_range) - .header("Content-Length", chunk_bytes.len().to_string()) - .body(chunk_bytes.clone()) - .send() - .await; - - match res { - Ok(resp) - if resp.status().is_success() - || resp.status() == StatusCode::PERMANENT_REDIRECT => - { - // 200 or 308 = good - uploaded = chunk_end; - tracing::info!("Uploaded {} bytes", uploaded); - break; - } - Ok(resp) if resp.status() == StatusCode::TOO_MANY_REQUESTS => { - // Backoff on 429 - tokio::time::sleep(std::time::Duration::from_secs(5 * (1 << retries))).await; - } - Ok(resp) => { - let text = resp.text().await.unwrap_or_default(); - return Err(anyhow::anyhow!("Chunk upload failed: {}", text)); - } - Err(e) if e.is_timeout() || e.is_connect() => { - if retries > 5 { - return Err(e).context("Too many retries"); - } - retries += 1; - tokio::time::sleep(std::time::Duration::from_secs(2u64.pow(retries))).await; - } - Err(e) => return Err(e).context("Chunk request failed"), - } + + let res = send_with_retry( + || { + client + .put(upload_url) + .header("Content-Range", &content_range) + .header("Content-Length", chunk_bytes.len().to_string()) + .body(chunk_bytes.clone()) + .send() + }, + false, + ) + .await + .context("Chunk request failed")?; + + if !(res.status.is_success() || res.status == StatusCode::PERMANENT_REDIRECT) { + return Err(anyhow::anyhow!( + "Chunk upload failed: HTTP {}: {}", + res.status, + shorten(&res.body) + )); } + uploaded = chunk_end; + tracing::info!("Uploaded {} bytes", uploaded); } Ok(()) diff --git a/src/tests/storage/google_drive.rs b/src/tests/storage/google_drive.rs index b0c035fa..46e4327e 100644 --- a/src/tests/storage/google_drive.rs +++ b/src/tests/storage/google_drive.rs @@ -1,5 +1,7 @@ use crate::services::storage::providers::google_drive::helpers::{ - DRIVE_FILES_URL, DRIVE_RESUMABLE_UPLOAD_URL, exchange_refresh_token, upload_chunks, + DRIVE_RESUMABLE_UPLOAD_URL, DRIVE_RETRY_MAX, DriveItem, drive_backoff, drive_error_reasons, + ensure_folder_path_at, escape_query_value, exchange_refresh_token, is_retryable_drive_status, + list_files, parse_files_list, pick_oldest, upload_chunks, }; use crate::services::storage::providers::google_drive::models::GoogleDriveProviderConfig; use crate::tests::services::local_storage_tests::MASTER_KEY_B64; @@ -9,8 +11,9 @@ use crate::utils::stream::build_stream; use bytes::Bytes; use futures::stream; use reqwest::Client; +use std::time::Duration; use tempfile::TempDir; -use wiremock::matchers::{body_string_contains, method, path}; +use wiremock::matchers::{body_string_contains, method, path, query_param_contains}; use wiremock::{Mock, MockServer, ResponseTemplate}; const WINDOW: usize = 8 * 1024 * 1024; @@ -148,7 +151,6 @@ async fn empty_dump_finalizes_a_zero_byte_file() { fn drive_write_urls_carry_supports_all_drives() { assert!(DRIVE_RESUMABLE_UPLOAD_URL.contains("supportsAllDrives=true")); assert!(DRIVE_RESUMABLE_UPLOAD_URL.contains("uploadType=resumable")); - assert!(DRIVE_FILES_URL.contains("supportsAllDrives=true")); } fn drive_config() -> GoogleDriveProviderConfig { @@ -211,3 +213,315 @@ async fn rejected_refresh_token_surfaces_the_oauth_error() { assert!(format!("{error:#}").contains("invalid_grant"), "{error:#}"); } + +fn item(id: &str, created_time: &str) -> DriveItem { + DriveItem { + id: id.to_string(), + created_time: created_time.to_string(), + } +} + +#[test] +fn oldest_of_same_named_folders_wins() { + let items = [ + item("new", "2026-11-08T03:00:22.325Z"), + item("old", "2026-11-06T12:33:28.307Z"), + ]; + assert_eq!(pick_oldest(&items).unwrap().id, "old"); + assert!(pick_oldest(&[]).is_none()); +} + +#[test] +fn oldest_tie_breaks_on_id() { + let items = [ + item("z", "2026-11-06T12:33:28.307Z"), + item("a", "2026-11-06T12:33:28.307Z"), + ]; + assert_eq!(pick_oldest(&items).unwrap().id, "a"); +} + +#[test] +fn failed_list_is_an_error_not_an_empty_folder() { + let body = r#"{"error":{"code":403,"errors":[{"reason":"rateLimitExceeded"}]}}"#; + let error = parse_files_list(403, body).unwrap_err().to_string(); + assert!(error.contains("HTTP 403"), "{error}"); +} + +#[test] +fn list_without_files_array_is_an_error() { + let error = parse_files_list(200, r#"{"kind":"drive#fileList"}"#) + .unwrap_err() + .to_string(); + assert!(error.contains("no files array"), "{error}"); +} + +#[test] +fn list_reads_ids_and_created_times() { + let body = r#"{"files":[{"id":"a","createdTime":"2026-11-06T12:33:28.307Z"},{"id":"b"}]}"#; + assert_eq!( + parse_files_list(200, body).unwrap(), + vec![item("a", "2026-11-06T12:33:28.307Z"), item("b", "")] + ); +} + +#[test] +fn query_values_are_escaped() { + assert_eq!(escape_query_value("o'neil\\db"), "o\\'neil\\\\db"); +} + +#[tokio::test(start_paused = true)] +async fn list_error_surfaces_from_list_files() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(500).set_body_string("backendError")) + .expect(u64::from(DRIVE_RETRY_MAX) + 1) + .mount(&server) + .await; + + let error = list_files(&Client::new(), &server.uri(), "t", "q") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("HTTP 500"), "{error}"); +} + +#[tokio::test] +async fn failed_list_never_creates_a_folder() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(401).set_body_string("invalid credentials")) + .mount(&server) + .await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"id":"dup"}"#)) + .expect(0) + .mount(&server) + .await; + + assert!( + ensure_folder_path_at(&Client::new(), &server.uri(), "t", "root", &["backups"]) + .await + .is_err() + ); +} + +#[tokio::test] +async fn existing_folders_resolve_to_the_oldest() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/files")) + .and(query_param_contains("q", "name='backups'")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"files":[{"id":"new","createdTime":"2026-11-08T03:00:00Z"},{"id":"old","createdTime":"2026-11-06T12:00:00Z"}]}"#, + )) + .mount(&server) + .await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + + let id = ensure_folder_path_at(&Client::new(), &server.uri(), "t", "root", &["backups"]) + .await + .unwrap(); + assert_eq!(id, "old"); +} + +#[tokio::test] +async fn concurrent_create_converges_on_the_oldest_folder() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"files":[]}"#)) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(200).set_body_string( + r#"{"files":[{"id":"theirs","createdTime":"2026-11-08T03:00:00.100Z"},{"id":"mine","createdTime":"2026-11-08T03:00:00.200Z"}]}"#, + )) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/files")) + .and(query_param_contains("supportsAllDrives", "true")) + .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"id":"mine"}"#)) + .expect(1) + .mount(&server) + .await; + + let id = ensure_folder_path_at(&Client::new(), &server.uri(), "t", "root", &["backups"]) + .await + .unwrap(); + assert_eq!(id, "theirs"); +} + +const RATE_LIMIT_403: &str = r#"{"error":{"code":403,"message":"Rate Limit Exceeded","errors":[{"domain":"usageLimits","reason":"rateLimitExceeded","message":"Rate Limit Exceeded"}]}}"#; + +#[test] +fn drive_error_reasons_are_read_from_json() { + assert_eq!( + drive_error_reasons(RATE_LIMIT_403), + vec!["rateLimitExceeded"] + ); + assert!(drive_error_reasons("not json").is_empty()); +} + +#[test] +fn only_rate_limit_403s_are_retryable() { + assert!(is_retryable_drive_status(429, "", false)); + assert!(is_retryable_drive_status(403, RATE_LIMIT_403, false)); + assert!(is_retryable_drive_status( + 403, + r#"{"error":{"errors":[{"reason":"userRateLimitExceeded"}]}}"#, + false + )); + for reason in [ + "insufficientFilePermissions", + "storageQuotaExceeded", + "dailyLimitExceeded", + ] { + let body = format!(r#"{{"error":{{"errors":[{{"reason":"{reason}"}}]}}}}"#); + assert!(!is_retryable_drive_status(403, &body, true), "{reason}"); + } + assert!(!is_retryable_drive_status(403, "rateLimitExceeded", true)); +} + +#[test] +fn server_errors_retry_only_when_safe() { + assert!(is_retryable_drive_status(503, "", true)); + assert!(!is_retryable_drive_status(503, "", false)); + assert!(!is_retryable_drive_status(404, "", true)); +} + +#[tokio::test(start_paused = true)] +async fn list_retries_a_rate_limit_403() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(403).set_body_string(RATE_LIMIT_403)) + .up_to_n_times(2) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/files")) + .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"files":[{"id":"a"}]}"#)) + .mount(&server) + .await; + + let started = tokio::time::Instant::now(); + let files = list_files(&Client::new(), &server.uri(), "t", "q") + .await + .unwrap(); + assert_eq!(files, vec![item("a", "")]); + let waited = started.elapsed(); + assert!(waited >= Duration::from_secs(15), "{waited:?}"); +} + +#[tokio::test] +async fn permission_403_fails_without_retry() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(403).set_body_string( + r#"{"error":{"errors":[{"reason":"insufficientFilePermissions"}]}}"#, + ), + ) + .expect(1) + .mount(&server) + .await; + + let error = list_files(&Client::new(), &server.uri(), "t", "q") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("HTTP 403"), "{error}"); +} + +#[tokio::test(start_paused = true)] +async fn chunk_retries_a_rate_limit_403_and_completes() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/upload")) + .respond_with(ResponseTemplate::new(403).set_body_string(RATE_LIMIT_403)) + .up_to_n_times(1) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path("/upload")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + upload_chunks( + &Client::new(), + &format!("{}/upload", server.uri()), + stream::iter(vec![Ok(Bytes::from(vec![9u8; 1024]))]), + 1024, + ) + .await + .unwrap(); + + let puts = received_puts(&server).await; + assert_eq!(puts.len(), 2); + assert_eq!(puts[0], puts[1]); +} + +#[tokio::test(start_paused = true)] +async fn chunk_gives_up_after_bounded_rate_limit_retries() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(429)) + .expect(u64::from(DRIVE_RETRY_MAX) + 1) + .mount(&server) + .await; + + assert!( + upload_chunks( + &Client::new(), + &format!("{}/upload", server.uri()), + stream::iter(vec![Ok(Bytes::from(vec![9u8; 16]))]), + 16, + ) + .await + .is_err() + ); +} + +#[tokio::test] +async fn chunk_does_not_resend_after_a_server_error() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(503).set_body_string("backendError")) + .expect(1) + .mount(&server) + .await; + + let error = upload_chunks( + &Client::new(), + &format!("{}/upload", server.uri()), + stream::iter(vec![Ok(Bytes::from(vec![9u8; 16]))]), + 16, + ) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("backendError"), "{error}"); +} + +#[test] +fn backoff_doubles_from_five_seconds_with_bounded_jitter() { + for (attempt, base) in [(0, 5), (1, 10), (2, 20), (3, 40), (4, 80), (9, 80)] { + for _ in 0..50 { + let delay = drive_backoff(attempt); + assert!( + delay >= Duration::from_secs(base) && delay < Duration::from_secs(base + 1), + "attempt {attempt}: {delay:?}" + ); + } + } +} From 82b63d0a8c9b17e5f0399ecbca6ab0a987126fa6 Mon Sep 17 00:00:00 2001 From: Charles Gauthereau Date: Sat, 14 Nov 2026 20:19:15 +0100 Subject: [PATCH 2/2] ci: publish static Linux binaries for amd64 and arm64 in releases --- .github/workflows/linux-release.yml | 82 +++++++++++++++++++++++++++++ .github/workflows/release.yml | 12 +++++ 2 files changed, 94 insertions(+) create mode 100644 .github/workflows/linux-release.yml diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml new file mode 100644 index 00000000..c60a52d2 --- /dev/null +++ b/.github/workflows/linux-release.yml @@ -0,0 +1,82 @@ +name: Build Linux release + +on: + workflow_call: + inputs: + version: + description: 'Release version (git tag), e.g. 1.18.4' + type: string + required: false + ref: + description: 'Git ref to check out and build' + type: string + required: false + draft_tag: + description: 'Draft GitHub release tag to attach the assets to (e.g. untagged-xxxx). Empty = skip upload.' + type: string + required: false + secrets: + GH_TOKEN: + required: false + + workflow_dispatch: + inputs: + ref: + description: 'Git ref to check out and build' + type: string + required: false + +jobs: + build-linux: + name: Build linux/${{ matrix.arch }} + runs-on: ${{ matrix.runner }} + strategy: + matrix: + include: + - arch: amd64 + runner: ubuntu-latest + target: x86_64-unknown-linux-musl + - arch: arm64 + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-musl + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref || github.ref }} + + - name: Install musl tools + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + + - name: Set up Rust toolchain (musl) + uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + + - name: Build (cargo release) + run: cargo build --release --locked --bin app --target ${{ matrix.target }} + + - name: Prepare artifact archive + id: prepare_artifact + env: + RELEASE_VERSION: ${{ inputs.version || github.sha }} + run: | + mkdir artifact + cp "target/${{ matrix.target }}/release/app" artifact/portabase-agent + archive="linux-${{ matrix.arch }}-release-$RELEASE_VERSION.tar.gz" + tar -czf "$archive" -C artifact portabase-agent + echo "archive=$archive" >> "$GITHUB_OUTPUT" + + - name: Upload build artifact + if: ${{ inputs.draft_tag == '' }} + uses: actions/upload-artifact@v4 + with: + name: linux-${{ matrix.arch }}-release + path: ${{ steps.prepare_artifact.outputs.archive }} + + - name: Attach asset to draft release + if: ${{ inputs.draft_tag != '' }} + env: + GH_TOKEN: ${{ secrets.GH_TOKEN }} + run: gh release upload "${{ inputs.draft_tag }}" "${{ steps.prepare_artifact.outputs.archive }}" --clobber diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4cc7d73e..b4db2dec 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,6 +129,17 @@ jobs: secrets: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + build-linux: + needs: create-release + if: ${{ needs.create-release.result == 'success' }} + uses: ./.github/workflows/linux-release.yml + with: + version: ${{ needs.create-release.outputs.version }} + ref: ${{ needs.create-release.outputs.version }} + draft_tag: ${{ needs.create-release.outputs.draft_tag }} + secrets: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + finalize-release: needs: - create-release @@ -136,6 +147,7 @@ jobs: - publish-docker-ghcr - publish-helm - build-windows + - build-linux runs-on: ubuntu-latest outputs: release_tag: ${{ steps.publish_release_step.outputs.release_tag }}