Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(rust-sdk): Google Drive retries, built-in client, typed sign-in errors; Rust CLI google-drive sign-in (#2726)
LJ π₯₯π΄617ee89a0990
diff --git a/docs/src/content/docs/cli_rust.mdx b/docs/src/content/docs/cli_rust.mdxindex cbefbc46..ef1ddba0 100644--- a/docs/src/content/docs/cli_rust.mdx+++ b/docs/src/content/docs/cli_rust.mdx@@ -5,7 +5,7 @@ description: >your crate, the app target format, the three attributes an app registers with,and the ls, show, update, drop and init subcommands.----The `cocoindex` CLI for Rust projects gives a Rust pipeline the same commands the [Python CLI](./cli) has: `ls`, `show`, `update`, `drop` and `init`. The Python prose on that page describes the Python tool; this page describes the Rust tool, which is a separate binary built from the `rust/cli` crate of the repository.+The `cocoindex` CLI for Rust projects gives a Rust pipeline the same commands the [Python CLI](./cli) has: `ls`, `show`, `update`, `drop`, `init` and `google-drive`. The Python prose on that page describes the Python tool; this page describes the Rust tool, which is a separate binary built from the `rust/cli` crate of the repository.## How it works@@ -211,6 +211,21 @@ The scaffold is a crate with `Cargo.toml`, `src/main.rs` (a `lifespan`, an `app`* `--dir <DIR>`: Directory to create the project in.* `--sdk-path <PATH>`: Depend on a local checkout of the cocoindex Rust SDK (`rust/sdk/cocoindex`) instead of the git repository.+### `google-drive`++Sign a personal Google account in to the Google Drive connector (experimental). The same two commands as the Python CLI, over the same token file, so one sign-in serves both SDKs; see [Google Drive](./connectors/google_drive#signing-in-with-a-personal-account).++```sh+cocoindex google-drive sign-in [CLIENT_SECRETS]+cocoindex google-drive sign-out+```++`sign-in` opens the consent page in the browser, or prints the link when this host has none, and keeps the tokens in a file readable by this user only. It uses CocoIndex's own OAuth client when this release includes one; to use a Desktop-app OAuth client of your own, pass `CLIENT_SECRETS`, the JSON file you downloaded for it. `sign-out` revokes the stored sign-in at Google and deletes its token file.++**Options:**++* `--token-path <FILE>`: Where to keep the sign-in (`sign-in`), or the sign-in to end (`sign-out`); default: `cocoindex/google_drive_token.json` under the user's config directory.+## Exit codes`0` on success (also after a clean Ctrl-C), `1` on an error (including a failed build), `2` on a usage error or a protocol mismatch between the CLI and the SDK the binary was built with.diff --git a/docs/src/content/docs/connectors/google_drive.mdx b/docs/src/content/docs/connectors/google_drive.mdxindex 37601263..11478866 100644--- a/docs/src/content/docs/connectors/google_drive.mdx+++ b/docs/src/content/docs/connectors/google_drive.mdx@@ -306,7 +306,7 @@ cocoindex google-drive sign-out # revokes the sign-in at Google and deletesThe same two steps are available in Python as `UserAccount().sign_in(client_secrets_path)` (with no argument for CocoIndex's own client) and `UserAccount().sign_out()`.-The Rust SDK has no `cocoindex google-drive` command. The Rust `UserAccount` reads and writes the same token file as the Python SDK, at the same default location, so one sign-in serves both: sign in with the Python CLI, or call `UserAccount::new()?.sign_in(client_secrets_path).await?` once from a small binary. The Rust `sign_in` always takes the client secrets file. `sign_out().await?` revokes the sign-in and deletes the file.+The `cocoindex` binary for Rust projects has the same two commands. The Rust `UserAccount` reads and writes the same token file as the Python SDK, at the same default location, so one sign-in serves both. From code, `UserAccount::new()?.sign_in(Some(client_secrets_path)).await?` signs in with your own client and `sign_in(None)` with the client built into the release, when it has one; `sign_out().await?` revokes the sign-in and deletes the file.### UserAccount@@ -325,7 +325,7 @@ class UserAccount(token_path: str | os.PathLike[str] | None = None)pub fn UserAccount::new() -> Result<Self>pub fn UserAccount::with_token_path(token_path: impl Into<PathBuf>) -> Selfpub fn UserAccount::token_path(&self) -> &Path-pub async fn UserAccount::sign_in(&self, client_secrets_path: impl AsRef<Path>) -> Result<String>+pub async fn UserAccount::sign_in(&self, client_secrets_path: Option<&Path>) -> Result<String>pub async fn UserAccount::sign_out(&self) -> Result<bool>pub fn UserAccount::email(&self) -> Result<String>pub fn UserAccount::is_signed_in(&self) -> bool@@ -374,7 +374,7 @@ mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {.await?;```-`from_user_account` reads the token file now and fails with a message that says how to sign in when no usable sign-in is stored. The client's identity is the account's address, so a refreshed token keeps memoized work and a different account invalidates it.+`from_user_account` reads the token file now and fails with a message that says how to sign in when no usable sign-in is stored. The sign-in errors are typed: `SignInError::of(&error)` recovers a `SignInError` from the SDK error, `SignInRequired` when a run has no working sign-in (none stored, or Google refused the stored one) and `Failed` for the rest; the message never contains a token. The client's identity is the account's address, so a refreshed token keeps memoized work and a different account invalidates it.</Fragment></LangTabs>diff --git a/rust/cli/Cargo.toml b/rust/cli/Cargo.tomlindex 902481e4..b10bda2f 100644--- a/rust/cli/Cargo.toml+++ b/rust/cli/Cargo.toml@@ -16,7 +16,8 @@ doc = false[dependencies]# Protocol types (`cocoindex::cli::protocol`) shared with user binaries.-cocoindex = { path = "../sdk/cocoindex" }+# `google-drive sign-in` / `sign-out` call the connector's `UserAccount`.+cocoindex = { path = "../sdk/cocoindex", features = ["google_drive"] }# State-db inspection for `ls --db` and `show`, without user code.cocoindex_core = { path = "../core", package = "cocoindex_core" }clap = { workspace = true }diff --git a/rust/cli/src/commands.rs b/rust/cli/src/commands.rsindex 96d35172..b7179a8a 100644--- a/rust/cli/src/commands.rs+++ b/rust/cli/src/commands.rs@@ -1,9 +1,10 @@-//! `ls`, `show`, `update` and `drop`.+//! `ls`, `show`, `update`, `drop`, and the `google-drive` sign-in.use std::path::{Path, PathBuf};use cocoindex::app::DB_PATH_ENV;use cocoindex::cli::protocol::{AppInfo, Event, Outcome};+use cocoindex::connectors::gdrive;use crate::build::{self, BuildOpts};use crate::child::{self, Interrupt, Output};@@ -434,6 +435,54 @@ pub async fn drop_app(args: DropArgs) -> CliResult<()> {Ok(())}+// ---------------------------------------------------------------------------+// google-drive sign-in / sign-out+// ---------------------------------------------------------------------------++/// The account at `token_path`, or at the connector's default token file.+fn google_account(token_path: Option<PathBuf>) -> CliResult<gdrive::UserAccount> {+ match token_path {+ Some(path) => Ok(gdrive::UserAccount::with_token_path(path)),+ None => gdrive::UserAccount::new().map_err(|e| CliError::failure(e.to_string())),+ }+}++pub async fn google_drive_sign_in(+ client_secrets: Option<PathBuf>,+ token_path: Option<PathBuf>,+) -> CliResult<()> {+ if let Some(path) = &client_secrets+ && !path.is_file()+ {+ return Err(CliError::usage(format!(+ "Invalid value for 'CLIENT_SECRETS': File '{}' does not exist.",+ path.display()+ )));+ }+ let email = google_account(token_path)?+ .sign_in(client_secrets.as_deref())+ .await+ .map_err(|e| CliError::failure(e.to_string()))?;+ println!("Signed in as {email}.");+ Ok(())+}++pub async fn google_drive_sign_out(token_path: Option<PathBuf>) -> CliResult<()> {+ let existed = google_account(token_path)?+ .sign_out()+ .await+ .map_err(|e| CliError::failure(e.to_string()))?;+ println!(+ "{}",+ if existed {+ "Signed out."+ } else {+ "No sign-in was stored."+ }+ );+ Ok(())+}+#[cfg(test)]mod tests {use super::*;diff --git a/rust/cli/src/main.rs b/rust/cli/src/main.rsindex 86697f77..52790cf9 100644--- a/rust/cli/src/main.rs+++ b/rust/cli/src/main.rs@@ -153,6 +153,9 @@ enum Command {#[command(flatten)]build: BuildArgs,},+ /// Sign a personal Google account in to the Google Drive connector (experimental).+ #[command(name = "google-drive", subcommand)]+ GoogleDrive(GoogleDriveCommand),/// Initialize a new Rust CocoIndex project.Init {/// Name of the project (defaults to the directory name).@@ -167,6 +170,34 @@ enum Command {},}+#[derive(Subcommand)]+enum GoogleDriveCommand {+ /// Sign in with a Google account to read its Google Drive.+ ///+ /// Uses CocoIndex's own OAuth client when this release includes one. To use a+ /// Desktop-app OAuth client of your own, pass CLIENT_SECRETS, the JSON file you+ /// downloaded for it.+ ///+ /// Opens the consent page in the browser, or prints the link when this host has+ /// none, and keeps the tokens in a file readable by this user only.+ #[command(name = "sign-in")]+ SignIn {+ #[arg(value_name = "CLIENT_SECRETS")]+ client_secrets: Option<PathBuf>,+ /// Where to keep the sign-in; default: cocoindex/google_drive_token.json under the+ /// user's config directory.+ #[arg(long, value_name = "FILE")]+ token_path: Option<PathBuf>,+ },+ /// Revoke the stored sign-in at Google and delete its token file.+ #[command(name = "sign-out")]+ SignOut {+ /// The sign-in to end; default: the one `sign-in` writes by default.+ #[arg(long, value_name = "FILE")]+ token_path: Option<PathBuf>,+ },+}+fn load_env(env_file: Option<&PathBuf>) -> CliResult<()> {let loaded = match env_file {Some(path) => dotenvy::from_path(path)@@ -253,6 +284,13 @@ async fn run(cli: Cli) -> CliResult<()> {}).await}+ Command::GoogleDrive(GoogleDriveCommand::SignIn {+ client_secrets,+ token_path,+ }) => commands::google_drive_sign_in(client_secrets, token_path).await,+ Command::GoogleDrive(GoogleDriveCommand::SignOut { token_path }) => {+ commands::google_drive_sign_out(token_path).await+ }Command::Init {project_name,dir,diff --git a/rust/cli/tests/e2e.rs b/rust/cli/tests/e2e.rsindex c6c7e010..33ed4130 100644--- a/rust/cli/tests/e2e.rs+++ b/rust/cli/tests/e2e.rs@@ -593,3 +593,62 @@ fn init_scaffold_builds_and_runs() {"the lifespan's db path");}++/// `google-drive sign-out` without a stored sign-in says so; `sign-in` with a+/// missing client file is a usage error, and without one this build (which+/// has no built-in OAuth client) says how to sign in. No browser opens: both+/// fail before the consent.+#[test]+fn google_drive_sign_in_and_sign_out() {+ let sb = Sandbox::new(&[]);+ let token = sb.path("google_drive_token.json");+ let token_arg = token.display().to_string();++ let out = sb.cli(&["google-drive", "sign-out", "--token-path", &token_arg]);+ assert_ok(&out);+ assert!(+ stdout(&out).contains("No sign-in was stored."),+ "{}",+ stdout(&out)+ );++ let missing = sb.cli(&[+ "google-drive",+ "sign-in",+ "/definitely/not/here.json",+ "--token-path",+ &token_arg,+ ]);+ assert_eq!(missing.status.code(), Some(2));+ assert!(+ stderr(&missing).contains("does not exist"),+ "{}",+ stderr(&missing)+ );++ let no_builtin = sb.cli(&["google-drive", "sign-in", "--token-path", &token_arg]);+ assert_eq!(no_builtin.status.code(), Some(1));+ assert!(+ stderr(&no_builtin).contains("no built-in OAuth client"),+ "{}",+ stderr(&no_builtin)+ );+ assert!(!token.exists());++ // A stored sign-in is deleted even though Google cannot be reached at the+ // address in the file: the sign-out never leaves tokens behind.+ std::fs::write(+ &token,+ r#"{"version":1,"client_id":"c","client_secret":"s","refresh_token":"r","access_token":"a","expires_at":0.0,"email":"[email protected]"}"#,+ )+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o600)).unwrap();+ }+ let out = sb.cli(&["google-drive", "sign-out", "--token-path", &token_arg]);+ assert_ok(&out);+ assert!(stdout(&out).contains("Signed out."), "{}", stdout(&out));+ assert!(!token.exists());+}diff --git a/rust/sdk/cocoindex/src/connectors/gdrive.rs b/rust/sdk/cocoindex/src/connectors/gdrive.rsindex 17a18e7a..2ffcd0a6 100644--- a/rust/sdk/cocoindex/src/connectors/gdrive.rs+++ b/rust/sdk/cocoindex/src/connectors/gdrive.rs@@ -247,6 +247,106 @@ impl crate::memo::MemoInput for DriveFile {}}+/// Attempts after the first for every Drive API request, as Python's+/// `googleapiclient` makes them (`num_retries`): a 5xx, a 429, a 403 whose+/// reason is a rate limit, or a transport failure is tried again after a+/// random wait of up to `2^n` Γ [`RETRY_BACKOFF_UNIT`]; Drive's usage-limits+/// guide asks clients to do exactly that.+const RETRIES: u32 = 5;+const RETRY_BACKOFF_UNIT: Duration = Duration::from_secs(1);++/// A random fraction in `[0, 1)`, for the retry jitter.+fn random_fraction() -> f64 {+ let bytes = uuid::Uuid::new_v4().into_bytes();+ f64::from(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) / f64::from(u32::MAX)+}++/// Whether a `403` is Drive's rate limit, read from its error body.+fn is_rate_limit_403(body: &[u8]) -> bool {+ let Ok(json) = serde_json::from_slice::<serde_json::Value>(body) else {+ return false;+ };+ json.get("error")+ .and_then(|e| e.get("errors"))+ .and_then(|errors| errors.as_array())+ .is_some_and(|errors| {+ errors.iter().any(|e| {+ matches!(+ e.get("reason").and_then(|r| r.as_str()),+ Some("userRateLimitExceeded" | "rateLimitExceeded")+ )+ })+ })+}++/// How one attempt of a Drive request failed.+enum Attempt {+ /// A failure another attempt may not repeat.+ Retry(String),+ /// A failure to report as it is.+ Final(Error),+}++async fn send_once(+ request: reqwest::RequestBuilder,+ what: &str,+) -> std::result::Result<reqwest::Response, Attempt> {+ let resp = request+ .send()+ .await+ .map_err(|e| Attempt::Retry(format!("{what}: {e}")))?;+ let status = resp.status();+ if status.is_success() {+ return Ok(resp);+ }+ let retry = status.is_server_error()+ || status == reqwest::StatusCode::TOO_MANY_REQUESTS+ || (status == reqwest::StatusCode::FORBIDDEN+ && is_rate_limit_403(&resp.bytes().await.unwrap_or_default()));+ if retry {+ Err(Attempt::Retry(format!("{what} failed: {status}")))+ } else {+ Err(Attempt::Final(Error::engine(format!(+ "{what} failed: {status}"+ ))))+ }+}++/// Send a Drive API request, retrying as [`RETRIES`] says; the successful+/// response, or the last failure as an error naming `what`.+async fn send_with_retry(+ request: reqwest::RequestBuilder,+ what: &str,+) -> Result<reqwest::Response> {+ let mut retries = 0u32;+ loop {+ // A request with a streaming body cannot be cloned; Drive reads have+ // none. The last attempt takes the request itself.+ let this_try = match request.try_clone() {+ Some(cloned) if retries < RETRIES => cloned,+ _ => {+ return send_once(request, what).await.map_err(|a| match a {+ Attempt::Retry(failure) => {+ Error::engine(format!("{failure} (after {retries} retries)"))+ }+ Attempt::Final(e) => e,+ });+ }+ };+ match send_once(this_try, what).await {+ Ok(resp) => return Ok(resp),+ Err(Attempt::Final(e)) => return Err(e),+ Err(Attempt::Retry(failure)) => {+ retries += 1;+ let wait =+ RETRY_BACKOFF_UNIT.mul_f64(random_fraction() * f64::from(1u32 << retries));+ tracing::debug!("{failure}; retrying in {wait:?}");+ tokio::time::sleep(wait).await;+ }+ }+ }+}+fn default_file_cache() -> Arc<FileContentCache> {Arc::new(FileContentCache::new())}@@ -573,7 +673,7 @@ impl GoogleDriveClient {}/// List the direct children of a folder (one page at a time, following- /// `nextPageToken`).+ /// `nextPageToken`). Drive lists them in no set order.async fn list_children(&self, folder_id: &str) -> Result<Vec<DriveFile>> {validate_folder_id(folder_id)?;let token = self.token().await?;@@ -592,12 +692,7 @@ impl GoogleDriveClient {if let Some(t) = &page_token {req = req.query(&[("pageToken", t.as_str())]);}- let resp = req- .send()- .await- .map_err(|e| Error::engine(format!("drive list: {e}")))?- .error_for_status()- .map_err(|e| Error::engine(format!("drive list failed: {e}")))?;+ let resp = send_with_retry(req, "drive list").await?;let json: serde_json::Value = resp.json().await@@ -632,13 +727,7 @@ impl GoogleDriveClient {.get(format!("{}/files/{}", self.inner.base_url, file.file_id)).query(&[("alt", "media")]),};- let resp = req- .bearer_auth(&token)- .send()- .await- .map_err(|e| Error::engine(format!("drive download: {e}")))?- .error_for_status()- .map_err(|e| Error::engine(format!("drive download failed: {e}")))?;+ let resp = send_with_retry(req.bearer_auth(&token), "drive download").await?;let bytes = resp.bytes().await@@ -710,6 +799,74 @@ const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(300);const OWN_CLIENT_DOCS: &str ="https://cocoindex.io/docs/connectors/google_drive#setting-up-the-oauth-client";+/// CocoIndex's own Desktop-app OAuth client, so that a sign-in needs no+/// client file: built into the crate when `COCOINDEX_GOOGLE_OAUTH_CLIENT_ID`+/// and `COCOINDEX_GOOGLE_OAUTH_CLIENT_SECRET` were set when it compiled (a+/// release build sets them from the repository's secrets, as the Python+/// wheel's `_builtin_client.json` is written at release time). A build from+/// source has none: its sign-in takes the user's own client.+const BUILTIN_CLIENT: Option<(&str, &str)> = match (+ option_env!("COCOINDEX_GOOGLE_OAUTH_CLIENT_ID"),+ option_env!("COCOINDEX_GOOGLE_OAUTH_CLIENT_SECRET"),+) {+ (Some(client_id), Some(client_secret)) => Some((client_id, client_secret)),+ _ => None,+};++/// A sign-in, sign-out or token refresh failed; the message says what to do.+/// The Python SDK's `SignInError` and `SignInRequiredError`. It reaches the+/// caller as [`Error::User`]; [`SignInError::of`] recovers it from an [`Error`].+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum SignInError {+ /// A run needs a signed-in account and has none that works: no sign-in is+ /// stored, or Google refuses the stored one (the consent expired or was+ /// revoked, or the OAuth client was deleted, disabled or given a new+ /// secret). Sign in again.+ SignInRequired(String),+ /// The sign-in, sign-out or refresh failed for another reason: an unusable+ /// client file, a cancelled consent, a token file another user can read, β¦+ Failed(String),+}++impl SignInError {+ /// The message, without the variant.+ pub fn message(&self) -> &str {+ match self {+ Self::SignInRequired(message) | Self::Failed(message) => message,+ }+ }++ /// The sign-in error behind `error`, if it is one.+ pub fn of(error: &Error) -> Option<&SignInError> {+ match error {+ Error::User(inner) => inner.downcast_ref::<SignInError>(),+ _ => None,+ }+ }++ fn required(message: impl Into<String>) -> Error {+ Error::User(Box::new(Self::SignInRequired(message.into())))+ }++ fn failed(message: impl Into<String>) -> Error {+ Error::User(Box::new(Self::Failed(message.into())))+ }+}++impl std::fmt::Display for SignInError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self.message())+ }+}++impl std::error::Error for SignInError {}++impl From<SignInError> for Error {+ fn from(e: SignInError) -> Self {+ Error::User(Box::new(e))+ }+}+/// Google's OAuth and Drive endpoints. The default is Google; a test points/// them at a mock server with [`UserAccount::with_endpoints`].#[derive(Clone, Debug)]@@ -788,40 +945,62 @@ struct TokenFile {struct OAuthClient {client_id: String,client_secret: String,+ /// CocoIndex's own client ([`BUILTIN_CLIENT`]), not one the user created.+ builtin: bool,+}++/// The client a sign-in uses: the file at `path`, or the built-in one for+/// `None`.+fn resolve_client(path: Option<&std::path::Path>) -> Result<OAuthClient> {+ if let Some(path) = path {+ return load_client(path);+ }+ let Some((client_id, client_secret)) = BUILTIN_CLIENT else {+ return Err(SignInError::failed(format!(+ "This build of CocoIndex has no built-in OAuth client. Sign in with a Desktop \+ app OAuth client of your own: pass the JSON file you downloaded for it (see \+ {OWN_CLIENT_DOCS})."+ )));+ };+ Ok(OAuthClient {+ client_id: client_id.to_string(),+ client_secret: client_secret.to_string(),+ builtin: true,+ })}/// Read the client JSON the Google Cloud console downloads for a Desktop app.fn load_client(path: &std::path::Path) -> Result<OAuthClient> {let raw = std::fs::read_to_string(path).map_err(|e| match e.kind() {std::io::ErrorKind::NotFound => {- Error::engine(format!("No OAuth client file at {}.", path.display()))+ SignInError::failed(format!("No OAuth client file at {}.", path.display()))}- _ => Error::engine(format!(+ _ => SignInError::failed(format!("Cannot read the OAuth client file {}: {e}",path.display())),})?;let document: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {- Error::engine(format!(+ SignInError::failed(format!("Cannot read the OAuth client file {}: {e}",path.display()))})?;let Some(document) = document.as_object() else {- return Err(Error::engine(format!(+ return Err(SignInError::failed(format!("{} is not an OAuth client file.",path.display())));};if document.contains_key("web") && !document.contains_key("installed") {- return Err(Error::engine(format!(+ return Err(SignInError::failed(format!("{} describes a Web application client; the sign-in needs a Desktop app \client (create one under APIs & Services > Credentials).",path.display())));}let Some(installed) = document.get("installed").and_then(|v| v.as_object()) else {- return Err(Error::engine(format!(+ return Err(SignInError::failed(format!("{} is not the JSON of a Desktop app OAuth client (it has no 'installed' section).",path.display())));@@ -833,8 +1012,9 @@ fn load_client(path: &std::path::Path) -> Result<OAuthClient> {(Some(client_id), Some(client_secret)) => Ok(OAuthClient {client_id: client_id.to_string(),client_secret: client_secret.to_string(),+ builtin: false,}),- _ => Err(Error::engine(format!(+ _ => Err(SignInError::failed(format!("{} has no client_id and client_secret.",path.display()))),@@ -886,7 +1066,7 @@ fn check_private(path: &std::path::Path) -> Result<()> {.mode()& 0o777;if mode & 0o077 != 0 {- return Err(Error::engine(format!(+ return Err(SignInError::failed(format!("The token file {} is accessible to other users (mode {mode:04o}); run \`chmod 600` on it, or delete it and sign in again.",path.display()@@ -904,13 +1084,13 @@ fn load_tokens(path: &std::path::Path) -> Result<Option<Tokens>> {}check_private(path)?;let raw = std::fs::read_to_string(path).map_err(|e| {- Error::engine(format!(+ SignInError::failed(format!("Cannot read the token file {}: {e}",path.display()))})?;let document: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {- Error::engine(format!(+ SignInError::failed(format!("Cannot read the token file {}: {e}",path.display()))@@ -1012,7 +1192,7 @@ enum TokenRequestError {impl From<TokenRequestError> for Error {fn from(e: TokenRequestError) -> Self {match e {- TokenRequestError::Refused(r) => Error::engine(format!(+ TokenRequestError::Refused(r) => SignInError::failed(format!("Google refused the request: {}{}.",r.code,r.detail()@@ -1101,7 +1281,7 @@ async fn refresh_tokens({Ok(payload) => payload,Err(TokenRequestError::Refused(r)) if r.code == "invalid_grant" => {- return Err(Error::engine(format!(+ return Err(SignInError::required(format!("Google refused the stored sign-in: invalid_grant{}. The consent may have \expired (seven days for a client in Testing status), or the access was \revoked. Sign in again.",@@ -1109,7 +1289,7 @@ async fn refresh_tokens()));}Err(TokenRequestError::Refused(r)) if is_client_refusal(&r.code) => {- return Err(Error::engine(format!(+ return Err(SignInError::required(format!("Google no longer accepts the OAuth client this sign-in used: {}{}. It was \deleted or disabled, or its secret changed. Sign in again with a working \Desktop app client of your own.",@@ -1483,11 +1663,11 @@ async fn run_consent(if let Some(error) = params.get("error") {if error == "access_denied" {- return Err(Error::engine(+ return Err(SignInError::failed("The sign-in was cancelled on the consent screen.",));}- return Err(Error::engine(format!(+ return Err(SignInError::failed(format!("Google refused the sign-in: {error}.")));}@@ -1495,14 +1675,14 @@ async fn run_consent(params.get("state").map(String::as_str).unwrap_or(""),&state,) {- return Err(Error::engine(+ return Err(SignInError::failed("The redirect does not belong to this sign-in (its state does not match); \nothing was stored. Start the sign-in again.",));}let code = params.get("code").map(String::as_str).unwrap_or("");if code.is_empty() {- return Err(Error::engine(+ return Err(SignInError::failed("Google's redirect carried no authorization code.",));}@@ -1522,12 +1702,21 @@ async fn run_consent({Ok(payload) => Ok(payload),Err(TokenRequestError::Refused(r)) if is_client_refusal(&r.code) => {- Err(Error::engine(format!(- "Google refused the OAuth client in the client file: {}. Download the \- current JSON of the Desktop app client (its secret may have been reset) \- and sign in again (see {OWN_CLIENT_DOCS}).",- r.code- )))+ Err(SignInError::failed(if client_cfg.builtin {+ format!(+ "Google refused CocoIndex's built-in OAuth client: {}. Upgrade CocoIndex \+ and sign in again, or sign in with a Desktop app OAuth client of your \+ own (see {OWN_CLIENT_DOCS}).",+ r.code+ )+ } else {+ format!(+ "Google refused the OAuth client in the client file: {}. Download the \+ current JSON of the Desktop app client (its secret may have been reset) \+ and sign in again.",+ r.code+ )+ }))}Err(e) => Err(e.into()),}@@ -1576,13 +1765,12 @@ impl UserAccount {/// Sign in interactively with a Desktop-app OAuth client; the account's/// address. `client_secrets_path` is the JSON downloaded for a client of- /// your own (see the docs linked from the error when it is unusable).- /// Opens the consent page in the browser, or prints the link when this- /// host has none, and stores the tokens readable by this user only.- pub async fn sign_in(- &self,- client_secrets_path: impl AsRef<std::path::Path>,- ) -> Result<String> {+ /// your own (see the docs linked from the error when it is unusable);+ /// `None` takes the client built into this release, and fails as a+ /// [`SignInError`] when the build has none. Opens the consent page in the+ /// browser, or prints the link when this host has none, and stores the+ /// tokens readable by this user only.+ pub async fn sign_in(&self, client_secrets_path: Option<&std::path::Path>) -> Result<String> {self.sign_in_with(client_secrets_path, SignInOptions::default()).await}@@ -1591,15 +1779,15 @@ impl UserAccount {/// [`SignInOptions`], so a test can drive the flow against fake endpoints.pub async fn sign_in_with(&self,- client_secrets_path: impl AsRef<std::path::Path>,+ client_secrets_path: Option<&std::path::Path>,options: SignInOptions,) -> Result<String> {- let client_cfg = load_client(client_secrets_path.as_ref())?;+ let client_cfg = resolve_client(client_secrets_path)?;let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).connect_timeout(Duration::from_secs(10)).build()- .map_err(|e| Error::engine(format!("http client: {e}")))?;+ .map_err(|e| SignInError::failed(format!("http client: {e}")))?;let payload = run_consent(&client_cfg, &self.endpoints, &http, &options).await?;let granted: Vec<&str> = payload.get("scope")@@ -1608,7 +1796,7 @@ impl UserAccount {.split_whitespace().collect();if !granted.is_empty() && !granted.contains(&DRIVE_READONLY_SCOPE) {- return Err(Error::engine(+ return Err(SignInError::failed("The consent did not grant read access to Google Drive; sign in again and \keep the Drive permission selected.",));@@ -1618,7 +1806,7 @@ impl UserAccount {.and_then(|v| v.as_str()).filter(|s| !s.is_empty())else {- return Err(Error::engine(+ return Err(SignInError::failed("Google returned no refresh token, so the sign-in could not be kept. Remove \the app at https://myaccount.google.com/permissions and sign in again.",));@@ -1676,10 +1864,9 @@ impl UserAccount {fn tokens(&self) -> Result<Tokens> {load_tokens(&self.token_path)?.ok_or_else(|| {- Error::engine(format!(+ SignInError::required(format!("No usable Google sign-in is stored at {}. Sign in once with \- `UserAccount::sign_in(client_secret.json)` or \- `cocoindex google-drive sign-in <client_secret.json>`.",+ `cocoindex google-drive sign-in` or `UserAccount::sign_in(..)`.",self.token_path.display()))})@@ -1757,7 +1944,11 @@ impl GoogleDriveSource {if !seen_folders.insert(folder_id.clone()) {continue; // guard against cycles / shortcuts}- for mut file in self.client.list_children(&folder_id).await? {+ // Sorting the children makes the path kept for a file with several+ // parents (the first one seen) the same every run.+ let mut children = self.client.list_children(&folder_id).await?;+ children.sort_by(|a, b| (&a.name, &a.file_id).cmp(&(&b.name, &b.file_id)));+ for mut file in children {let path = if prefix.is_empty() {file.name.clone()} else {diff --git a/rust/sdk/cocoindex/tests/gdrive_source.rs b/rust/sdk/cocoindex/tests/gdrive_source.rsindex 21fa57be..2f93ea36 100644--- a/rust/sdk/cocoindex/tests/gdrive_source.rs+++ b/rust/sdk/cocoindex/tests/gdrive_source.rs@@ -229,3 +229,122 @@ async fn gdrive_drive_file_uses_shared_cached_filelike_reads() {assert_eq!(file.read_text().await.unwrap(), "cached text");assert_eq!(file.read_text().await.unwrap(), "cached text");}++/// A listing that fails with a 503, then a 429, then a rate-limit 403, is+/// retried until it succeeds; another 403 is not retried.+#[tokio::test]+async fn gdrive_retries_server_errors_and_rate_limits() {+ use std::sync::Arc;+ use std::sync::atomic::{AtomicUsize, Ordering};+ use wiremock::{Request, Respond};++ struct Flaky(Arc<AtomicUsize>);+ impl Respond for Flaky {+ fn respond(&self, _: &Request) -> ResponseTemplate {+ match self.0.fetch_add(1, Ordering::SeqCst) {+ 0 => ResponseTemplate::new(503),+ 1 => ResponseTemplate::new(429),+ 2 => ResponseTemplate::new(403).set_body_json(serde_json::json!({+ "error": {"errors": [{"reason": "userRateLimitExceeded"}], "code": 403}+ })),+ _ => ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "files": [{+ "id": "txt-1", "name": "root.txt", "mimeType": "text/plain",+ "size": "7", "modifiedTime": "2026-01-02T00:00:00Z"+ }]+ })),+ }+ }+ }++ let server = MockServer::start().await;+ let attempts = Arc::new(AtomicUsize::new(0));+ Mock::given(method("GET"))+ .and(path("/files"))+ .respond_with(Flaky(attempts.clone()))+ .mount(&server)+ .await;+ let client = GoogleDriveClient::from_static_token("test-token").with_base_url(server.uri());+ let files = GoogleDriveSource::new(client, vec!["root".to_string()])+ .list_files()+ .await+ .unwrap();+ assert_eq!(files.len(), 1);+ assert_eq!(+ attempts.load(Ordering::SeqCst),+ 4,+ "three retried failures, then success"+ );++ // A 403 that is not a rate limit is the caller's problem: no retry.+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/files"))+ .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({+ "error": {"errors": [{"reason": "insufficientFilePermissions"}], "code": 403}+ })))+ .expect(1)+ .mount(&server)+ .await;+ let client = GoogleDriveClient::from_static_token("test-token").with_base_url(server.uri());+ let err = match GoogleDriveSource::new(client, vec!["root".to_string()])+ .list_files()+ .await+ {+ Ok(_) => panic!("a permission error is not retried into a success"),+ Err(err) => err,+ };+ assert!(err.to_string().contains("403"), "{err}");+}++/// Drive lists children in no set order; the source sorts them by name and+/// id, so a file reachable through two folders keeps the same path every run.+#[tokio::test]+async fn gdrive_sorts_children_so_paths_are_stable() {+ let server = MockServer::start().await;+ // Two folders under the root, listed in reverse order; the same file is in+ // both. Sorted, "alpha" comes first, so the file's path is under it.+ Mock::given(method("GET"))+ .and(path("/files"))+ .and(query_param("q", "'root' in parents and trashed = false"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "files": [+ {"id": "f-zulu", "name": "zulu", "mimeType": FOLDER_MIME, "modifiedTime": "2026-01-01T00:00:00Z"},+ {"id": "f-alpha", "name": "alpha", "mimeType": FOLDER_MIME, "modifiedTime": "2026-01-01T00:00:00Z"}+ ]+ })))+ .mount(&server)+ .await;+ for folder in ["f-zulu", "f-alpha"] {+ Mock::given(method("GET"))+ .and(path("/files"))+ .and(query_param("q", format!("'{folder}' in parents and trashed = false")))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "files": [+ {"id": "shared", "name": "shared.txt", "mimeType": "text/plain", "size": "1", "modifiedTime": "2026-01-01T00:00:00Z"},+ {"id": "b", "name": "same-name.txt", "mimeType": "text/plain", "size": "1", "modifiedTime": "2026-01-01T00:00:00Z"},+ {"id": "a", "name": "same-name.txt", "mimeType": "text/plain", "size": "1", "modifiedTime": "2026-01-01T00:00:00Z"}+ ]+ })))+ .mount(&server)+ .await;+ }+ let client = GoogleDriveClient::from_static_token("test-token").with_base_url(server.uri());+ let files = GoogleDriveSource::new(client, vec!["root".to_string()])+ .list_files()+ .await+ .unwrap();+ let listed: Vec<(String, String)> = files+ .iter()+ .map(|f| (f.file_id.clone(), f.path().to_string()))+ .collect();+ assert_eq!(+ listed,+ vec![+ ("a".to_string(), "alpha/same-name.txt".to_string()),+ ("b".to_string(), "alpha/same-name.txt".to_string()),+ ("shared".to_string(), "alpha/shared.txt".to_string()),+ ],+ "sorted by (name, id) within a folder; the shared file keeps the path of the first folder by name"+ );+}diff --git a/rust/sdk/cocoindex/tests/gdrive_user_account.rs b/rust/sdk/cocoindex/tests/gdrive_user_account.rsindex 165c166b..c6d01aee 100644--- a/rust/sdk/cocoindex/tests/gdrive_user_account.rs+++ b/rust/sdk/cocoindex/tests/gdrive_user_account.rs@@ -12,7 +12,7 @@ use std::time::Duration;use base64::Engine as _;use cocoindex::connectors::gdrive::{- GoogleDriveClient, GoogleDriveSource, GoogleEndpoints, SignInOptions, UserAccount,+ GoogleDriveClient, GoogleDriveSource, GoogleEndpoints, SignInError, SignInOptions, UserAccount,};use sha2::Digest;use wiremock::matchers::{body_string_contains, header, method, path, query_param};@@ -260,7 +260,7 @@ async fn sign_in_round_trip_stores_the_python_token_file() {assert!(!account.is_signed_in());let email = account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();assert_eq!(email, EMAIL);@@ -340,7 +340,7 @@ async fn without_a_browser_the_link_is_printed_and_the_redirect_pasted_back() {..flow.options()};let email = account- .sign_in_with(&flow.client_secrets, options)+ .sign_in_with(Some(&flow.client_secrets), options).await.unwrap();assert_eq!(email, EMAIL);@@ -364,7 +364,7 @@ async fn a_redirect_with_another_state_is_refused_and_nothing_is_stored() {..flow.options()};let err = account- .sign_in_with(&flow.client_secrets, options)+ .sign_in_with(Some(&flow.client_secrets), options).await.unwrap_err();assert!(err.to_string().contains("state does not match"), "{err}");@@ -383,7 +383,7 @@ async fn a_cancelled_consent_is_reported() {};let err = flow.account()- .sign_in_with(&flow.client_secrets, options)+ .sign_in_with(Some(&flow.client_secrets), options).await.unwrap_err();assert!(err.to_string().contains("cancelled"), "{err}");@@ -400,13 +400,13 @@ async fn a_web_client_or_a_missing_client_file_is_refused() {.unwrap();let err = flow.account()- .sign_in_with(&web, flow.options())+ .sign_in_with(Some(&web), flow.options()).await.unwrap_err();assert!(err.to_string().contains("Web application client"), "{err}");let err = flow.account()- .sign_in_with(flow.dir.path().join("missing.json"), flow.options())+ .sign_in_with(Some(&flow.dir.path().join("missing.json")), flow.options()).await.unwrap_err();assert!(err.to_string().contains("No OAuth client file"), "{err}");@@ -418,7 +418,7 @@ async fn an_expired_access_token_is_refreshed_and_the_file_updated() {let flow = Flow::start().await;let account = flow.account();account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();// Expire the stored access token, as a run the next day would find it.@@ -465,7 +465,7 @@ async fn a_revoked_sign_in_asks_to_sign_in_again_without_leaking_tokens() {let flow = Flow::start().await;let account = flow.account();account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();let mut file = token_file(&flow.token_path());@@ -493,7 +493,7 @@ async fn sign_out_revokes_and_deletes() {let flow = Flow::start().await;let account = flow.account();account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();assert!(account.sign_out().await.unwrap());@@ -516,7 +516,7 @@ async fn sign_out_revokes_and_deletes() {async fn sign_out_deletes_the_file_even_when_google_is_unreachable() {let flow = Flow::start().await;flow.account()- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();let unreachable =@@ -535,7 +535,7 @@ async fn a_token_file_readable_by_others_is_refused() {let flow = Flow::start().await;let account = flow.account();account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();std::fs::set_permissions(flow.token_path(), std::fs::Permissions::from_mode(0o644)).unwrap();@@ -549,7 +549,7 @@ async fn a_token_file_of_another_version_means_signing_in_again() {let flow = Flow::start().await;let account = flow.account();account- .sign_in_with(&flow.client_secrets, flow.options())+ .sign_in_with(Some(&flow.client_secrets), flow.options()).await.unwrap();let mut file = token_file(&flow.token_path());@@ -575,3 +575,57 @@ async fn a_run_without_a_sign_in_says_how_to_sign_in() {"{err}");}++/// Without a client file, the sign-in takes the client built into the crate;+/// this build has none, and says how to sign in instead, as a `SignInError`.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_build_without_a_builtin_client_asks_for_a_client_file() {+ let flow = Flow::start().await;+ let err = flow+ .account()+ .sign_in_with(None, flow.options())+ .await+ .unwrap_err();+ let sign_in = SignInError::of(&err).expect("a typed sign-in error");+ assert!(+ matches!(sign_in, SignInError::Failed(message) if message.contains("no built-in OAuth client")),+ "{err}"+ );+ assert!(+ flow.opened.lock().unwrap().is_empty(),+ "no consent page was opened"+ );+ assert!(!flow.token_path().exists());+}++/// The errors a run meets are typed: no stored sign-in is `SignInRequired`,+/// an unusable client file is `Failed`, and a plain engine error is neither.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn sign_in_errors_are_typed() {+ let dir = tempfile::tempdir().unwrap();+ let account = UserAccount::with_token_path(dir.path().join("none.json"));+ let err = GoogleDriveClient::from_user_account(&account)+ .err()+ .unwrap();+ assert!(+ matches!(SignInError::of(&err), Some(SignInError::SignInRequired(_))),+ "{err}"+ );+ assert_eq!(+ SignInError::of(&err).unwrap().message(),+ err.to_string(),+ "the error displays as its message"+ );++ let flow = Flow::start().await;+ let err = flow+ .account()+ .sign_in_with(Some(&flow.dir.path().join("missing.json")), flow.options())+ .await+ .unwrap_err();+ assert!(+ matches!(SignInError::of(&err), Some(SignInError::Failed(_))),+ "{err}"+ );+ assert!(SignInError::of(&cocoindex::Error::engine("other")).is_none());+}