tensorlake 0.5.153

A Rust SDK for interacting with Tensorlake Cloud APIs.
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! HTTP client that interacts with the Tensorlake Cloud API.
use futures::{Future, Stream, StreamExt};
use reqwest::{
    Method, Request, Response, StatusCode,
    header::{ACCEPT, CONTENT_LENGTH, HeaderMap, HeaderValue, InvalidHeaderValue},
};
use reqwest_middleware::{ClientBuilder as ReqwestClientBuilder, ClientWithMiddleware, Middleware};
use serde::de::DeserializeOwned;
use std::{
    ops::{Deref, DerefMut},
    pin::Pin,
    result::Result,
    sync::Arc,
    time::Duration,
};

use crate::{error::SdkError, sse::event_stream};

#[path = "read_retry.rs"]
mod read_retry;
pub use read_retry::ReadRetryConfig;

pub const REQUEST_TIMEOUT_HEADER: &str = "X-Tensorlake-Request-Timeout-Ms";

/// Wraps any SDK operation result with the W3C `trace_id` so callers can
/// correlate the request with its server-side spans in Datadog APM or any
/// other OTEL-compatible backend.
///
/// All fields and methods of `T` are accessible via `Deref`/`DerefMut`, so
/// most existing code compiles unchanged. Use `into_inner()` when you need an
/// owned `T`.
///
/// # Example
///
/// ```rust,ignore
/// let result = sdk.sandboxes("ns", false).create(&request).await?;
/// println!("{}", result.sandbox_id); // existing field — accessible via Deref
/// println!("{}", result.trace_id);   // new: look this up in Datadog APM
/// ```
#[derive(Debug, Clone)]
pub struct Traced<T> {
    /// W3C trace ID for this request (32 lowercase hex chars).
    pub trace_id: String,
    value: T,
}

impl<T> Traced<T> {
    pub fn new(trace_id: String, value: T) -> Self {
        Self { trace_id, value }
    }

    pub fn into_inner(self) -> T {
        self.value
    }

    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Traced<U> {
        Traced {
            trace_id: self.trace_id,
            value: f(self.value),
        }
    }
}

impl<T> Deref for Traced<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}

impl<T> DerefMut for Traced<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

/// HTTP client that interacts with the Tensorlake Cloud API.
#[derive(Clone)]
pub struct Client {
    /// Base URL of the API, used to construct the full URL for each request.
    base_url: String,
    /// Base client to construct more specialized clients, used to construct EventSource requests.
    base_client: reqwest::Client,
    /// Client with user provided middlewares. Used to perform regular HTTP requests.
    client: ClientWithMiddleware,
    /// Default headers configured on the underlying clients.
    default_headers: HeaderMap,
    /// User-Agent configured on the underlying client.
    user_agent: String,
    /// Total request timeout configured for this client.
    timeout: Option<Duration>,
    reads: Arc<read_retry::ReadTransport>,
}

/// Builder for creating a [`Client`] with a fluent API.
///
/// The base URL is required, while bearer token, middlewares, and scope are optional.
#[derive(Clone)]
pub struct ClientBuilder {
    base_url: String,
    bearer_token: Option<String>,
    middlewares: Vec<Arc<dyn Middleware + 'static>>,
    organization_id: Option<String>,
    project_id: Option<String>,
    user_agent: Option<String>,
    timeout: Option<Duration>,
    follow_redirects: bool,
    read_retry: ReadRetryConfig,
}

impl ClientBuilder {
    pub(crate) fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Create a new [`ClientBuilder`] with the specified base URL.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of the API
    pub fn new(base_url: &str) -> Self {
        Self {
            base_url: base_url.to_string(),
            bearer_token: None,
            middlewares: Vec::new(),
            organization_id: None,
            project_id: None,
            user_agent: None,
            timeout: None,
            follow_redirects: true,
            read_retry: ReadRetryConfig::default(),
        }
    }

