firn 0.15.0

snowflake-rs fork: cancellation, async, streaming, multi-statement, bind params, structured types, retry middleware
Documentation
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use arc_swap::ArcSwapOption;
use futures::lock::Mutex;
use secrecy::{ExposeSecret, SecretString};
#[cfg(feature = "cert-auth")]
use snowflake_jwt::generate_jwt_token;
use thiserror::Error;

use crate::connection;
use crate::connection::{Connection, QueryType};
#[cfg(feature = "browser-auth")]
use crate::requests::{
    AuthenticatorRequest, AuthenticatorRequestData, BrowserLoginRequest, BrowserRequestData,
};
#[cfg(feature = "cert-auth")]
use crate::requests::{CertLoginRequest, CertRequestData};
use crate::requests::{
    ClientEnvironment, LoginRequest, LoginRequestCommon, PasswordLoginRequest, PasswordRequestData,
    RenewSessionRequest, SessionParameters,
};
use crate::responses::{AuthResponse, BaseRestResponse};

#[derive(Error, Debug)]
pub enum AuthError {
    #[error(transparent)]
    #[cfg(feature = "cert-auth")]
    JwtError(#[from] snowflake_jwt::JwtError),

    #[error(transparent)]
    RequestError(#[from] connection::ConnectionError),

    #[error("Environment variable `{0}` is required, but were not set")]
    MissingEnvArgument(String),

    #[error("Password auth was requested, but password wasn't provided")]
    MissingPassword,

    #[error("Certificate auth was requested, but certificate wasn't provided")]
    MissingCertificate,

    #[error("Unexpected API response")]
    UnexpectedResponse,

    // todo: add code mapping to meaningful message and/or refer to docs
    //   eg https://docs.snowflake.com/en/user-guide/key-pair-auth-troubleshooting
    #[error("Failed to authenticate. Error code: {0}. Message: {1}")]
    AuthFailed(String, String),

    #[error("Can not renew closed session token")]
    OutOfOrderRenew,

    #[error("Failed to exchange or request a new token")]
    TokenFetchFailed,

    #[error("Login timed out after {0:?}")]
    LoginTimeout(Duration),

    #[error("Enable the cert-auth feature to use certificate authentication")]
    CertAuthNotEnabled,

    #[error("Enable the browser-auth feature to use external browser authentication")]
    BrowserAuthNotEnabled,

    #[cfg(feature = "browser-auth")]
    #[error(transparent)]
    BrowserAuthError(#[from] crate::browser::BrowserAuthError),
}

#[derive(Debug)]
struct AuthState {
    session_token: AuthToken,
    master_token: AuthToken,
    // Precomputed so the hot path in `get_token` doesn't reformat per query.
    auth_header: String,
}

impl AuthState {
    fn new(session_token: AuthToken, master_token: AuthToken) -> Self {
        let auth_header = session_token.auth_header();
        Self {
            session_token,
            master_token,
            auth_header,
        }
    }

    fn is_fresh(&self) -> bool {
        !self.master_token.is_expired() && !self.session_token.is_expired()
    }
}

#[derive(Clone)]
struct AuthToken {
    token: SecretString,
    valid_for: Duration,
    issued_on: Instant,
}

impl std::fmt::Debug for AuthToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthToken")
            .field("token", &"[REDACTED]")
            .field("valid_for", &self.valid_for)
            .field("issued_on", &self.issued_on)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct AuthParts {
    pub session_token_auth_header: String,
    pub sequence_id: u64,
}

impl AuthToken {
    pub fn new(token: &str, validity_in_seconds: i64) -> Self {
        let token = SecretString::from(token);

        let valid_for = if validity_in_seconds < 0 {
            Duration::from_secs(u64::MAX)
        } else {
            Duration::from_secs(u64::try_from(validity_in_seconds).unwrap_or(u64::MAX))
        };
        let issued_on = Instant::now();

        Self {
            token,
            valid_for,
            issued_on,
        }
    }

    pub fn is_expired(&self) -> bool {
        Instant::now().duration_since(self.issued_on) >= self.valid_for
    }

    pub fn auth_header(&self) -> String {
        format!("Snowflake Token=\"{}\"", self.token.expose_secret())
    }
}

enum AuthType {
    Certificate,
    Password,
    #[cfg(feature = "browser-auth")]
    Browser,
}

/// Requests, caches, and renews authentication tokens.
/// Tokens are given as response to creating new session in Snowflake. Session persists
/// the configuration state and temporary objects (tables, procedures, etc).
// todo: split warehouse-database-schema and username-role-key into its own structs
// todo: close session after object is dropped
pub struct Session {
    connection: Arc<Connection>,

    auth_state: ArcSwapOption<AuthState>,
    sequence_id: AtomicU64,
    // Single-flights login/renew so concurrent first-callers share one
    // round-trip instead of racing each other.
    refresh_lock: Mutex<()>,
    auth_type: AuthType,
    account_identifier: String,

    warehouse: Option<String>,
    database: Option<String>,
    schema: Option<String>,

    username: String,
    role: Option<String>,
    // This is not used with the certificate auth crate
    #[allow(dead_code)]
    private_key_pem: Option<SecretString>,
    password: Option<SecretString>,
    login_timeout: Duration,
}

/// <https://github.com/snowflakedb/gosnowflake/blob/v2.0.2/internal/config/dsn.go#L27-L28>
const DEFAULT_LOGIN_TIMEOUT: Duration = Duration::from_secs(300);

// todo: make builder
impl Session {
    /// Authenticate using private certificate and JWT
    // fixme: add builder or introduce structs
    #[allow(clippy::too_many_arguments)]
    pub fn cert_auth(
        connection: Arc<Connection>,
        account_identifier: &str,
        warehouse: Option<&str>,
        database: Option<&str>,
        schema: Option<&str>,
        username: &str,
        role: Option<&str>,
        private_key_pem: SecretString,
    ) -> Self {
        let account_identifier = account_identifier.to_uppercase();

        let database = database.map(str::to_uppercase);
        let schema = schema.map(str::to_uppercase);

        let username = username.to_uppercase();
        let role = role.map(str::to_uppercase);

        Self {
            connection,
            auth_state: ArcSwapOption::empty(),
            sequence_id: AtomicU64::new(0),
            refresh_lock: Mutex::new(()),
            auth_type: AuthType::Certificate,
            private_key_pem: Some(private_key_pem),
            account_identifier,
            warehouse: warehouse.map(str::to_uppercase),
            database,
            username,
            role,
            schema,
            password: None,
            login_timeout: DEFAULT_LOGIN_TIMEOUT,
        }
    }

    /// Authenticate using password
    // fixme: add builder or introduce structs
    #[allow(clippy::too_many_arguments)]
    pub fn password_auth(
        connection: Arc<Connection>,
        account_identifier: &str,
        warehouse: Option<&str>,
        database: Option<&str>,
        schema: Option<&str>,
        username: &str,
        role: Option<&str>,
        password: SecretString,
    ) -> Self {
        let account_identifier = account_identifier.to_uppercase();

        let database = database.map(str::to_uppercase);
        let schema = schema.map(str::to_uppercase);

        let username = username.to_uppercase();
        let role = role.map(str::to_uppercase);

        Self {
            connection,
            auth_state: ArcSwapOption::empty(),
            sequence_id: AtomicU64::new(0),
            refresh_lock: Mutex::new(()),
            auth_type: AuthType::Password,
            account_identifier,
            warehouse: warehouse.map(str::to_uppercase),
            database,
            username,
            role,
            password: Some(password),
            schema,
            private_key_pem: None,
            login_timeout: DEFAULT_LOGIN_TIMEOUT,
        }
    }

    /// Authenticate using external browser SSO
    #[cfg(feature = "browser-auth")]
    #[allow(clippy::too_many_arguments)]
    pub fn browser_auth(
        connection: Arc<Connection>,
        account_identifier: &str,
        warehouse: Option<&str>,
        database: Option<&str>,
        schema: Option<&str>,
        username: &str,
        role: Option<&str>,
    ) -> Self {
        let account_identifier = account_identifier.to_uppercase();

        let database = database.map(str::to_uppercase);
        let schema = schema.map(str::to_uppercase);

        let username = username.to_uppercase();
        let role = role.map(str::to_uppercase);

        Self {
            connection,
            auth_state: ArcSwapOption::empty(),
            sequence_id: AtomicU64::new(0),
            refresh_lock: Mutex::new(()),
            auth_type: AuthType::Browser,
            account_identifier,
            warehouse: warehouse.map(str::to_uppercase),
            database,
            username,
            role,
            password: None,
            schema,
            private_key_pem: None,
            login_timeout: DEFAULT_LOGIN_TIMEOUT,
        }
    }

    pub fn set_login_timeout(&mut self, timeout: Duration) {
        self.login_timeout = timeout;
    }

    /// Get cached auth + a fresh sequence id. Hot path is lock-free
    /// (`ArcSwap` load + atomic `fetch_add`). Refresh single-flights
    /// via `refresh_lock`.
    pub async fn get_token(&self) -> Result<AuthParts, AuthError> {
        if let Some(state) = self.auth_state.load_full() {
            if state.is_fresh() {
                return Ok(self.build_parts(&state));
            }
        }

        let _refresh_guard = self.refresh_lock.lock().await;

        // Re-check: another caller may have refreshed while we waited.
        if let Some(state) = self.auth_state.load_full() {
            if state.is_fresh() {
                return Ok(self.build_parts(&state));
            }
        }

        let current = self.auth_state.load_full();
        let need_full_create = current
            .as_deref()
            .is_none_or(|s| s.master_token.is_expired());

        let new_state = if need_full_create {
            let tokens = match self.auth_type {
                AuthType::Certificate => {
                    log::info!("Starting session with certificate authentication");
                    if cfg!(feature = "cert-auth") {
                        self.create(self.cert_request_body()?).await?
                    } else {
                        return Err(AuthError::MissingCertificate);
                    }
                }
                AuthType::Password => {
                    log::info!("Starting session with password authentication");
                    self.create(self.passwd_request_body()?).await?
                }
                #[cfg(feature = "browser-auth")]
                AuthType::Browser => {
                    log::info!("Starting session with external browser authentication");
                    self.create_browser_session().await?
                }
            };
            // Full re-create => new Snowflake session => reset counter.
            self.sequence_id.store(0, Ordering::Relaxed);
            tokens
        } else {
            match current {
                Some(state) => self.renew(&state).await?,
                None => return Err(AuthError::OutOfOrderRenew),
            }
        };

        let new_state = Arc::new(new_state);
        self.auth_state.store(Some(Arc::clone(&new_state)));
        Ok(self.build_parts(&new_state))
    }

    fn build_parts(&self, state: &AuthState) -> AuthParts {
        // +1 to match pre-refactor semantics where first id returned is 1.
        let sequence_id = self.sequence_id.fetch_add(1, Ordering::Relaxed) + 1;
        AuthParts {
            session_token_auth_header: state.auth_header.clone(),
            sequence_id,
        }
    }

    /// Renew now, regardless of TTL. For callers that observed an explicit
    /// `390112` from the server mid-flight and need to refresh before
    /// retrying. Falls back to a full re-create if the master token is
    /// gone or itself expired.
    pub async fn force_renew(&self) -> Result<AuthParts, AuthError> {
        let _refresh_guard = self.refresh_lock.lock().await;

        let current = self.auth_state.load_full();
        let new_state = match current.as_deref() {
            Some(s) if !s.master_token.is_expired() => self.renew(s).await?,
            _ => {
                let tokens = match self.auth_type {
                    AuthType::Certificate => {
                        log::info!("Re-creating session (certificate auth)");
                        if cfg!(feature = "cert-auth") {
                            self.create(self.cert_request_body()?).await?
                        } else {
                            return Err(AuthError::MissingCertificate);
                        }
                    }
                    AuthType::Password => {
                        log::info!("Re-creating session (password auth)");
                        self.create(self.passwd_request_body()?).await?
                    }
                    #[cfg(feature = "browser-auth")]
                    AuthType::Browser => {
                        log::info!("Re-creating session (browser auth)");
                        self.create_browser_session().await?
                    }
                };
                self.sequence_id.store(0, Ordering::Relaxed);
                tokens
            }
        };

        let new_state = Arc::new(new_state);
        self.auth_state.store(Some(Arc::clone(&new_state)));
        Ok(self.build_parts(&new_state))
    }

    // &self (not &mut): only mutation is ArcSwap, so Arc<Session> callers can close.
    pub async fn close(&self) -> Result<(), AuthError> {
        let Some(state) = self.auth_state.swap(None) else {
            return Ok(());
        };
        log::debug!("Closing sessions");

        let resp = self
            .connection
            .request::<AuthResponse>(
                QueryType::CloseSession,
                &self.account_identifier,
                &[("delete", "true")],
                Some(&state.auth_header),
                serde_json::Value::default(),
                None,
            )
            .await?;

        match resp {
            AuthResponse::Close(_) => Ok(()),
            AuthResponse::Error(e) => Err(AuthError::AuthFailed(
                e.code.unwrap_or_default(),
                e.message.unwrap_or_default(),
            )),
            _ => Err(AuthError::UnexpectedResponse),
        }
    }

    #[cfg(feature = "cert-auth")]
    fn cert_request_body(&self) -> Result<CertLoginRequest, AuthError> {
        let full_identifier = format!("{}.{}", &self.account_identifier, &self.username);
        let private_key_pem = self
            .private_key_pem
            .as_ref()
            .ok_or(AuthError::MissingCertificate)?;
        let jwt_token = generate_jwt_token(private_key_pem.expose_secret(), &full_identifier)?;

        Ok(CertLoginRequest {
            data: CertRequestData {
                login_request_common: self.login_request_common(),
                authenticator: "SNOWFLAKE_JWT".to_string(),
                token: jwt_token,
            },
        })
    }

    fn passwd_request_body(&self) -> Result<PasswordLoginRequest, AuthError> {
        let password = self.password.as_ref().ok_or(AuthError::MissingPassword)?;

        Ok(PasswordLoginRequest {
            data: PasswordRequestData {
                login_request_common: self.login_request_common(),
                password: password.expose_secret().to_string(),
            },
        })
    }

    /// Start new session, all the Snowflake temporary objects will be scoped towards it,
    /// as well as temporary configuration parameters.
    ///
    /// Enforces [`login_timeout`](https://github.com/snowflakedb/gosnowflake/blob/v2.0.2/internal/config/dsn.go#L27-L28) (default 300s).
    async fn create<T: serde::ser::Serialize>(
        &self,
        body: LoginRequest<T>,
    ) -> Result<AuthState, AuthError> {
        let timeout = self.login_timeout;
        tokio::time::timeout(timeout, self.create_inner(body))
            .await
            .map_err(|_| AuthError::LoginTimeout(timeout))?
    }

    async fn create_inner<T: serde::ser::Serialize>(
        &self,
        body: LoginRequest<T>,
    ) -> Result<AuthState, AuthError> {
        let mut get_params = Vec::new();
        if let Some(warehouse) = &self.warehouse {
            get_params.push(("warehouse", warehouse.as_str()));
        }

        if let Some(database) = &self.database {
            get_params.push(("databaseName", database.as_str()));
        }

        if let Some(schema) = &self.schema {
            get_params.push(("schemaName", schema.as_str()));
        }

        if let Some(role) = &self.role {
            get_params.push(("roleName", role.as_str()));
        }

        let resp = self
            .connection
            .request::<AuthResponse>(
                QueryType::LoginRequest,
                &self.account_identifier,
                &get_params,
                None,
                body,
                None,
            )
            .await?;
        log::debug!("Auth response: {resp:?}");

        match resp {
            AuthResponse::Login(lr) => {
                let session_token = AuthToken::new(&lr.data.token, lr.data.validity_in_seconds);
                let master_token =
                    AuthToken::new(&lr.data.master_token, lr.data.master_validity_in_seconds);

                Ok(AuthState::new(session_token, master_token))
            }
            AuthResponse::Error(e) => Err(AuthError::AuthFailed(
                e.code.unwrap_or_default(),
                e.message.unwrap_or_default(),
            )),
            _ => Err(AuthError::UnexpectedResponse),
        }
    }

    fn login_request_common(&self) -> LoginRequestCommon {
        LoginRequestCommon {
            client_app_id: "Go".to_string(),
            client_app_version: "1.6.22".to_string(),
            svn_revision: String::new(),
            account_name: self.account_identifier.clone(),
            login_name: self.username.clone(),
            session_parameters: SessionParameters {
                client_validate_default_parameters: true,
            },
            client_environment: ClientEnvironment {
                application: "Rust".to_string(),
                // gosnowflake reports `runtime.GOOS` (lowercase: darwin /
                // linux / windows). Rust's std::env::consts::OS matches
                // except macOS reports as "macos"; remap.
                os: match std::env::consts::OS {
                    "macos" => "darwin".to_owned(),
                    other => other.to_owned(),
                },
                // gosnowflake's `os_version` carries the runtime arch
                // (the prior hardcoded "gc-arm64" was a stale Go-runtime
                // tag). Use Rust's target arch: x86_64 / aarch64 / etc.
                os_version: std::env::consts::ARCH.to_owned(),
                ocsp_mode: "FAIL_OPEN".to_string(),
            },
        }
    }

    /// Browser SSO authentication flow:
    /// 1. Create local TCP listener for callback
    /// 2. Generate proof key
    /// 3. Send authenticator-request to get SSO URL
    /// 4. Open browser with SSO URL
    /// 5. Wait for token on local listener
    /// 6. Send login-request with token and proof key
    #[cfg(feature = "browser-auth")]
    async fn create_browser_session(&self) -> Result<AuthState, AuthError> {
        use crate::browser::{
            create_local_listener, generate_proof_key, open_browser, wait_for_token,
        };

        // Step 1: Create local listener for callback
        let (listener, port) = create_local_listener()?;

        // Step 2: Generate proof key
        let proof_key = generate_proof_key();

        // Step 3: Send authenticator-request to get SSO URL
        let auth_request = AuthenticatorRequest {
            data: AuthenticatorRequestData {
                client_app_id: "Go".to_string(),
                client_app_version: "1.6.22".to_string(),
                svn_revision: String::new(),
                account_name: self.account_identifier.clone(),
                login_name: self.username.clone(),
                authenticator: "EXTERNALBROWSER".to_string(),
                browser_mode_redirect_port: port.to_string(),
                proof_key: proof_key.clone(),
                client_environment: crate::requests::AuthenticatorClientEnvironment {
                    application: "Rust".to_string(),
                    os: std::env::consts::OS.to_string(),
                    os_version: "unknown".to_string(),
                },
            },
        };

        let resp = self
            .connection
            .request::<AuthResponse>(
                QueryType::AuthenticatorRequest,
                &self.account_identifier,
                &[],
                None,
                auth_request,
                None,
            )
            .await?;

        let (sso_url, server_proof_key) = match resp {
            AuthResponse::Auth(auth_resp) => (auth_resp.data.sso_url, auth_resp.data.proof_key),
            AuthResponse::Error(e) => {
                return Err(AuthError::AuthFailed(
                    e.code.unwrap_or_default(),
                    e.message.unwrap_or_default(),
                ));
            }
            _ => return Err(AuthError::UnexpectedResponse),
        };

        // Use the server-returned proof_key for the login request
        // The server may modify the proof key, and the login request must match
        let final_proof_key = if server_proof_key.is_empty() {
            proof_key
        } else {
            server_proof_key
        };

        // Step 4: Open browser with SSO URL
        open_browser(&sso_url)?;

        // Step 5: Wait for token on local listener (blocking)
        let token = tokio::task::spawn_blocking(move || wait_for_token(&listener))
            .await
            .map_err(|_| AuthError::TokenFetchFailed)??;

        // Step 6: Send login-request with token and proof key
        let login_request = BrowserLoginRequest {
            data: BrowserRequestData {
                login_request_common: self.login_request_common(),
                authenticator: "EXTERNALBROWSER".to_string(),
                token,
                proof_key: final_proof_key,
            },
        };

        self.create(login_request).await
    }

    // Caller must NOT reset `sequence_id`: renewals preserve the Snowflake
    // session id space.
    async fn renew(&self, old: &AuthState) -> Result<AuthState, AuthError> {
        log::debug!("Renewing the token");
        let auth = old.master_token.auth_header();
        let body = RenewSessionRequest {
            old_session_token: old.session_token.token.expose_secret().to_string(),
            request_type: "RENEW".to_string(),
        };

        let resp = self
            .connection
            .request(
                QueryType::TokenRequest,
                &self.account_identifier,
                &[],
                Some(&auth),
                body,
                None,
            )
            .await?;

        match resp {
            AuthResponse::Renew(rs) => {
                let session_token =
                    AuthToken::new(&rs.data.session_token, rs.data.validity_in_seconds_s_t);
                let master_token =
                    AuthToken::new(&rs.data.master_token, rs.data.validity_in_seconds_m_t);
                Ok(AuthState::new(session_token, master_token))
            }
            AuthResponse::Error(e) => Err(AuthError::AuthFailed(
                e.code.unwrap_or_default(),
                e.message.unwrap_or_default(),
            )),
            _ => Err(AuthError::UnexpectedResponse),
        }
    }

    /// Hit `/session/heartbeat` to keep the cached session token fresh. No-op
    /// if no session has been created yet (we don't auth purely to heartbeat).
    /// On `390112` we force-renew once and retry; the next tick handles any
    /// further failures.
    pub async fn heartbeat(&self) -> Result<(), AuthError> {
        if self.auth_state.load().is_none() {
            return Ok(());
        }
        let parts = self.get_token().await?;
        let resp = self
            .send_heartbeat(&parts.session_token_auth_header)
            .await?;
        if resp.success {
            return Ok(());
        }
        if resp.code.as_deref() == Some("390112") {
            log::debug!("Heartbeat saw 390112; renewing and retrying once");
            let parts = self.force_renew().await?;
            let resp = self
                .send_heartbeat(&parts.session_token_auth_header)
                .await?;
            if resp.success {
                return Ok(());
            }
            return Err(AuthError::AuthFailed(
                resp.code.unwrap_or_default(),
                resp.message.unwrap_or_default(),
            ));
        }
        Err(AuthError::AuthFailed(
            resp.code.unwrap_or_default(),
            resp.message.unwrap_or_default(),
        ))
    }

    async fn send_heartbeat(
        &self,
        auth_header: &str,
    ) -> Result<BaseRestResponse<serde_json::Value>, AuthError> {
        Ok(self
            .connection
            .request::<BaseRestResponse<serde_json::Value>>(
                QueryType::Heartbeat,
                &self.account_identifier,
                &[],
                Some(auth_header),
                serde_json::Value::Null,
                None,
            )
            .await?)
    }
}