grr-cli 0.4.0

Google tools from the terminal, at maximum performance: zero-config Gmail, Calendar, Drive, Contacts, Chat and Forms over HTTP/3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Service-agnostic HTTP core: one authenticated transport for every
//! Google API client (Gmail, Calendar, Drive, Contacts, Chat, Forms).
//!
//! Zero-config by construction: all tuning is compile-time constants.
//! tokio sizes OS threads to cores; the semaphore bounds only in-flight
//! HTTP requests so bursts stay under Google's per-user rate limits.

use std::sync::Arc;
use std::time::Duration;

use reqwest::Client as ReqwestClient;
use reqwest::header::{ACCEPT_ENCODING, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
use serde::de::DeserializeOwned;
use tokio::sync::Semaphore;
use tracing::{debug, info, warn};
use url::Url;

use crate::core::auth::GoogleAuth;
use crate::core::error::{GrrError, Result, api_error};

// ── Auto-tuned transport constants ────────────────────────────────────────

/// Hard ceiling on in-flight HTTP requests. Google's per-user rate limits
/// (not CPU) are the scarce resource; exceeding this burns quota into 429s.
pub(crate) const MAX_INFLIGHT_REQUESTS: usize = 64;
/// Whole-request timeout (includes server processing time).
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// TCP+TLS establishment only.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Idle keepalive connections per host for instant reuse.
const POOL_IDLE_PER_HOST: usize = 32;
const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(90);
const TCP_KEEPALIVE: Duration = Duration::from_secs(60);
const H2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
/// Transient-failure retries (connect/timeout/5xx/429).
const RETRY_ATTEMPTS: u32 = 3;
/// Exponential backoff base; grows 100ms -> 200ms -> 400ms.
const RETRY_BACKOFF_MS: u64 = 100;
/// Never sleep longer than this honoring a 429 Retry-After mid-command.
const MAX_RATE_LIMIT_WAIT: Duration = Duration::from_secs(30);

#[derive(Default)]
pub(crate) struct QueryParams {
    values: Vec<(String, String)>,
}

impl QueryParams {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn add(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.values.push((key.into(), value.into()));
        self
    }

    pub(crate) fn add_optional(
        mut self,
        key: impl Into<String>,
        value: Option<impl Into<String>>,
    ) -> Self {
        if let Some(value) = value {
            self.values.push((key.into(), value.into()));
        }
        self
    }

    pub(crate) fn add_page_token(self, token: Option<&str>) -> Self {
        self.add_optional("pageToken", token)
    }

    pub(crate) fn apply(self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        request.query(&self.values)
    }
}

pub(crate) fn parse_url(raw: &str, kind: &str) -> Result<Url> {
    Url::parse(raw).map_err(|error| GrrError::Config(format!("Invalid {kind} URL: {error}")))
}

pub(crate) fn join_url(base: &Url, path: &str, kind: &str) -> Result<Url> {
    base.join(path)
        .map_err(|error| GrrError::Config(format!("Invalid {kind} URL: {error}")))
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum TransportMode {
    Http3PriorKnowledge,
    Http2PriorKnowledge,
}

pub fn resolve_transport_mode(use_http3: bool) -> TransportMode {
    if use_http3 {
        TransportMode::Http3PriorKnowledge
    } else {
        TransportMode::Http2PriorKnowledge
    }
}

#[derive(Debug, Clone)]
pub struct TransportInfo {
    pub negotiated_version: String,
    pub http3_requested: bool,
    pub http3_effective: bool,
    pub fell_back: bool,
}

impl Default for TransportInfo {
    fn default() -> Self {
        Self {
            negotiated_version: "not-probed".into(),
            http3_requested: true,
            http3_effective: false,
            fell_back: false,
        }
    }
}

/// The shared authenticated HTTP engine behind every service client.
///
/// Owns the reqwest client, the in-flight request valve, and the retry
/// executor (429 Retry-After, transient 5xx, fast-fail 401/403/404).
/// Service clients build URLs from their own base and hand requests to
/// [`HttpCore::execute`].
#[derive(Clone)]
pub struct HttpCore {
    auth: Arc<GoogleAuth>,
    http_client: ReqwestClient,
    semaphore: Arc<Semaphore>,
    transport_info: TransportInfo,
}

impl HttpCore {
    /// Build the core, probing the negotiated HTTP version against the
    /// service base URL (any authenticated probe path works; a dead
    /// stored token must not brick construction — `grr auth login`
    /// recovers without one).
    pub async fn connect(auth: GoogleAuth, base_url: &Url, probe_path: &str) -> Result<Self> {
        let mut info = TransportInfo {
            http3_requested: true,
            http3_effective: true,
            ..TransportInfo::default()
        };
        let mut http_client = build_http_client()?;

        match probe(
            &http_client,
            base_url,
            &auth,
            reqwest::Version::HTTP_3,
            probe_path,
        )
        .await
        {
            Ok(version) => info.negotiated_version = version,
            Err(GrrError::Auth(error)) => return Err(GrrError::Auth(error)),
            Err(error) => {
                warn!("HTTP/3 probe failed ({error}); rebuilding with HTTP/2");
                info.http3_effective = false;
                info.fell_back = true;
                http_client = build_http_client_with_mode(TransportMode::Http2PriorKnowledge)?;
                match probe(
                    &http_client,
                    base_url,
                    &auth,
                    reqwest::Version::HTTP_2,
                    probe_path,
                )
                .await
                {
                    Ok(version) => info.negotiated_version = version,
                    Err(error) => {
                        warn!("HTTP/2 probe failed ({error}); continuing unprobed");
                        info.negotiated_version = "not-probed".into();
                    }
                }
            }
        }

        info!(
            "HttpCore connected (probe {}: {}): http3_effective={}, max_inflight_requests={}",
            probe_path, info.negotiated_version, info.http3_effective, MAX_INFLIGHT_REQUESTS
        );

        Ok(Self {
            auth: Arc::new(auth),
            http_client,
            semaphore: Arc::new(Semaphore::new(MAX_INFLIGHT_REQUESTS)),
            transport_info: info,
        })
    }

    /// Core assembled without probing (test injection: custom client, mock
    /// base URLs).
    pub fn unprobed(auth: GoogleAuth, http_client: ReqwestClient) -> Self {
        Self {
            auth: Arc::new(auth),
            http_client,
            semaphore: Arc::new(Semaphore::new(MAX_INFLIGHT_REQUESTS)),
            transport_info: TransportInfo {
                negotiated_version: "not-probed".into(),
                http3_requested: true,
                http3_effective: false,
                fell_back: false,
            },
        }
    }

    /// Start a GET request against an absolute URL.
    pub fn get(&self, url: Url) -> reqwest::RequestBuilder {
        self.http_client.get(url)
    }

    /// Start a POST request against an absolute URL.
    pub fn post(&self, url: Url) -> reqwest::RequestBuilder {
        self.http_client.post(url)
    }

    /// Start a PUT request against an absolute URL.
    pub fn put(&self, url: Url) -> reqwest::RequestBuilder {
        self.http_client.put(url)
    }

    /// Start a PATCH request against an absolute URL.
    pub fn patch(&self, url: Url) -> reqwest::RequestBuilder {
        self.http_client.patch(url)
    }

    /// Start a DELETE request against an absolute URL.
    pub fn delete(&self, url: Url) -> reqwest::RequestBuilder {
        self.http_client.delete(url)
    }

    /// The underlying reqwest client (multipart uploads, raw control).
    pub fn http_client(&self) -> &ReqwestClient {
        &self.http_client
    }

    /// Shared Google OAuth handle (login, device flow, token backend).
    pub fn auth(&self) -> &GoogleAuth {
        &self.auth
    }

    /// Transport negotiation details observed during connection.
    pub fn transport_info(&self) -> &TransportInfo {
        &self.transport_info
    }

    /// Execute a request: bearer auth, HTTP/3 version pinning, in-flight
    /// valve, and the retry policy (429 Retry-After honored up to
    /// [`MAX_RATE_LIMIT_WAIT`]; 401 fails fast with a `grr auth login`
    /// hint; transient errors back off exponentially).
    pub async fn execute(&self, mut request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
        let _permit = self
            .semaphore
            .acquire()
            .await
            .map_err(|_| GrrError::Internal("Semaphore closed".into()))?;

        let token = self.auth.get_access_token().await?;
        request = request.header(AUTHORIZATION, format!("Bearer {}", token));
        request = apply_transport_version(request, self.transport_info.http3_effective);

        let mut pending = Some(request);
        let mut last_error = None;

        for attempt in 0..=RETRY_ATTEMPTS {
            // Streaming bodies are non-replayable: try_clone() yields None and
            // only one send attempt is possible, so the builder is consumed.
            let to_send = match pending.take() {
                None => break,
                Some(builder) => match builder.try_clone() {
                    Some(replayable) => {
                        pending = Some(builder);
                        replayable
                    }
                    None => builder,
                },
            };

            let response = to_send.send().await;

            match response {
                Ok(resp) => {
                    let status = resp.status();

                    if status.is_success() {
                        return Ok(resp);
                    }

                    match status.as_u16() {
                        401 => {
                            // The bearer token above was fetched once before
                            // this loop, so retrying re-sends the same stale
                            // credential and can never succeed — and clearing
                            // storage would drop callers into the implicit
                            // OAuth flow mid-request. Fail fast instead.
                            return Err(GrrError::Auth(
                                "request rejected as unauthorized (401); \
                                 your access token is expired or invalid — \
                                 rerun `grr auth login`"
                                    .into(),
                            ));
                        }
                        429 => {
                            // Rate limited. Honor the server's Retry-After and
                            // keep going when the wait is short; surface the
                            // wait immediately when it is not.
                            let retry_after = resp
                                .headers()
                                .get("retry-after")
                                .and_then(|h| h.to_str().ok())
                                .and_then(|s| s.parse::<u64>().ok())
                                .unwrap_or(60);
                            let wait = Duration::from_secs(retry_after);
                            if attempt < RETRY_ATTEMPTS && wait <= MAX_RATE_LIMIT_WAIT {
                                warn!(
                                    "rate limited; honoring Retry-After of {retry_after}s \
                                     (attempt {}/{})",
                                    attempt + 1,
                                    RETRY_ATTEMPTS
                                );
                                tokio::time::sleep(wait).await;
                                continue;
                            }
                            return Err(GrrError::RateLimited {
                                retry_after_secs: retry_after,
                            });
                        }
                        403 => {
                            return Err(GrrError::PermissionDenied(
                                "Insufficient permissions for this API or scope \
                                 (was the API enabled in Google Cloud, and does \
                                 your login include its scope? rerun `grr auth login` \
                                 to grant new scopes)"
                                    .into(),
                            ));
                        }
                        404 => {
                            return Err(GrrError::NotFound("Resource not found".into()));
                        }
                        500..=599 => {
                            let body = resp.text().await.unwrap_or_default();
                            last_error = Some(api_error(status.as_u16(), &body));
                        }
                        _ => {
                            let error_text = resp.text().await.unwrap_or_default();
                            return Err(api_error(status.as_u16(), &error_text));
                        }
                    }
                }
                Err(e) => {
                    if e.is_timeout() || e.is_connect() || e.is_request() {
                        last_error = Some(GrrError::Http(e));
                    } else {
                        return Err(GrrError::Http(e));
                    }
                }
            }

            if attempt < RETRY_ATTEMPTS {
                let backoff = RETRY_BACKOFF_MS * (2_u64.pow(attempt));
                debug!(
                    "Request failed, retrying in {:?} (attempt {}/{})",
                    backoff,
                    attempt + 1,
                    RETRY_ATTEMPTS
                );
                tokio::time::sleep(Duration::from_millis(backoff)).await;
            }
        }

        Err(last_error.unwrap_or_else(|| GrrError::Internal("Max retries exceeded".into())))
    }

    pub(crate) async fn execute_json<T>(&self, request: reqwest::RequestBuilder) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let response = self.execute(request).await?;
        Ok(response.json().await?)
    }
}

/// Apply the transport-level HTTP version override for data-plane requests.
///
/// reqwest only routes an individual request over HTTP/3 when the request
/// itself carries `version(HTTP_3)`; client-level `http3_prior_knowledge()`
/// merely builds the QUIC connector. When h3 is effective, every API request
/// must be explicitly versioned or it silently rides TCP.
pub fn apply_transport_version(
    builder: reqwest::RequestBuilder,
    http3_effective: bool,
) -> reqwest::RequestBuilder {
    if http3_effective {
        builder.version(reqwest::Version::HTTP_3)
    } else {
        builder
    }
}

/// Probe the negotiated HTTP version with a real authenticated request.
///
/// Any HTTP response — even a 404/401 — proves the transport negotiated
/// (some services, e.g. Forms, have no cheap "list" endpoint to hit).
/// Only transport-level failures (connect/timeout) fail the probe.
async fn probe(
    client: &ReqwestClient,
    base: &Url,
    auth: &GoogleAuth,
    version: reqwest::Version,
    probe_path: &str,
) -> std::result::Result<String, GrrError> {
    let token = auth.get_access_token().await?;
    let url = base.join(probe_path)?;
    let resp = client
        .get(url)
        .bearer_auth(&token)
        .version(version)
        .send()
        .await?;
    Ok(format!("{:?}", resp.version()))
}

/// Build HTTP client with auto-tuned transport settings.
///
/// Zero-config: every value is a constant tuned for Google frontends and
/// bounded async I/O; the tokio runtime already sizes OS threads to cores.
pub fn build_http_client() -> Result<ReqwestClient> {
    build_http_client_with_mode(resolve_transport_mode(true))
}

fn build_http_client_with_mode(mode: TransportMode) -> Result<ReqwestClient> {
    let mut builder = ReqwestClient::builder()
        .timeout(REQUEST_TIMEOUT)
        .connect_timeout(CONNECT_TIMEOUT)
        .pool_max_idle_per_host(POOL_IDLE_PER_HOST)
        .pool_idle_timeout(POOL_IDLE_TIMEOUT)
        .tcp_keepalive(TCP_KEEPALIVE)
        .http2_keep_alive_interval(H2_KEEPALIVE_INTERVAL)
        .http2_adaptive_window(true)
        .brotli(true)
        .zstd(true)
        .gzip(true);

    builder = match mode {
        TransportMode::Http3PriorKnowledge => builder.http3_prior_knowledge(),
        TransportMode::Http2PriorKnowledge => builder.http2_prior_knowledge(),
    };

    let mut headers = HeaderMap::new();
    headers.insert(
        ACCEPT_ENCODING,
        HeaderValue::from_static("zstd, br, gzip, deflate"),
    );
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

    builder
        .default_headers(headers)
        .build()
        .map_err(|error| GrrError::Config(format!("Failed to build HTTP client: {error}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn query_params_collects_optional_values_and_page_tokens() -> Result<()> {
        let request = QueryParams::new()
            .add("q", "in:inbox")
            .add_optional("labelId", Some("INBOX"))
            .add_optional("timeMin", None::<&str>)
            .add_page_token(Some("next"))
            .apply(ReqwestClient::new().get("https://example.com/messages"))
            .build()?;

        assert_eq!(
            request.url().query(),
            Some("q=in%3Ainbox&labelId=INBOX&pageToken=next")
        );
        Ok(())
    }
}