    /// Override the User-Agent header sent with every request.
    ///
    /// Defaults to `tensorlake-rust-sdk/{CARGO_PKG_VERSION}`. Callers that
    /// wrap this client (e.g. the Python SDK via PyO3) should set a value like
    /// `tensorlake-python-sdk/{version}` so server logs can distinguish traffic
    /// by SDK language.
    pub fn user_agent(mut self, ua: &str) -> Self {
        self.user_agent = Some(ua.to_string());
        self
    }

    /// Set the timeout for each HTTP request.
    ///
    /// It bounds a whole request and response. For a streamed response, such
    /// as server-sent events, it bounds the wait for the response headers and
    /// each wait for more of the stream, so a stream that keeps sending data
    /// runs until the server closes it.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Configure bounded retries for explicitly designated sandbox metadata reads.
    /// The request's timeout, when smaller, also caps the entire retry sequence.
    pub fn read_retry(mut self, config: ReadRetryConfig) -> Self {
        self.read_retry = config;
        self
    }

    /// Configure automatic redirects. Mutations that may be retried should
    /// disable redirects so a later hop cannot hide delivery of the first one.
    pub fn follow_redirects(mut self, enabled: bool) -> Self {
        self.follow_redirects = enabled;
        self
    }

    /// Set the bearer token for authentication.
    pub fn bearer_token(mut self, token: &str) -> Self {
        self.bearer_token = Some(token.to_string());
        self
    }

    /// Add middleware to the client.
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware + 'static,
    {
        self.middlewares.push(Arc::new(middleware));
        self
    }

    /// Add multiple middlewares to the client.
    pub fn middlewares(mut self, middlewares: Vec<Arc<dyn Middleware + 'static>>) -> Self {
        self.middlewares = middlewares;
        self
    }

    /// Set the organization and project scope.
    pub fn scope(mut self, organization_id: &str, project_id: &str) -> Self {
        self.organization_id = Some(organization_id.to_string());
        self.project_id = Some(project_id.to_string());
        self
    }

    /// Build the [`Client`].
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created or configured.
    pub fn build(self) -> Result<Client, SdkError> {
        self.read_retry.validate()?;
        let mut default_headers = HeaderMap::new();

        // Add bearer token if provided
        if let Some(token) = &self.bearer_token {
            default_headers = new_default_headers(token)?;
        }

        // Add scope headers if provided
        if let Some(org_id) = &self.organization_id {
            default_headers.insert("X-Forwarded-Organization-Id", str_to_header_value(org_id)?);
        }
        if let Some(project_id) = &self.project_id {
            default_headers.insert("X-Forwarded-Project-Id", str_to_header_value(project_id)?);
        }

        let ua = self
            .user_agent
            .as_deref()
            .unwrap_or(concat!("tensorlake-rust-sdk/", env!("CARGO_PKG_VERSION")));
        let transport = crate::http_transport::https_builder()
            .user_agent(ua)
            .default_headers(default_headers.clone())
            .redirect(if self.follow_redirects {
                reqwest::redirect::Policy::default()
            } else {
                reqwest::redirect::Policy::none()
            });
        let base_client = transport.build()?;
        let mut builder = ReqwestClientBuilder::new(base_client.clone());

        for middleware in &self.middlewares {
            builder = builder.with_arc(middleware.clone());
        }

        let client = builder.build();

        let reads = Arc::new(read_retry::ReadTransport::new(
            self.read_retry,
            default_headers.clone(),
            ua.to_string(),
            self.middlewares,
            self.follow_redirects,
        ));
        Ok(Client {
            base_url: self.base_url,
            base_client,
            client,
            default_headers,
            user_agent: ua.to_string(),
            timeout: self.timeout,
            reads,
        })
    }
}

type EventSourceStream<T> = Pin<Box<dyn Stream<Item = Result<T, SdkError>> + Send>>;

const WAITING_FOR_RESPONSE_HEADERS: &str = "the response headers";

impl Client {
    pub(crate) fn base_url(&self) -> &str {
        &self.base_url
    }

