cli-engine 0.2.0

Rust CLI framework for consistent command modules
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
use std::{
    collections::BTreeMap,
    io::Write,
    path::Path,
    sync::{Arc, OnceLock, RwLock},
    time::Duration,
};

use reqwest::{Method, StatusCode, header};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
use tokio::time;

use super::{AuthInjector, Error};
use crate::{CliCoreError, Result};

const MAX_RETRIES: usize = 3;
const BASE_BACKOFF: Duration = Duration::from_millis(500);
const BUILTIN_DEFAULT_USER_AGENT: &str = "cli/dev";
static DEFAULT_USER_AGENT: OnceLock<RwLock<String>> = OnceLock::new();

/// Sets the user-agent used by subsequently created [`HttpClient`] values.
pub fn set_default_user_agent(user_agent: impl Into<String>) {
    let lock =
        DEFAULT_USER_AGENT.get_or_init(|| RwLock::new(BUILTIN_DEFAULT_USER_AGENT.to_owned()));
    if let Ok(mut current) = lock.write() {
        *current = user_agent.into();
    }
}

fn default_user_agent() -> String {
    DEFAULT_USER_AGENT
        .get_or_init(|| RwLock::new(BUILTIN_DEFAULT_USER_AGENT.to_owned()))
        .read()
        .map_or_else(
            |_| BUILTIN_DEFAULT_USER_AGENT.to_owned(),
            |value| value.clone(),
        )
}

#[derive(serde::Deserialize)]
struct GraphQlError {
    message: String,
}

#[derive(Default, serde::Deserialize)]
struct GraphQlEnvelope {
    data: Option<Value>,
    #[serde(default)]
    errors: Vec<GraphQlError>,
}

/// Structured debug event emitted by [`TransportLogger`].
#[derive(Clone, Debug)]
pub struct TransportLogEvent {
    /// Event name such as `http request` or `retrying request`.
    pub message: &'static str,
    /// Stable event fields.
    pub fields: BTreeMap<String, String>,
}

/// Debug logger interface for transport events.
pub trait TransportLogger: Send + Sync + std::fmt::Debug {
    /// Records one debug event.
    fn debug(&self, event: &TransportLogEvent);
}

/// Logger that intentionally drops transport events.
#[derive(Clone, Debug, Default)]
pub struct NoopTransportLogger;

impl TransportLogger for NoopTransportLogger {
    fn debug(&self, _event: &TransportLogEvent) {}
}

/// Authenticated HTTP client for CLI command implementations.
///
/// The client covers the transport behavior command authors usually need: auth
/// injection, JSON request/response helpers, structured HTTP errors,
/// idempotent retries, ETag helpers, raw streaming helpers, multipart helpers,
/// and GraphQL envelope decoding.
#[derive(Clone, Debug)]
pub struct HttpClient {
    base: reqwest::Client,
    base_url: String,
    auth: Arc<dyn AuthInjector>,
    user_agent: String,
    default_headers: BTreeMap<String, String>,
    logger: Arc<dyn TransportLogger>,
}

/// Builder for [`HttpClient`].
#[derive(Clone, Debug)]
pub struct HttpClientBuilder {
    base_url: String,
    auth: Arc<dyn AuthInjector>,
    user_agent: String,
    default_headers: BTreeMap<String, String>,
    logger: Arc<dyn TransportLogger>,
}

impl HttpClientBuilder {
    /// Creates a builder with a base URL and auth injector.
    #[must_use]
    pub fn new(base_url: impl Into<String>, auth: Arc<dyn AuthInjector>) -> Self {
        Self {
            base_url: base_url.into(),
            auth,
            user_agent: default_user_agent(),
            default_headers: BTreeMap::new(),
            logger: Arc::new(NoopTransportLogger),
        }
    }

    /// Sets the user-agent for this client.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    /// Alias for [`HttpClientBuilder::user_agent`] for migration readability.
    #[must_use]
    pub fn with_user_agent(self, user_agent: impl Into<String>) -> Self {
        self.user_agent(user_agent)
    }

    /// Sets headers sent on every request.
    #[must_use]
    pub fn default_headers(mut self, headers: BTreeMap<String, String>) -> Self {
        self.default_headers = headers;
        self
    }

