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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
use reqwest::{Client, Response, StatusCode};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, error, info, warn};
use crate::configuration::Configuration;
use crate::error::{ConductorError, Result};
use crate::http::metrics::HttpMetricsObserver;
/// Token response from authentication endpoint.
#[derive(Debug, serde::Deserialize)]
struct TokenResponse {
token: String,
}
/// Maximum consecutive auth failures before stopping retry attempts.
const MAX_AUTH_FAILURES: u32 = 5;
/// Pairs a resolved request path with a bounded-cardinality metric template.
///
/// For **static** endpoints (no dynamic segments) simply pass a `&str` —
/// the [`From<&str>`] impl uses the same string for both the request path
/// and the metric label.
///
/// For **dynamic** endpoints use [`ApiPath::templated`] to supply the
/// resolved path alongside its template:
///
/// ```ignore
/// let path = format!("/workflow/{}", workflow_id);
/// api.get(ApiPath::templated(&path, "/workflow/{workflowId}")).await
/// ```
pub struct ApiPath<'a> {
pub(crate) path: &'a str,
pub(crate) metric_uri: &'a str,
}
impl<'a> ApiPath<'a> {
/// Use when the resolved path differs from the metric template.
#[must_use]
pub fn templated(path: &'a str, template: &'a str) -> Self {
Self {
path,
metric_uri: template,
}
}
}
impl<'a> From<&'a str> for ApiPath<'a> {
fn from(path: &'a str) -> Self {
Self {
path,
metric_uri: path,
}
}
}
/// HTTP API client for Conductor server.
///
/// Thread-safe and cloneable. Multiple clones share the same connection pool
/// and authentication state.
///
/// # Authentication
///
/// The client automatically handles authentication when credentials are configured:
/// - Fetches tokens from `/token` endpoint using key/secret
/// - Proactively refreshes tokens before TTL expiration (default: 45 min)
/// - Automatically retries requests on 401 after refreshing token
/// - Gracefully handles OSS Conductor (no auth endpoint returns 404)
///
/// # Environment Variables
///
/// Configure via environment variables or `.env` file:
/// - `CONDUCTOR_SERVER_URL`: Server API URL (default: <http://localhost:8080/api>)
/// - `CONDUCTOR_AUTH_KEY`: Authentication key ID (Orkes Conductor)
/// - `CONDUCTOR_AUTH_SECRET`: Authentication secret (Orkes Conductor)
/// - `CONDUCTOR_AUTH_TOKEN_TTL_MINS`: Token TTL in minutes (default: 45)
/// - `CONDUCTOR_DEBUG`: Enable debug logging (true/false)
/// - `CONDUCTOR_TIMEOUT_SECS`: Request timeout in seconds (default: 30)
#[derive(Clone)]
pub struct ApiClient {
client: Client,
config: Arc<RwLock<Configuration>>,
base_url: String,
/// Track consecutive auth failures for backoff.
auth_failures: Arc<RwLock<u32>>,
/// Last time we attempted token refresh (for backoff).
last_refresh_attempt: Arc<RwLock<Option<Instant>>>,
/// Mutex to ensure only one token refresh happens at a time.
token_refresh_lock: Arc<Mutex<()>>,
/// Cached result of OSS detection (None = not yet probed).
is_oss: Arc<RwLock<Option<bool>>>,
/// HTTP metrics observer. `None` when the client is created standalone
/// (without a `TaskHandler`). `Some` after [`set_http_observer`](Self::set_http_observer).
http_metrics: Option<Arc<dyn HttpMetricsObserver>>,
}
impl ApiClient {
/// Create a new API client.
///
/// The client will automatically handle authentication if credentials are
/// configured via `CONDUCTOR_AUTH_KEY` and `CONDUCTOR_AUTH_SECRET` environment
/// variables, or via `Configuration::with_auth()`.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the underlying `reqwest` client fails to build
/// (e.g. TLS backend initialization failure) -- this doesn't make any network request.
pub fn new(config: Configuration) -> Result<Self> {
let client = Client::builder()
.timeout(config.timeout)
.connect_timeout(config.connect_timeout)
.pool_max_idle_per_host(10)
.build()?;
let base_url = config.server_api_url.trim_end_matches('/').to_owned();
Ok(Self {
client,
config: Arc::new(RwLock::new(config)),
base_url,
auth_failures: Arc::new(RwLock::new(0)),
last_refresh_attempt: Arc::new(RwLock::new(None)),
token_refresh_lock: Arc::new(Mutex::new(())),
is_oss: Arc::new(RwLock::new(None)),
http_metrics: None,
})
}
/// Get the base URL.
#[must_use]
pub fn base_url(&self) -> &str {
&self.base_url
}
/// Install an HTTP metrics observer on an existing client.
///
/// All subsequent clones share the same observer via `Arc`.
pub fn set_http_observer(&mut self, observer: Arc<dyn HttpMetricsObserver>) {
self.http_metrics = Some(observer);
}
/// Unified post-request bookkeeping: tracing log + observer callback.
///
/// `path` is the interpolated request path (for the tracing log).
/// `metric_uri` is the bounded-cardinality path template used as the
/// `uri` label (e.g. `/tasks/poll/batch/{taskType}`).
/// `status_str` is the HTTP status code rendered as a string, or `"0"`
/// for pre-response transport errors.
#[inline]
fn record_request(
&self,
method: &str,
path: &str,
metric_uri: &str,
status_str: &str,
duration: Duration,
) {
debug!(
method = method,
url = %format!("{}{}", self.base_url, path),
status = status_str,
duration_ms = %duration.as_millis(),
"API request completed"
);
if let Some(obs) = &self.http_metrics {
obs.observe(method, metric_uri, status_str, duration);
}
}
/// Convenience: call [`record_request`](Self::record_request) with a
/// successful response's status code.
#[inline]
fn record_response(
&self,
method: &str,
path: &str,
metric_uri: &str,
status: StatusCode,
duration: Duration,
) {
self.record_request(method, path, metric_uri, status.as_str(), duration);
}
/// Send a prepared request, recording the outcome (success *and* transport
/// failures) to the `http_metrics` observer and the `debug!` tracing log.
///
/// Transport-level failures (no HTTP status produced) are observed with
/// `status = "0"`, matching the convention of the canonical SDK metrics
/// harmonization plan.
async fn send_observed(
&self,
method: &str,
path: &str,
metric_uri: &str,
request: reqwest::RequestBuilder,
) -> Result<Response> {
let start = Instant::now();
let result = request.send().await;
let duration = start.elapsed();
match &result {
Ok(resp) => self.record_response(method, path, metric_uri, resp.status(), duration),
Err(_) => self.record_request(method, path, metric_uri, "0", duration),
}
result.map_err(ConductorError::Http)
}
/// GET request.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get<T>(&self, path: impl Into<ApiPath<'_>>) -> Result<T>
where
T: DeserializeOwned,
{
let p = path.into();
self.request::<(), T>(reqwest::Method::GET, p.path, p.metric_uri, None)
.await
}
/// GET request returning raw text (for endpoints that respond with
/// `text/plain` rather than JSON, e.g. secret values)
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn get_text(&self, path: impl Into<ApiPath<'_>>) -> Result<String> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.get(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("GET", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(response.text().await?)
} else {
Err(self.handle_error_response(response).await)
}
}
/// GET request with query parameters.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_with_params<T>(
&self,
path: impl Into<ApiPath<'_>>,
params: &[(&str, &str)],
) -> Result<T>
where
T: DeserializeOwned,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.get(&url);
request = self.add_auth_header(request).await?;
request = request.query(params);
let response = self
.send_observed("GET", p.path, p.metric_uri, request)
.await?;
self.handle_response(response).await
}
/// GET request that returns the raw, unbuffered [`Response`] instead of deserializing it.
///
/// For endpoints whose body is consumed incrementally (e.g. Server-Sent Events) rather than
/// parsed as a single JSON document. Applies the same auth-header/refresh handling as
/// [`get`](Self::get), but does not retry on 401 — a streaming caller has already begun
/// reading the body by the time a status past the headers would be observed, so there is no
/// safe point to re-issue the request transparently.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn get_stream(&self, path: impl Into<ApiPath<'_>>) -> Result<Response> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.get(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("GET", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(response)
} else {
Err(self.handle_error_response(response).await)
}
}
/// POST request.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn post<B, T>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<T>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
let p = path.into();
self.request_with_body(reqwest::Method::POST, p.path, p.metric_uri, body)
.await
}
/// POST request returning raw text.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn post_text<B>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<String>
where
B: Serialize,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(response.text().await?)
} else {
Err(self.handle_error_response(response).await)
}
}
/// PUT request.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn put<B, T>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<T>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
let p = path.into();
self.request_with_body(reqwest::Method::PUT, p.path, p.metric_uri, body)
.await
}
/// DELETE request.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn delete<T>(&self, path: impl Into<ApiPath<'_>>) -> Result<T>
where
T: DeserializeOwned,
{
let p = path.into();
self.request::<(), T>(reqwest::Method::DELETE, p.path, p.metric_uri, None)
.await
}
/// DELETE request with no response body.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn delete_no_content(&self, path: impl Into<ApiPath<'_>>) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.delete(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("DELETE", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() || status == StatusCode::NO_CONTENT {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// DELETE request with body.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn delete_with_body<B>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<()>
where
B: Serialize + ?Sized,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.delete(&url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed("DELETE", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() || status == StatusCode::NO_CONTENT {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// DELETE request with query parameters.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn delete_with_params(
&self,
path: impl Into<ApiPath<'_>>,
params: &[(&str, &str)],
) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.delete(&url);
request = self.add_auth_header(request).await?;
request = request.query(params);
let response = self
.send_observed("DELETE", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() || status == StatusCode::NO_CONTENT {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// POST request with no response.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn post_no_response<B>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<()>
where
B: Serialize + ?Sized,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// POST request with no body.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn post_no_body<T>(&self, path: impl Into<ApiPath<'_>>) -> Result<T>
where
T: DeserializeOwned,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
self.handle_response(response).await
}
/// POST request with no body and no response.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn post_no_body_no_response(&self, path: impl Into<ApiPath<'_>>) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// PUT request with no response.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn put_no_response<B>(&self, path: impl Into<ApiPath<'_>>, body: &B) -> Result<()>
where
B: Serialize + ?Sized,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.put(&url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed("PUT", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// PUT request with no request body and no response body
///
/// For endpoints mapped as a bare `@PutMapping` with no `@RequestBody` --
/// e.g. `/scheduler/schedules/{name}/pause`. Sends no payload and no
/// `Content-Type` at all, rather than a JSON `null`.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn put_no_body(&self, path: impl Into<ApiPath<'_>>) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.put(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("PUT", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// PUT request with raw text body.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn put_raw(&self, path: impl Into<ApiPath<'_>>, body: &str) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.put(&url);
request = self.add_auth_header(request).await?;
request = request.body(body.to_owned());
request = request.header("Content-Type", "text/plain");
let response = self
.send_observed("PUT", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// POST request with JSON body and query parameters.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn post_with_params<B, T>(
&self,
path: impl Into<ApiPath<'_>>,
body: &B,
params: &[(&str, &str)],
) -> Result<T>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
request = request.query(params);
request = request.json(body);
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
self.handle_response(response).await
}
/// POST request with raw text body and query parameters.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn post_raw_with_params(
&self,
path: impl Into<ApiPath<'_>>,
body: &str,
params: &[(&str, &str)],
) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.post(&url);
request = self.add_auth_header(request).await?;
request = request.query(params);
request = request.body(body.to_owned());
request = request.header("Content-Type", "text/plain");
let response = self
.send_observed("POST", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// PUT request with raw text body and query parameters.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn put_raw_with_params(
&self,
path: impl Into<ApiPath<'_>>,
body: &str,
params: &[(&str, &str)],
) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.put(&url);
request = self.add_auth_header(request).await?;
request = request.query(params);
request = request.body(body.to_owned());
request = request.header("Content-Type", "text/plain");
let response = self
.send_observed("PUT", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// GET request with no response.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn get_no_response(&self, path: impl Into<ApiPath<'_>>) -> Result<()> {
let p = path.into();
let url = format!("{}{}", self.base_url, p.path);
let mut request = self.client.get(&url);
request = self.add_auth_header(request).await?;
let response = self
.send_observed("GET", p.path, p.metric_uri, request)
.await?;
let status = response.status();
if status.is_success() {
Ok(())
} else {
Err(self.handle_error_response(response).await)
}
}
/// Generic request method (no body) with automatic 401 retry.
async fn request<B, T>(
&self,
method: reqwest::Method,
path: &str,
metric_uri: &str,
body: Option<&B>,
) -> Result<T>
where
B: Serialize,
T: DeserializeOwned,
{
let url = format!("{}{}", self.base_url, path);
let method_str = method.as_str().to_owned();
let mut request = self.client.request(method.clone(), &url);
request = self.add_auth_header(request).await?;
if let Some(b) = body {
request = request.json(b);
}
let response = self
.send_observed(&method_str, path, metric_uri, request)
.await?;
let status = response.status();
// If 401, try refreshing token and retry once
if self.is_token_expired_error(status) {
debug!(method = %method, url = %url, "Got 401, refreshing token and retrying");
if self.force_refresh_token().await.is_ok() {
let mut request = self.client.request(method.clone(), &url);
request = self.add_auth_header(request).await?;
if let Some(b) = body {
request = request.json(b);
}
let response = self
.send_observed(&method_str, path, metric_uri, request)
.await?;
return self.handle_response(response).await;
}
}
self.handle_response(response).await
}
/// Generic request method with body (supports slices) with automatic 401 retry.
async fn request_with_body<B, T>(
&self,
method: reqwest::Method,
path: &str,
metric_uri: &str,
body: &B,
) -> Result<T>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
let url = format!("{}{}", self.base_url, path);
let method_str = method.as_str().to_owned();
let mut request = self.client.request(method.clone(), &url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed(&method_str, path, metric_uri, request)
.await?;
let status = response.status();
// If 401, try refreshing token and retry once
if self.is_token_expired_error(status) {
debug!(method = %method, url = %url, "Got 401, refreshing token and retrying");
if self.force_refresh_token().await.is_ok() {
let mut request = self.client.request(method.clone(), &url);
request = self.add_auth_header(request).await?;
request = request.json(body);
let response = self
.send_observed(&method_str, path, metric_uri, request)
.await?;
return self.handle_response(response).await;
}
}
self.handle_response(response).await
}
/// Handle successful response, deserializing the body.
async fn handle_response<T>(&self, response: Response) -> Result<T>
where
T: DeserializeOwned,
{
let status = response.status();
if status.is_success() {
// Reset auth failures on successful request
*self.auth_failures.write().await = 0;
let bytes = response.bytes().await.map_err(ConductorError::Http)?;
let text = String::from_utf8_lossy(&bytes);
if text.trim().is_empty() {
// Try to deserialize from empty - works for Option<T> or ()
serde_json::from_str("null").map_err(ConductorError::Json)
} else {
serde_json::from_str(&text).map_err(|e| {
error!(body = %text, error = %e, "Failed to parse response");
ConductorError::Json(e)
})
}
} else {
Err(self.handle_error_response(response).await)
}
}
/// Check if a 401 response indicates an expired/invalid token that should trigger retry.
fn is_token_expired_error(&self, status: StatusCode) -> bool {
status == StatusCode::UNAUTHORIZED
}
/// Handle error response.
async fn handle_error_response(&self, response: Response) -> ConductorError {
let status = response.status();
let status_code = status.as_u16();
// Track auth failures for backoff
if status == StatusCode::UNAUTHORIZED {
let mut failures = self.auth_failures.write().await;
*failures += 1;
warn!(failures = *failures, "Authentication failure");
}
let message = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_owned());
match status {
StatusCode::UNAUTHORIZED => ConductorError::auth(format!("Unauthorized: {message}")),
StatusCode::NOT_FOUND => ConductorError::api(format!("Not found: {message}"), None),
StatusCode::BAD_REQUEST => ConductorError::api(format!("Bad request: {message}"), None),
_ => ConductorError::server(status_code, message),
}
}
/// Add authentication header to request.
///
/// Uses a mutex to ensure only one token refresh happens at a time,
/// preventing thundering herd on token expiration. Also proactively
/// refreshes tokens before TTL expiration.
async fn add_auth_header(
&self,
request: reqwest::RequestBuilder,
) -> Result<reqwest::RequestBuilder> {
// First check current state (fast path, no lock needed for read)
{
let config = self.config.read().await;
// Auth disabled (e.g., OSS Conductor) - return request as-is
if config.auth_disabled {
return Ok(request);
}
// No auth credentials configured - return request as-is
if !config.has_auth() {
return Ok(request);
}
// Have a valid token that doesn't need refresh - use it
if let Some(ref token) = config.auth_token {
if !config.token_needs_refresh() {
return Ok(request.header("X-Authorization", token));
}
}
}
// Need to refresh token - acquire the refresh lock to prevent concurrent refreshes
let _refresh_guard = self.token_refresh_lock.lock().await;
// Double-check if another thread already refreshed the token while we waited
{
let config = self.config.read().await;
if config.auth_disabled {
return Ok(request);
}
if let Some(ref token) = config.auth_token {
if !config.token_needs_refresh() {
return Ok(request.header("X-Authorization", token));
}
}
}
// Actually refresh the token
match self.refresh_token().await {
Ok(()) => {}
Err(e) => {
// Check if auth was disabled during refresh (404 from OSS Conductor)
let config = self.config.read().await;
if config.auth_disabled {
return Ok(request);
}
return Err(e);
}
}
// Now get the new token
let config = self.config.read().await;
if let Some(ref token) = config.auth_token {
return Ok(request.header("X-Authorization", token));
}
Ok(request)
}
/// Refresh authentication token.
///
/// Handles several scenarios:
/// - Success: Updates token and resets failure counter
/// - 404: OSS Conductor without auth - disables auth for future requests
/// - 401: Invalid credentials - increments failure counter with backoff
/// - Other errors: Network issues, etc.
async fn refresh_token(&self) -> Result<()> {
let config = self.config.read().await;
// Check if auth is disabled
if config.auth_disabled {
return Ok(());
}
let (key, secret) = match (&config.auth_key, &config.auth_secret) {
(Some(k), Some(s)) => (k.clone(), s.clone()),
_ => return Ok(()),
};
// Check failure count and apply backoff
let failures = *self.auth_failures.read().await;
if failures >= MAX_AUTH_FAILURES {
error!(
failures = failures,
max = MAX_AUTH_FAILURES,
"Token refresh has failed too many times. Please check your CONDUCTOR_AUTH_KEY and CONDUCTOR_AUTH_SECRET."
);
return Err(ConductorError::auth(format!(
"Token refresh failed {failures} times. Check your authentication credentials."
)));
}
// Calculate backoff based on failures (exponential: 1s, 2s, 4s, 8s, 16s)
if failures > 0 {
// Check time since last attempt
if let Some(last_attempt) = *self.last_refresh_attempt.read().await {
let backoff = Duration::from_secs(2_u64.pow(failures.min(5)));
let elapsed = last_attempt.elapsed();
if elapsed < backoff {
let remaining = backoff.checked_sub(elapsed).unwrap_or_default();
warn!(
failures = failures,
backoff_secs = backoff.as_secs(),
remaining_secs = remaining.as_secs(),
"Auth backoff active, waiting before retry"
);
tokio::time::sleep(remaining).await;
}
}
}
drop(config); // Release read lock
// Update last refresh attempt time
*self.last_refresh_attempt.write().await = Some(Instant::now());
debug!("Refreshing authentication token");
let url = format!("{}/token", self.base_url);
let body = serde_json::json!({
"keyId": key,
"keySecret": secret
});
let response = match self.client.post(&url).json(&body).send().await {
Ok(resp) => {
debug!(
method = "POST",
url = %url,
status = %resp.status(),
"Token refresh request completed"
);
resp
}
Err(e) => {
*self.auth_failures.write().await += 1;
error!(error = %e, "Network error during token refresh");
return Err(ConductorError::Http(e));
}
};
let status = response.status();
if status.is_success() {
let token_response: TokenResponse = response.json().await?;
let mut config = self.config.write().await;
config.update_token(token_response.token);
*self.auth_failures.write().await = 0;
debug!("Token refreshed successfully");
Ok(())
} else if status == StatusCode::NOT_FOUND {
// 404 indicates OSS Conductor without authentication endpoint
// Disable auth to prevent future attempts
info!(
"Authentication endpoint /token not found (404). \
Running in open mode without authentication (Conductor OSS)."
);
let mut config = self.config.write().await;
config.disable_auth();
*self.auth_failures.write().await = 0;
*self.is_oss.write().await = Some(true);
Ok(())
} else if status == StatusCode::UNAUTHORIZED {
// 401 from /token endpoint - invalid credentials
let message = response.text().await.unwrap_or_default();
let mut failures = self.auth_failures.write().await;
*failures += 1;
error!(
status = %status,
failures = *failures,
"Authentication failed. Please check your CONDUCTOR_AUTH_KEY and CONDUCTOR_AUTH_SECRET."
);
Err(ConductorError::auth(format!(
"Invalid credentials: {} (attempt {}/{})",
message, *failures, MAX_AUTH_FAILURES
)))
} else {
// Other errors
let message = response.text().await.unwrap_or_default();
*self.auth_failures.write().await += 1;
error!(status = %status, message = %message, "Failed to refresh token");
Err(ConductorError::auth(format!(
"Failed to get token: {status} - {message}"
)))
}
}
/// Force refresh the authentication token.
///
/// Called when a request fails with 401, indicating the token may have
/// been invalidated server-side before TTL expiration.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn force_refresh_token(&self) -> Result<()> {
// Clear current token to force refresh
{
let mut config = self.config.write().await;
config.clear_token();
}
// Acquire lock and refresh
let _refresh_guard = self.token_refresh_lock.lock().await;
self.refresh_token().await
}
/// Check whether the server is OSS Conductor (vs Orkes Enterprise).
///
/// Probes `POST /token` with dummy credentials on first call and caches
/// the result. OSS Conductor returns 404 (the endpoint does not exist);
/// Enterprise returns a non-404 status (e.g. 401/403 for invalid creds).
///
/// This mirrors the detection strategy used by the JavaScript SDK.
pub async fn is_oss(&self) -> bool {
// Fast path: already probed
if let Some(cached) = *self.is_oss.read().await {
return cached;
}
// Probe /token
let url = format!("{}/token", self.base_url);
let body = serde_json::json!({"keyId": "probe", "keySecret": "probe"});
let is_oss = match self.client.post(&url).json(&body).send().await {
Ok(resp) => resp.status() == StatusCode::NOT_FOUND,
Err(_) => false,
};
info!(
"Server detection: {} (POST {} \u{2192} {})",
if is_oss { "OSS" } else { "Enterprise" },
url,
if is_oss { "404" } else { "non-404" }
);
*self.is_oss.write().await = Some(is_oss);
is_oss
}
/// Get configuration (for reading settings).
pub async fn get_config(&self) -> Configuration {
self.config.read().await.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_api_client_creation() {
let config = Configuration::new("http://localhost:8080/api");
let client = ApiClient::new(config);
assert!(client.is_ok());
let client = client.unwrap();
assert_eq!(client.base_url(), "http://localhost:8080/api");
}
}