    pub(crate) fn default_headers(&self) -> HeaderMap {
        self.default_headers.clone()
    }

    /// Total request timeout configured for this client, if any.
    pub fn request_timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// Create a new client that shares the same underlying HTTP connection pool but uses a
    /// different base URL. Cloning `reqwest::Client` shares its Arc-backed connection pool, so
    /// HTTP/2 connections established for one base URL can be reused (via connection coalescing)
    /// when talking to another host that resolves to the same IP with the same TLS certificate.
    pub fn with_base_url(&self, new_url: &str) -> Self {
        let client = ReqwestClientBuilder::new(self.base_client.clone()).build();
        Self {
            base_url: new_url.to_string(),
            base_client: self.base_client.clone(),
            client,
            default_headers: self.default_headers.clone(),
            user_agent: self.user_agent.clone(),
            timeout: self.timeout,
            reads: self.reads.clone(),
        }
    }

    /// Create a new client for a different base URL without a request timeout.
    pub fn with_base_url_without_timeout(&self, new_url: &str) -> Result<Self, SdkError> {
        self.with_base_url_and_timeout(new_url, None)
    }

    /// Create a new client for a different base URL with an explicit total request timeout.
    pub fn with_base_url_and_timeout(
        &self,
        new_url: &str,
        timeout: Option<Duration>,
    ) -> Result<Self, SdkError> {
        let mut client = self.with_base_url(new_url);
        client.timeout = timeout;
        Ok(client)
    }

    fn prepare_request(&self, request: &mut Request) {
        let (traceparent, _) = generate_traceparent();
        if let Ok(value) = traceparent.parse::<HeaderValue>() {
            request.headers_mut().insert("traceparent", value);
        }
        self.insert_request_timeout_header(request);
    }

    fn prepare_traced_request(&self, request: &mut Request) -> String {
        let (traceparent, trace_id) = generate_traceparent();
        if let Ok(value) = traceparent.parse::<HeaderValue>() {
            request.headers_mut().insert("traceparent", value);
        }
        self.insert_request_timeout_header(request);
        trace_id
    }

    fn insert_request_timeout_header(&self, request: &mut Request) {
        // Timeouts belong to requests, so clients with different deadlines can
        // share the same transport and TLS configuration. Preserve an explicit
        // per-request timeout when the caller supplied one.
        if request.timeout().is_none() {
            *request.timeout_mut() = self.timeout;
        }
        let Some(timeout) = self.timeout else {
            return;
        };
        let millis = timeout.as_millis();
        if millis == 0 {
            return;
        }
        if let Ok(value) = HeaderValue::from_str(&millis.to_string()) {
            request.headers_mut().insert(REQUEST_TIMEOUT_HEADER, value);
        }
    }

    /// Execute an HTTP request. Injects a W3C `traceparent` header for server-side
    /// correlation. Use [`execute_traced`] or [`execute_json`] when you need the
    /// `trace_id` returned to the caller.
    pub async fn execute(&self, mut request: Request) -> Result<Response, SdkError> {
        self.prepare_request(&mut request);
        let response = self.client.execute(request).await?;
        self.handle_response(response).await
    }

    /// Execute an HTTP request without mapping non-success statuses to [`SdkError`].
    /// Injects a W3C `traceparent` header for server-side correlation.
    pub async fn execute_raw(&self, mut request: Request) -> Result<Response, SdkError> {
        self.prepare_request(&mut request);
        let response = self.client.execute(request).await?;
        Ok(response)
    }

    /// Execute a traced request while leaving status handling to the binding.
    /// Useful for APIs with expected non-success statuses (such as lookup 404s).
    pub async fn execute_raw_traced(
        &self,
        mut request: Request,
    ) -> Result<Traced<Response>, SdkError> {
        let trace_id = self.prepare_traced_request(&mut request);
        let response = self.client.execute(request).await?;
        Ok(Traced::new(trace_id, response))
    }