    /// Alias for [`HttpClientBuilder::default_headers`] for migration readability.
    #[must_use]
    pub fn with_default_headers(self, headers: BTreeMap<String, String>) -> Self {
        self.default_headers(headers)
    }

    /// Sets the transport debug logger.
    #[must_use]
    pub fn logger(mut self, logger: Arc<dyn TransportLogger>) -> Self {
        self.logger = logger;
        self
    }

    /// Alias for [`HttpClientBuilder::logger`] for migration readability.
    #[must_use]
    pub fn with_logger(self, logger: Arc<dyn TransportLogger>) -> Self {
        self.logger(logger)
    }

    /// Builds the client.
    #[must_use]
    pub fn build(self) -> HttpClient {
        HttpClient {
            base: reqwest::Client::new(),
            base_url: self.base_url,
            auth: self.auth,
            user_agent: self.user_agent,
            default_headers: self.default_headers,
            logger: self.logger,
        }
    }
}

impl HttpClient {
    /// Creates a client builder.
    #[must_use]
    pub fn builder(base_url: impl Into<String>, auth: Arc<dyn AuthInjector>) -> HttpClientBuilder {
        HttpClientBuilder::new(base_url, auth)
    }

    /// Creates a client with default settings.
    #[must_use]
    pub fn new(base_url: impl Into<String>, auth: Arc<dyn AuthInjector>) -> Self {
        HttpClientBuilder::new(base_url, auth).build()
    }

