Skip to main content

omni_dev/drive/sheets/
client.rs

1//! Sheets v4 REST API client.
2//!
3//! A typed wrapper around [`GoogleApiClient`] — the same transport
4//! `DriveClient` uses — pinned to `sheets.googleapis.com`. Everything
5//! interesting (OAuth session, 401 refresh-and-retry, quota backoff,
6//! request logging, error-envelope parsing) is inherited, so this module is
7//! only a default host, an env override, and a distinct *type*.
8//!
9//! That distinct type is the point, not incidental: `FilesApi::new` takes a
10//! `&DriveClient`, so a Sheets-hosted client cannot be handed to it and
11//! silently issue `/drive/v3/files` against the Sheets host. A shared
12//! `DriveClient` re-based onto a second URL would compile.
13
14use anyhow::Result;
15
16use crate::drive::api_client::GoogleApiClient;
17use crate::drive::auth::DriveCredentials;
18use crate::drive::client::{DriveClient, SERVICE_TAG};
19use crate::utils::env::{EnvSource, SystemEnv};
20
21/// Environment variable overriding the Sheets API host wholesale.
22///
23/// Mirrors `DRIVE_API_URL`/`GMAIL_API_URL`; process-env only, never written
24/// to `settings.json`. Used to point at a wiremock server or route through a
25/// forced egress proxy.
26pub const SHEETS_API_URL: &str = "SHEETS_API_URL";
27
28/// Human-readable API name for Sheets error messages.
29///
30/// The request-log tag stays `SERVICE_TAG` (`"drive"`) so one feature's
31/// traffic is not split across two services; only the *message* differs.
32const API_NAME: &str = "Sheets";
33
34/// HTTP client for the Sheets v4 REST API.
35pub struct SheetsClient {
36    inner: GoogleApiClient,
37}
38
39impl std::fmt::Debug for SheetsClient {
40    // Hand-written for the same reason `DriveClient`'s is: never mention the
41    // session, rather than trusting every nested `Secret` to stay wrapped.
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("SheetsClient")
44            .field("base_url", &self.inner.base_url())
45            .finish_non_exhaustive()
46    }
47}
48
49impl SheetsClient {
50    /// The real Sheets API host.
51    ///
52    /// Unlike Drive — which lives on the general `www.googleapis.com` with a
53    /// `/drive/v3/...` prefix — Sheets has its own subdomain, so no base-URL
54    /// tweak to `DriveClient` could ever reach it.
55    const DEFAULT_BASE_URL: &'static str = "https://sheets.googleapis.com";
56
57    /// Builds a client against `base_url` with already-loaded credentials.
58    ///
59    /// Prefer [`Self::from_drive_client`] when a `DriveClient` is already in
60    /// hand: this constructor opens a *second* OAuth session, which means a
61    /// second token refresh per invocation.
62    pub fn new(base_url: &str, credentials: &DriveCredentials) -> Result<Self> {
63        Ok(Self {
64            inner: GoogleApiClient::new(base_url, credentials, SERVICE_TAG, API_NAME)?,
65        })
66    }
67
68    /// Derives a Sheets client from a Drive client, sharing its OAuth session
69    /// and connection pool.
70    ///
71    /// This is the constructor every real caller wants. A `sheets write` has
72    /// to talk to *both* APIs — Drive for `files.get` and the ancestor-chain
73    /// walk that feeds the write gate, Sheets for the cells — and two
74    /// independent sessions would refresh the same refresh token twice for
75    /// one command.
76    ///
77    /// Honours `SHEETS_API_URL`; the Drive client's own base URL is
78    /// irrelevant here, since the two hosts are unrelated.
79    pub fn from_drive_client(drive: &DriveClient) -> Result<Self> {
80        Self::from_drive_client_with(&SystemEnv, drive)
81    }
82
83    /// [`from_drive_client`](Self::from_drive_client) over an injected
84    /// [`EnvSource`], so tests can exercise the `SHEETS_API_URL` override via
85    /// `MapEnv` without mutating the process environment.
86    pub(crate) fn from_drive_client_with(
87        env: &impl EnvSource,
88        drive: &DriveClient,
89    ) -> Result<Self> {
90        let base_url = Self::resolve_base_url(env);
91        Ok(Self {
92            inner: drive.transport().derived(&base_url, SERVICE_TAG, API_NAME),
93        })
94    }
95
96    fn resolve_base_url(env: &impl EnvSource) -> String {
97        env.var(SHEETS_API_URL)
98            .filter(|s| !s.is_empty())
99            .unwrap_or_else(|| Self::DEFAULT_BASE_URL.to_string())
100    }
101
102    /// Returns the API base URL (without trailing slash).
103    #[must_use]
104    pub fn base_url(&self) -> &str {
105        self.inner.base_url()
106    }
107
108    /// The shared transport, for the `SheetsApi` façade's requests.
109    pub(in crate::drive) fn transport(&self) -> &GoogleApiClient {
110        &self.inner
111    }
112}
113
114#[cfg(test)]
115#[allow(clippy::unwrap_used, clippy::expect_used)]
116mod tests {
117    use super::*;
118    use crate::drive::auth::DriveGrantedScopes;
119    use crate::test_support::env::MapEnv;
120    use crate::utils::secret::Secret;
121
122    fn test_credentials() -> DriveCredentials {
123        DriveCredentials {
124            client_id: "client-1".to_string(),
125            client_secret: Secret::new("secret-1"),
126            refresh_token: Secret::new("refresh-1"),
127            scope: DriveGrantedScopes::READONLY,
128        }
129    }
130
131    fn drive_client() -> DriveClient {
132        DriveClient::new("https://www.googleapis.com", &test_credentials()).unwrap()
133    }
134
135    #[test]
136    fn derives_the_real_sheets_host_by_default() {
137        // Via a fresh MapEnv, not the real SystemEnv — a stray
138        // SHEETS_API_URL in the process environment must not make this
139        // flaky (mirrors the Drive/Gmail precedent).
140        let sheets = SheetsClient::from_drive_client_with(&MapEnv::new(), &drive_client()).unwrap();
141        assert_eq!(sheets.base_url(), "https://sheets.googleapis.com");
142    }
143
144    #[test]
145    fn honours_the_sheets_api_url_override() {
146        let env = MapEnv::new().with(SHEETS_API_URL, "http://127.0.0.1:9/sheets");
147        let sheets = SheetsClient::from_drive_client_with(&env, &drive_client()).unwrap();
148        assert_eq!(sheets.base_url(), "http://127.0.0.1:9/sheets");
149    }
150
151    #[test]
152    fn ignores_an_empty_sheets_api_url_override() {
153        let env = MapEnv::new().with(SHEETS_API_URL, "");
154        let sheets = SheetsClient::from_drive_client_with(&env, &drive_client()).unwrap();
155        assert_eq!(sheets.base_url(), "https://sheets.googleapis.com");
156    }
157
158    #[test]
159    fn deriving_does_not_disturb_the_drive_client_host() {
160        let drive = drive_client();
161        let _sheets = SheetsClient::from_drive_client_with(&MapEnv::new(), &drive).unwrap();
162        assert_eq!(drive.base_url(), "https://www.googleapis.com");
163    }
164
165    #[test]
166    fn new_strips_a_trailing_slash() {
167        let sheets =
168            SheetsClient::new("https://sheets.googleapis.com/", &test_credentials()).unwrap();
169        assert_eq!(sheets.base_url(), "https://sheets.googleapis.com");
170    }
171
172    #[tokio::test]
173    async fn a_sheets_failure_names_sheets_not_drive() {
174        // Regression guard for the message a new user is most likely to
175        // hit: a `drive.file` grant cannot write a Sheet created in the
176        // browser, and the resulting 403 previously announced itself as a
177        // *Drive* failure — sending the reader to the wrong API's docs.
178        let server = wiremock::MockServer::start().await;
179        wiremock::Mock::given(wiremock::matchers::method("GET"))
180            .and(wiremock::matchers::path("/boom"))
181            .respond_with(
182                wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
183                    "error": {"code": 403, "message": "The caller does not have permission",
184                              "status": "PERMISSION_DENIED"},
185                })),
186            )
187            .mount(&server)
188            .await;
189        let response = reqwest::get(format!("{}/boom", server.uri()))
190            .await
191            .unwrap();
192
193        let err = GoogleApiClient::response_to_error(API_NAME, response).await;
194        let text = err.to_string();
195        assert!(text.starts_with("Sheets API request failed"), "{text}");
196        assert!(!text.contains("Drive API request failed"), "{text}");
197    }
198
199    #[test]
200    fn debug_never_mentions_the_session_or_a_secret() {
201        let sheets = SheetsClient::from_drive_client_with(&MapEnv::new(), &drive_client()).unwrap();
202        let debug = format!("{sheets:?}");
203        assert!(debug.contains("SheetsClient"));
204        assert!(!debug.contains("session"));
205        assert!(!debug.contains("secret-1"));
206        assert!(!debug.contains("refresh-1"));
207    }
208}