    /// Execute an HTTP request, inject a W3C `traceparent` header, and return
    /// the raw response alongside the `trace_id`. Use this when you need the
    /// `trace_id` but want to handle the response body yourself.
    pub async fn execute_traced(&self, mut request: Request) -> Result<Traced<Response>, SdkError> {
        let trace_id = self.prepare_traced_request(&mut request);
        let response = self.client.execute(request).await?;
        let response = self.handle_response(response).await?;
        Ok(Traced::new(trace_id, response))
    }

    /// Execute a request whose response body is a stream, such as server-sent
    /// events. The client's request timeout bounds the wait for the response
    /// headers and is returned so [`event_stream`] can bound each wait for
    /// more of the body. Non-success statuses become [`SdkError`]s.
    pub(crate) async fn execute_stream_traced(
        &self,
        request: Request,
    ) -> Result<(Traced<Response>, Option<Duration>), SdkError> {
        self.send_stream(request).await
    }

    async fn send_stream(
        &self,
        mut request: Request,
    ) -> Result<(Traced<Response>, Option<Duration>), SdkError> {
        let trace_id = self.prepare_traced_request(&mut request);
        // reqwest applies a request timeout until the body ends, which would
        // cut off a stream that is still delivering data. Keep the timeout
        // header for the server and enforce the deadline here instead.
        let timeout = request.timeout_mut().take();
        let response = within_timeout(timeout, WAITING_FOR_RESPONSE_HEADERS, async {
            let response = self.client.execute(request).await?;
            self.handle_response(response).await
        })
        .await?;
        Ok((Traced::new(trace_id, response), timeout))
    }

    /// Execute an HTTP request, inject a W3C `traceparent` header, deserialize
    /// the JSON response body, and return both alongside the `trace_id`.
    ///
    /// This is the primary building block for service-level methods that return
    /// structured responses. The `trace_id` lets callers look up the full
    /// server-side cascade in Datadog APM.
    pub async fn execute_json<T: DeserializeOwned>(
        &self,
        request: Request,
    ) -> Result<Traced<T>, SdkError> {
        let traced = self.execute_traced(request).await?;
        Self::decode_traced_json(traced).await
    }

    /// Execute an HTTP request and deserialize JSON if the status is success or
    /// explicitly listed in `allowed_statuses`.
    pub async fn execute_json_allow_status<T: DeserializeOwned>(
        &self,
        mut request: Request,
        allowed_statuses: &[StatusCode],
    ) -> Result<Traced<T>, SdkError> {
        let trace_id = self.prepare_traced_request(&mut request);
        let response = self.client.execute(request).await?;
        let response =
            if response.status().is_success() || allowed_statuses.contains(&response.status()) {
                response
            } else {
                self.handle_response(response).await?
            };
        Self::decode_traced_json(Traced::new(trace_id, response)).await
    }

    async fn decode_traced_json<T: DeserializeOwned>(
        traced: Traced<Response>,
    ) -> Result<Traced<T>, SdkError> {
        let trace_id = traced.trace_id.clone();
        let bytes = traced.into_inner().bytes().await?;
        let jd = &mut serde_json::Deserializer::from_slice(bytes.as_ref());
        let value: T = serde_path_to_error::deserialize(jd)?;
        Ok(Traced::new(trace_id, value))
    }

    pub fn request(
        &self,
        method: reqwest::Method,
        path: &str,
    ) -> reqwest_middleware::RequestBuilder {
        let request = self.client.request(method, self.base_url.clone() + path);
        match self.timeout {
            Some(timeout) => request.timeout(timeout),
            None => request,
        }
    }