    /// Sends GET and decodes a JSON response.
    pub async fn get<T: Default + DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.do_json(Method::GET, path, Option::<&()>::None).await
    }

    /// Sends GET and checks only for success.
    pub async fn get_without_response(&self, path: &str) -> Result<()> {
        self.do_empty(Method::GET, path, Option::<&()>::None).await
    }

    /// Sends POST with a JSON body and decodes a JSON response.
    pub async fn post<B: Serialize, T: Default + DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.do_json(Method::POST, path, Some(body)).await
    }

    /// Sends POST with a JSON body and checks only for success.
    pub async fn post_without_response<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        self.do_empty(Method::POST, path, Some(body)).await
    }

    /// Sends PUT with a JSON body and decodes a JSON response.
    pub async fn put<B: Serialize, T: Default + DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.do_json(Method::PUT, path, Some(body)).await
    }

    /// Sends PUT with a JSON body and checks only for success.
    pub async fn put_without_response<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        self.do_empty(Method::PUT, path, Some(body)).await
    }

    /// Sends PATCH with a JSON body and decodes a JSON response.
    pub async fn patch<B: Serialize, T: Default + DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        self.do_json(Method::PATCH, path, Some(body)).await
    }

    /// Sends PATCH with a JSON body and checks only for success.
    pub async fn patch_without_response<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        self.do_empty(Method::PATCH, path, Some(body)).await
    }

    /// Sends DELETE and checks for success.
    pub async fn delete(&self, path: &str) -> Result<()> {
        self.do_empty(Method::DELETE, path, Option::<&()>::None)
            .await
    }

    /// Sends DELETE with a JSON body and checks for success.
    pub async fn delete_with_body<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        self.do_empty(Method::DELETE, path, Some(body)).await
    }

    /// Sends GET and returns decoded JSON plus the ETag header.
    pub async fn get_etag<T: Default + DeserializeOwned>(&self, path: &str) -> Result<(T, String)> {
        let response = self.send_get_status_only_retry(path).await?;
        let etag = response
            .headers()
            .get(header::ETAG)
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        let value = decode_json_response(response, "GET", path).await?;
        Ok((value, etag))
    }

    /// Sends GET and returns only the ETag header after checking success.
    pub async fn get_etag_without_response(&self, path: &str) -> Result<String> {
        let response = self.send_get_status_only_retry(path).await?;
        let etag = response
            .headers()
            .get(header::ETAG)
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_owned();
        ensure_success_response(response, "GET", path).await?;
        Ok(etag)
    }

    /// Sends PUT with `If-Match` and decodes a JSON response.
    pub async fn put_if_match<B: Serialize, T: Default + DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
        etag: &str,
    ) -> Result<T> {
        let response = self.send_put_if_match(path, body, etag).await?;
        decode_json_response(response, "PUT", path).await
    }

    /// Sends PUT with `If-Match` and checks only for success.
    pub async fn put_if_match_without_response<B: Serialize>(
        &self,
        path: &str,
        body: &B,
        etag: &str,
    ) -> Result<()> {
        let response = self.send_put_if_match(path, body, etag).await?;
        ensure_success_response(response, "PUT", path).await
    }

    /// Streams a raw GET response body into a writer.
    pub async fn get_raw(&self, path: &str, writer: &mut dyn Write) -> Result<()> {
        let response = self.send_get_raw_status_only_retry(path).await?;
        if response.status().is_client_error() || response.status().is_server_error() {
            return Err(parse_error_response(response, "GET", path).await.into());
        }
        let bytes = response
            .bytes()
            .await
            .map_err(|err| CliCoreError::message(format!("transport: stream response: {err}")))?;
        writer.write_all(&bytes)?;
        Ok(())
    }

    /// Sends GET and returns the raw response body as bytes.
    pub async fn get_bytes(&self, path: &str) -> Result<Vec<u8>> {
        let response = self.send_get_raw_status_only_retry(path).await?;
        if response.status().is_client_error() || response.status().is_server_error() {
            return Err(parse_error_response(response, "GET", path).await.into());
        }
        let bytes = response
            .bytes()
            .await
            .map_err(|err| CliCoreError::message(format!("transport: stream response: {err}")))?;
        Ok(bytes.to_vec())
    }

    /// Sends POST and streams the raw response body into a writer.
    pub async fn post_raw<B: Serialize>(
        &self,
        path: &str,
        body: Option<&B>,
        writer: &mut dyn Write,
    ) -> Result<()> {
        let response = self.send_post_raw_once(path, body).await?;
        if response.status().is_client_error() || response.status().is_server_error() {
            return Err(parse_error_response(response, "POST", path).await.into());
        }
        let bytes = response
            .bytes()
            .await
            .map_err(|err| CliCoreError::message(format!("transport: stream response: {err}")))?;
        writer.write_all(&bytes)?;
        Ok(())
    }

    /// Sends a raw-body request and decodes a JSON response.
    pub async fn do_raw<T: Default + DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        content_type: &str,
        body: impl Into<Vec<u8>>,
    ) -> Result<T> {
        self.do_raw_optional_body(method, path, content_type, Some(body.into()))
            .await
    }

    /// Sends an optional raw-body request and decodes a JSON response.
    pub async fn do_raw_optional_body<T: Default + DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        content_type: &str,
        body: Option<Vec<u8>>,
    ) -> Result<T> {
        let method_text = method.as_str().to_owned();
        let response = self.send_raw_once(method, path, content_type, body).await?;
        decode_json_response(response, &method_text, path).await
    }

    /// Sends a raw-body request and checks only for success.
    pub async fn do_raw_without_response(
        &self,
        method: Method,
        path: &str,
        content_type: &str,
        body: impl Into<Vec<u8>>,
    ) -> Result<()> {
        self.do_raw_optional_body_without_response(method, path, content_type, Some(body.into()))
            .await
    }

    /// Sends an optional raw-body request and checks only for success.
    pub async fn do_raw_optional_body_without_response(
        &self,
        method: Method,
        path: &str,
        content_type: &str,
        body: Option<Vec<u8>>,
    ) -> Result<()> {
        let method_text = method.as_str().to_owned();
        let response = self.send_raw_once(method, path, content_type, body).await?;
        ensure_success_response(response, &method_text, path).await
    }

    /// Sends a multipart file upload and decodes a JSON response.
    pub async fn post_multipart<T: Default + DeserializeOwned>(
        &self,
        path: &str,
        field_name: &str,
        file_path: &Path,
    ) -> Result<T> {
        self.post_multipart_with_fields(path, field_name, file_path, &BTreeMap::new())
            .await
    }

    /// Sends a multipart file upload and checks only for success.
    pub async fn post_multipart_without_response(
        &self,
        path: &str,
        field_name: &str,
        file_path: &Path,
    ) -> Result<()> {
        self.post_multipart_with_fields_without_response(
            path,
            field_name,
            file_path,
            &BTreeMap::new(),
        )
        .await
    }

    /// Sends a multipart file upload with fields and decodes a JSON response.
    pub async fn post_multipart_with_fields<T: Default + DeserializeOwned>(
        &self,
        path: &str,
        file_field: &str,
        file_path: &Path,
        fields: &BTreeMap<String, String>,
    ) -> Result<T> {
        let form = self.multipart_form(file_field, file_path, fields).await?;
        self.send_multipart(path, form).await
    }

    async fn multipart_form(
        &self,
        file_field: &str,
        file_path: &Path,
        fields: &BTreeMap<String, String>,
    ) -> Result<reqwest::multipart::Form> {
        let mut form = reqwest::multipart::Form::new();
        for (key, value) in fields {
            form = form.text(key.clone(), value.clone());
        }
        let file_name = file_path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("file")
            .to_owned();
        let bytes = tokio::fs::read(file_path)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: open file: {err}")))?;
        let part = reqwest::multipart::Part::bytes(bytes).file_name(file_name);
        form = form.part(file_field.to_owned(), part);
        Ok(form)
    }

    /// Sends a multipart file upload with fields and checks only for success.
    pub async fn post_multipart_with_fields_without_response(
        &self,
        path: &str,
        file_field: &str,
        file_path: &Path,
        fields: &BTreeMap<String, String>,
    ) -> Result<()> {
        let form = self.multipart_form(file_field, file_path, fields).await?;
        self.send_multipart_without_response(path, form).await
    }

    /// Sends multipart form fields without a file and decodes a JSON response.
    pub async fn post_multipart_fields<T: Default + DeserializeOwned>(
        &self,
        path: &str,
        fields: &BTreeMap<String, String>,
    ) -> Result<T> {
        let mut form = reqwest::multipart::Form::new();
        for (key, value) in fields {
            form = form.text(key.clone(), value.clone());
        }
        self.send_multipart(path, form).await
    }

    /// Sends multipart form fields without a file and checks only for success.
    pub async fn post_multipart_fields_without_response(
        &self,
        path: &str,
        fields: &BTreeMap<String, String>,
    ) -> Result<()> {
        let mut form = reqwest::multipart::Form::new();
        for (key, value) in fields {
            form = form.text(key.clone(), value.clone());
        }
        self.send_multipart_without_response(path, form).await
    }

    /// Sends a GraphQL request and decodes the `data` envelope into a value.
    pub async fn post_graphql<T: DeserializeOwned + Default>(
        &self,
        path: &str,
        query: &str,
        variables: BTreeMap<String, Value>,
    ) -> Result<T> {
        self.post_graphql_optional_variables(path, query, Some(variables))
            .await
    }

    /// Sends a GraphQL request with optional variables and decodes `data`.
    pub async fn post_graphql_optional_variables<T: DeserializeOwned + Default>(
        &self,
        path: &str,
        query: &str,
        variables: Option<BTreeMap<String, Value>>,
    ) -> Result<T> {
        let mut result = T::default();
        self.post_graphql_optional_variables_into(path, query, variables, &mut result)
            .await?;
        Ok(result)
    }

    /// Sends a GraphQL request and checks only for GraphQL/HTTP success.
    pub async fn post_graphql_without_response(
        &self,
        path: &str,
        query: &str,
        variables: BTreeMap<String, Value>,
    ) -> Result<()> {
        self.post_graphql_optional_variables_without_response(path, query, Some(variables))
            .await
    }

    /// Sends a GraphQL request with optional variables and checks only for success.
    pub async fn post_graphql_optional_variables_without_response(
        &self,
        path: &str,
        query: &str,
        variables: Option<BTreeMap<String, Value>>,
    ) -> Result<()> {
        self.post_graphql_response_envelope(path, query, variables)
            .await?;
        Ok(())
    }

    /// Sends a GraphQL request and decodes `data` into an existing value.
    pub async fn post_graphql_into<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &str,
        variables: BTreeMap<String, Value>,
        result: &mut T,
    ) -> Result<()> {
        self.post_graphql_optional_variables_into(path, query, Some(variables), result)
            .await
    }

    /// Sends a GraphQL request with optional variables and decodes into an existing value.
    pub async fn post_graphql_optional_variables_into<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &str,
        variables: Option<BTreeMap<String, Value>>,
        result: &mut T,
    ) -> Result<()> {
        let envelope = self
            .post_graphql_response_envelope(path, query, variables)
            .await?;
        if let Some(data) = envelope.data
            && !data.is_null()
        {
            *result = serde_json::from_value(data).map_err(|err| {
                CliCoreError::message(format!("transport: decode graphql data: {err}"))
            })?;
        }
        Ok(())
    }

    async fn do_json<B: Serialize, T: Default + DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<T> {
        let method_text = method.as_str().to_owned();
        let response = self.send_with_retry(method, path, body).await?;
        decode_json_response(response, &method_text, path).await
    }

    async fn post_graphql_response_envelope(
        &self,
        path: &str,
        query: &str,
        variables: Option<BTreeMap<String, Value>>,
    ) -> Result<GraphQlEnvelope> {
        #[derive(Serialize)]
        struct Request<'query> {
            query: &'query str,
            variables: Option<BTreeMap<String, Value>>,
        }

        let envelope: GraphQlEnvelope = self.post(path, &Request { query, variables }).await?;
        if !envelope.errors.is_empty() {
            let message = envelope
                .errors
                .iter()
                .map(|error| error.message.as_str())
                .collect::<Vec<_>>()
                .join("; ");
            return Err(CliCoreError::message(format!("graphql: {message}")));
        }
        Ok(envelope)
    }

    async fn send_put_if_match<B: Serialize>(
        &self,
        path: &str,
        body: &B,
        etag: &str,
    ) -> Result<reqwest::Response> {
        let mut request = self
            .build_request(Method::PUT, path, Some(body))?
            .header(header::IF_MATCH, etag)
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        let url = format!("{}{}", self.base_url, path);
        self.log_debug(
            "http request",
            [("method", "PUT".to_owned()), ("url", url.clone())],
        );
        let response = self
            .base
            .execute(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: PUT {path}: {err}")))?;
        self.log_debug(
            "http response",
            [
                ("status", response.status().as_u16().to_string()),
                ("method", "PUT".to_owned()),
                ("url", url),
            ],
        );
        Ok(response)
    }

    async fn send_multipart<T: Default + DeserializeOwned>(
        &self,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> Result<T> {
        let response = self.send_multipart_response(path, form).await?;
        decode_json_response(response, "POST", path).await
    }

    async fn send_multipart_without_response(
        &self,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> Result<()> {
        let response = self.send_multipart_response(path, form).await?;
        ensure_success_response(response, "POST", path).await
    }

    async fn send_multipart_response(
        &self,
        path: &str,
        form: reqwest::multipart::Form,
    ) -> Result<reqwest::Response> {
        let url = format!("{}{}", self.base_url, path);
        let mut builder = self
            .base
            .post(url.clone())
            .header(header::USER_AGENT, self.user_agent.clone())
            .multipart(form);
        for (key, value) in &self.default_headers {
            builder = builder.header(key, value);
        }
        let mut request = builder
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        self.log_debug("http multipart request", [("url", url)]);
        self.base
            .execute(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: POST {path}: {err}")))
    }

    async fn do_empty<B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<()> {
        let method_text = method.as_str().to_owned();
        let response = self.send_with_retry(method, path, body).await?;
        ensure_success_response(response, &method_text, path).await
    }

    async fn send_raw_once(
        &self,
        method: Method,
        path: &str,
        content_type: &str,
        body: Option<Vec<u8>>,
    ) -> Result<reqwest::Response> {
        let url = format!("{}{}", self.base_url, path);
        let method_text = method.as_str().to_owned();
        let mut builder = self
            .base
            .request(method, url)
            .header(header::USER_AGENT, self.user_agent.clone());
        if let Some(body) = body {
            builder = builder.body(body);
        }
        if !content_type.is_empty() {
            builder = builder.header(header::CONTENT_TYPE, content_type);
        }
        for (key, value) in &self.default_headers {
            builder = builder.header(key, value);
        }
        let mut request = builder
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        self.log_debug(
            "http request",
            [
                ("method", method_text.clone()),
                ("url", format!("{}{}", self.base_url, path)),
            ],
        );
        self.base
            .execute(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: {method_text} {path}: {err}")))
    }

    async fn send_get_raw_status_only_retry(&self, path: &str) -> Result<reqwest::Response> {
        let mut last_err = None;
        for attempt in 0..MAX_RETRIES {
            if attempt > 0 {
                let backoff = BASE_BACKOFF * 2_u32.pow(u32::try_from(attempt - 1).unwrap_or(0));
                time::sleep(backoff).await;
            }

            match self.send_get_raw_once(path).await {
                Ok(response) => {
                    if response.status() == StatusCode::TOO_MANY_REQUESTS
                        || response.status().is_server_error()
                    {
                        last_err = Some(CliCoreError::message(format!(
                            "transport: GET {}: status {}",
                            path,
                            response.status().as_u16()
                        )));
                        continue;
                    }
                    return Ok(response);
                }
                Err(err) => last_err = Some(err),
            }
        }
        Err(last_err.unwrap_or_else(|| CliCoreError::message("transport: retry failed")))
    }

    async fn send_get_raw_once(&self, path: &str) -> Result<reqwest::Response> {
        let url = format!("{}{}", self.base_url, path);
        let mut builder = self
            .base
            .get(url.clone())
            .header(header::USER_AGENT, self.user_agent.clone());
        for (key, value) in &self.default_headers {
            builder = builder.header(key, value);
        }
        let mut request = builder
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        self.log_debug("http raw request", [("url", url)]);
        self.base
            .execute(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: GET {path}: {err}")))
    }

    async fn send_post_raw_once<B: Serialize>(
        &self,
        path: &str,
        body: Option<&B>,
    ) -> Result<reqwest::Response> {
        let mut request = self
            .build_request(Method::POST, path, body)?
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        self.log_debug(
            "http post raw request",
            [("url", format!("{}{}", self.base_url, path))],
        );
        self.base
            .execute(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: POST {path}: {err}")))
    }

    async fn send_with_retry<B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<reqwest::Response> {
        let mut last_err = None;
        for attempt in 0..MAX_RETRIES {
            if attempt > 0 {
                let backoff = BASE_BACKOFF * 2_u32.pow(u32::try_from(attempt - 1).unwrap_or(0));
                self.log_debug(
                    "retrying request",
                    [
                        ("attempt", (attempt + 1).to_string()),
                        ("backoff", format!("{backoff:?}")),
                    ],
                );
                time::sleep(backoff).await;
            }

            match self.send_once(method.clone(), path, body).await {
                Ok(response) => {
                    if retryable_status(method.clone(), response.status()) {
                        last_err =
                            Some(retryable_status_error(response, method.as_str(), path).await);
                        continue;
                    }
                    return Ok(response);
                }
                Err(err) if is_idempotent(&method) => {
                    last_err = Some(err);
                }
                Err(err) => return Err(err),
            }
        }
        Err(last_err.unwrap_or_else(|| CliCoreError::message("transport: retry failed")))
    }

    async fn send_get_status_only_retry(&self, path: &str) -> Result<reqwest::Response> {
        let mut last_err = None;
        for attempt in 0..MAX_RETRIES {
            if attempt > 0 {
                let backoff = BASE_BACKOFF * 2_u32.pow(u32::try_from(attempt - 1).unwrap_or(0));
                self.log_debug(
                    "retrying request",
                    [
                        ("attempt", (attempt + 1).to_string()),
                        ("backoff", format!("{backoff:?}")),
                    ],
                );
                time::sleep(backoff).await;
            }

            match self.send_once(Method::GET, path, Option::<&()>::None).await {
                Ok(response) => {
                    if response.status() == StatusCode::TOO_MANY_REQUESTS
                        || response.status().is_server_error()
                    {
                        last_err = Some(CliCoreError::message(format!(
                            "transport: GET {}: status {}",
                            path,
                            response.status().as_u16()
                        )));
                        continue;
                    }
                    return Ok(response);
                }
                Err(err) => last_err = Some(err),
            }
        }
        Err(last_err.unwrap_or_else(|| CliCoreError::message("transport: retry failed")))
    }

    async fn send_once<B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<reqwest::Response> {
        let mut request = self
            .build_request(method.clone(), path, body)?
            .build()
            .map_err(|err| CliCoreError::message(format!("transport: create request: {err}")))?;
        self.inject_auth(&mut request).await?;
        let method_text = method.as_str().to_owned();
        self.log_debug(
            "http request",
            [
                ("method", method_text.clone()),
                ("url", format!("{}{}", self.base_url, path)),
            ],
        );
        let response = self.base.execute(request).await.map_err(|err| {
            CliCoreError::message(format!("transport: {method_text} {path}: {err}"))
        })?;
        self.log_debug(
            "http response",
            [
                ("status", response.status().as_u16().to_string()),
                ("method", method_text),
                ("url", format!("{}{}", self.base_url, path)),
            ],
        );
        Ok(response)
    }

    fn build_request<B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<reqwest::RequestBuilder> {
        let url = format!("{}{}", self.base_url, path);
        let mut builder = self
            .base
            .request(method, url)
            .header(header::USER_AGENT, self.user_agent.clone());
        if let Some(body) = body {
            let body = serde_json::to_vec(body)
                .map_err(|err| CliCoreError::message(format!("transport: marshal body: {err}")))?;
            builder = builder
                .header(header::CONTENT_TYPE, "application/json")
                .body(body);
        }
        for (key, value) in &self.default_headers {
            builder = builder.header(key, value);
        }
        Ok(builder)
    }

    fn log_debug(
        &self,
        message: &'static str,
        fields: impl IntoIterator<Item = (&'static str, String)>,
    ) {
        self.logger.debug(&TransportLogEvent {
            message,
            fields: fields
                .into_iter()
                .map(|(key, value)| (key.to_owned(), value))
                .collect(),
        });
    }

    async fn inject_auth(&self, request: &mut reqwest::Request) -> Result<()> {
        self.auth
            .inject(request)
            .await
            .map_err(|err| CliCoreError::message(format!("transport: auth inject: {err}")))
    }
}

async fn decode_json_response<T: Default + DeserializeOwned>(
    response: reqwest::Response,
    method: &str,
    path: &str,
) -> Result<T> {
    if response.status().is_client_error() || response.status().is_server_error() {
        return Err(parse_error_response(response, method, path).await.into());
    }
    if response.status() == StatusCode::NO_CONTENT {
        return Ok(T::default());
    }
    let body = response
        .bytes()
        .await
        .map_err(|err| CliCoreError::message(format!("transport: decode response: {err}")))?;
    if body.trim_ascii() == b"null" {
        return Ok(T::default());
    }
    serde_json::from_slice::<T>(&body)
        .map_err(|err| CliCoreError::message(format!("transport: decode response: {err}")))
}

async fn ensure_success_response(
    response: reqwest::Response,
    method: &str,
    path: &str,
) -> Result<()> {
    if response.status().is_client_error() || response.status().is_server_error() {
        return Err(parse_error_response(response, method, path).await.into());
    }
    Ok(())
}

/// Converts a non-success HTTP response into the shared transport error shape.
///
/// If the response body already contains an API-style error document, the
/// service message is preserved and the HTTP status is normalized into the
/// error code. Otherwise the method, path, status, and response body are folded
/// into a readable fallback message.
pub async fn parse_error_response(response: reqwest::Response, method: &str, path: &str) -> Error {
    let status = response.status();
    let body = response.text().await.unwrap_or_default();
    parse_error_body(status, &body, method, path)
}

fn parse_error_body(status: StatusCode, body: &str, method: &str, path: &str) -> Error {
    if let Ok(mut api_error) = serde_json::from_str::<Error>(body)
        && !api_error.message.is_empty()
    {
        api_error.code = format!("HTTP_{}", status.as_u16());
        return api_error;
    }
    Error {
        code: format!("HTTP_{}", status.as_u16()),
        message: format!("{} {}: {} {}", method, path, status.as_u16(), body),
        system: String::new(),
        request_id: String::new(),
    }
}

fn retryable_status(method: Method, status: StatusCode) -> bool {
    status == StatusCode::TOO_MANY_REQUESTS || (status.is_server_error() && is_idempotent(&method))
}

async fn retryable_status_error(
    response: reqwest::Response,
    method: &str,
    path: &str,
) -> CliCoreError {
    let status = response.status().as_u16();
    match response.text().await {
        Ok(body) => CliCoreError::message(format!(
            "transport: {method} {path}: status {status}: {body}"
        )),
        Err(err) => CliCoreError::message(format!(
            "transport: {method} {path}: status {status} (body read failed: {err})"
        )),
    }
}

fn is_idempotent(method: &Method) -> bool {
    matches!(*method, Method::GET | Method::HEAD | Method::DELETE)
}