    pub async fn build_event_source_request<T>(
        &self,
        path: &str,
    ) -> Result<Traced<EventSourceStream<T>>, SdkError>
    where
        T: DeserializeOwned,
    {
        let (traceparent, trace_id) = generate_traceparent();
        let mut request_builder = self
            .base_client
            .get(self.base_url.clone() + path)
            .header(ACCEPT, "text/event-stream")
            .header("traceparent", traceparent);
        if let Some(timeout) = self.timeout {
            let millis = timeout.as_millis();
            if millis > 0 {
                request_builder =
                    request_builder.header(REQUEST_TIMEOUT_HEADER, millis.to_string());
            }
        }
        let response = within_timeout(self.timeout, WAITING_FOR_RESPONSE_HEADERS, async {
            Ok(request_builder.send().await?)
        })
        .await?;

        let stream = event_stream(response, self.timeout).filter_map(move |event| async move {
            match event {
                Ok(msg) => match serde_json::from_str::<T>(&msg.data) {
                    Ok(evt) => Some(Ok(evt)),
                    Err(error) => Some(Err(SdkError::Json(error))),
                },
                Err(error) => Some(Err(error)),
            }
        });
        Ok(Traced::new(trace_id, Box::pin(stream)))
    }

    pub fn build_multipart_request(
        &self,
        method: reqwest::Method,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> Result<reqwest::Request, SdkError> {
        self.request(method, path)
            .multipart(form)
            .build()
            .map_err(Into::into)
    }

    pub fn build_empty_post_request(&self, path: &str) -> Result<reqwest::Request, SdkError> {
        build_empty_post_request_from_builder(self.request(Method::POST, path))
    }

    pub fn build_bytes_post_request(
        &self,
        path: &str,
        body: Vec<u8>,
    ) -> Result<reqwest::Request, SdkError> {
        build_bytes_post_request_from_builder(self.request(Method::POST, path), body)
    }

    /// Helper function to build POST, PUT or PATCH requests with JSON body
    pub fn build_post_json_request(
        &self,
        method: reqwest::Method,
        path: &str,
        body: &impl serde::Serialize,
    ) -> Result<reqwest::Request, SdkError> {
        Ok(self.request(method, path).json(body).build()?)
    }

    /// Helper function to build GET requests that return JSON responses
    pub fn build_get_json_request(
        &self,
        path: &str,
        query: Option<&[(&str, &str)]>,
    ) -> Result<reqwest::Request, SdkError> {
        let mut req_builder = self.request(Method::GET, path);
        if let Some(query) = query {
            req_builder = req_builder.query(query);
        }
        Ok(req_builder.header(ACCEPT, "application/json").build()?)
    }

    /// Helper function to handle HTTP responses and convert status codes to appropriate errors
    async fn handle_response(
        &self,
        response: reqwest::Response,
    ) -> Result<reqwest::Response, SdkError> {
        let status = response.status();

        match status {
            StatusCode::UNAUTHORIZED => {
                let message = body_message_or_default(response, "Unauthorized").await;
                Err(SdkError::Authentication(message))
            }
            StatusCode::FORBIDDEN => {
                let message = body_message_or_default(response, "Forbidden").await;
                Err(SdkError::Authorization(message))
            }
            status if status.is_server_error() => {
                let message = body_message_or_default(response, "Server error").await;
                Err(SdkError::ServerError { status, message })
            }
            status if !status.is_success() => {
                let message = body_message_or_default(response, "Request failed").await;
                Err(SdkError::ServerError { status, message })
            }
            _ => Ok(response),
        }
    }
}

async fn within_timeout<T>(
    timeout: Option<Duration>,
    waiting_for: &'static str,
    future: impl Future<Output = Result<T, SdkError>>,
) -> Result<T, SdkError> {
    match timeout {
        Some(timeout) => {
            tokio::time::timeout(timeout, future)
                .await
                .map_err(|_| SdkError::StreamTimeout {
                    waiting_for,
                    timeout,
                })?
        }
        None => future.await,
    }
}

pub(crate) fn build_empty_post_request_from_builder(
    builder: reqwest_middleware::RequestBuilder,
) -> Result<reqwest::Request, SdkError> {
    builder
        .header(CONTENT_LENGTH, "0")
        .build()
        .map_err(Into::into)
}

pub(crate) fn build_bytes_post_request_from_builder(
    builder: reqwest_middleware::RequestBuilder,
    body: Vec<u8>,
) -> Result<reqwest::Request, SdkError> {
    let len = body.len().to_string();
    builder
        .header(CONTENT_LENGTH, len)
        .body(body)
        .build()
        .map_err(Into::into)
}

fn generate_traceparent() -> (String, String) {
    let trace_id = hex::encode(rand::random::<[u8; 16]>());
    let span_id = hex::encode(rand::random::<[u8; 8]>());
    (format!("00-{trace_id}-{span_id}-01"), trace_id)
}

async fn body_message_or_default(response: Response, default: &str) -> String {
    let message = response
        .text()
        .await
        .unwrap_or_else(|_| default.to_string());
    if message.is_empty() {
        default.to_string()
    } else {
        message
    }
}

fn new_default_headers(bearer_token: &str) -> Result<HeaderMap, SdkError> {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Authorization",
        str_to_header_value(&format!("Bearer {}", bearer_token))?,
    );
    Ok(headers)
}

fn str_to_header_value(value: &str) -> Result<HeaderValue, SdkError> {
    value
        .parse()
        .map_err(|e: InvalidHeaderValue| SdkError::InvalidHeaderValue(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::ClientBuilder;
    use reqwest::Method;
    use std::{
        io::{Read, Write},
        net::TcpListener,
        sync::mpsc,
        thread,
        time::Duration,
    };

    #[tokio::test]
    async fn clients_with_different_timeouts_reuse_the_connection_pool() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        // One accepted socket must serve all three clients. If a client
        // rebuilds the pool, its request times out instead of using this socket.
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            for _ in 0..3 {
                let mut request = Vec::new();
                while !request.ends_with(b"\r\n\r\n") {
                    request.push(stream.read_u8().await.unwrap());
                }
                stream
                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                    .await
                    .unwrap();
            }
        });
        let client = ClientBuilder::new(&url)
            .timeout(Duration::from_secs(1))
            .build()
            .unwrap();
        let unbounded = client.with_base_url_without_timeout(&url).unwrap();
        let longer = client
            .with_base_url_and_timeout(&url, Some(Duration::from_secs(2)))
            .unwrap();
        for current in [&client, &unbounded, &longer] {
            let request = current.request(Method::GET, "/").build().unwrap();
            tokio::time::timeout(Duration::from_secs(3), current.execute_raw(request))
                .await
                .unwrap()
                .unwrap()
                .bytes()
                .await
                .unwrap();
        }
        server.await.unwrap();
    }

    #[tokio::test]
    async fn storage_transports_preserve_encoded_bytes() {
        use flate2::{Compression, write::GzEncoder};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let payload = b"bytes whose stored checksum must not change";
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(payload).unwrap();
        let encoded = encoder.finish().unwrap();
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let wire = encoded.clone();
        let server = tokio::spawn(async move {
            for _ in 0..2 {
                let (mut socket, _) = listener.accept().await.unwrap();
                let mut request = Vec::new();
                while !request.ends_with(b"\r\n\r\n") {
                    request.push(socket.read_u8().await.unwrap());
                }
                socket.write_all(format!(
                    "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Encoding: gzip\r\nContent-Length: {}\r\n\r\n",
                    wire.len(),
                ).as_bytes()).await.unwrap();
                socket.write_all(&wire).await.unwrap();
            }
        });

        // Both direct storage transport and the shared API client preserve bytes.
        for direct in [true, false] {
            let response = match direct {
                true => crate::http_transport::https_builder()
                    .timeout(Duration::from_secs(2))
                    .build()
                    .unwrap()
                    .get(&url)
                    .send()
                    .await
                    .unwrap(),
                false => {
                    let client = ClientBuilder::new(&url)
                        .timeout(Duration::from_secs(2))
                        .build()
                        .unwrap();
                    client
                        .execute_raw(client.request(Method::GET, "/").build().unwrap())
                        .await
                        .unwrap()
                }
            };
            let body = response.bytes().await.unwrap();
            assert_eq!(body.as_ref(), encoded.as_slice());
        }
        server.await.unwrap();
    }

    #[tokio::test]
    async fn proxy_can_remove_lifecycle_timeout_without_rebuilding_transport() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            for _ in 0..3 {
                let (mut stream, _) = listener.accept().await.unwrap();
                tokio::spawn(async move {
                    let mut request = Vec::new();
                    while !request.ends_with(b"\r\n\r\n") {
                        request.push(stream.read_u8().await.unwrap());
                    }
                    tokio::time::sleep(Duration::from_millis(150)).await;
                    let _ = stream
                        .write_all(
                            b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",
                        )
                        .await;
                });
            }
        });
        let client = ClientBuilder::new(&url)
            .timeout(Duration::from_millis(20))
            .build()
            .unwrap();
        let request = client.request(Method::GET, "/").build().unwrap();
        assert!(
            matches!(client.execute_raw(request).await.unwrap_err(), crate::error::SdkError::Middleware(error) if error.is_timeout())
        );

        let proxy = client.with_base_url_without_timeout(&url).unwrap();
        let request = proxy.request(Method::GET, "/").build().unwrap();
        assert!(request.timeout().is_none());
        tokio::time::timeout(Duration::from_secs(3), proxy.execute_raw(request))
            .await
            .unwrap()
            .unwrap();

        let request = proxy
            .request(Method::GET, "/")
            .timeout(Duration::from_millis(20))
            .build()
            .unwrap();
        assert!(
            matches!(proxy.execute_raw(request).await.unwrap_err(), crate::error::SdkError::Middleware(error) if error.is_timeout())
        );
        server.await.unwrap();
    }

    #[test]
    fn request_deadlines_are_preserved_when_preparing_external_requests() {
        let client = ClientBuilder::new("http://localhost")
            .timeout(Duration::from_secs(2))
            .build()
            .unwrap();
        let mut request = reqwest::Request::new(Method::GET, "http://localhost/".parse().unwrap());
        client.prepare_request(&mut request);
        assert_eq!(request.timeout(), Some(&Duration::from_secs(2)));
        *request.timeout_mut() = Some(Duration::from_millis(100));
        client.prepare_request(&mut request);
        assert_eq!(request.timeout(), Some(&Duration::from_millis(100)));
    }

    #[test]
    fn installs_rustls_provider() {
        let _ = crate::http_transport::https_builder();
        assert!(
            rustls::crypto::CryptoProvider::get_default().is_some(),
            "rustls crypto provider should be installed"
        );
    }

    #[test]
    fn api_key_bearer_is_preserved_for_proxy_without_implicit_scope_headers() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("listener");
        let address = listener.local_addr().expect("listener address");
        let (tx, rx) = mpsc::channel();
        let server = thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("connection");
            let mut buffer = [0_u8; 4096];
            let bytes_read = stream.read(&mut buffer).expect("request");
            tx.send(String::from_utf8_lossy(&buffer[..bytes_read]).to_string())
                .expect("captured request");
            stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                .expect("response");
        });

        let api_url = format!("http://{address}");
        let client = ClientBuilder::new(&api_url)
            .bearer_token("tl_apiKey_test")
            .build()
            .expect("client");
        let proxy_client = client
            .with_base_url_without_timeout(&api_url)
            .expect("proxy client");
        let request = proxy_client
            .request(Method::POST, "/sandbox-proxy/processes")
            .build()
            .expect("request");
        tokio::runtime::Runtime::new()
            .expect("runtime")
            .block_on(proxy_client.execute_raw(request))
            .expect("response");
        let raw_request = rx.recv().expect("captured request").to_lowercase();
        server.join().expect("server");

        assert!(raw_request.contains("authorization: bearer tl_apikey_test"));
        assert!(!raw_request.contains("x-forwarded-organization-id:"));
        assert!(!raw_request.contains("x-forwarded-project-id:"));
    }
}