-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathlib.rs
More file actions
2049 lines (1875 loc) · 74.2 KB
/
lib.rs
File metadata and controls
2049 lines (1875 loc) · 74.2 KB
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
#![warn(missing_docs)] // error if there are missing docs
//! This crate contains client implementations that can be used to contact the Temporal service.
//!
//! It implements auto-retry behavior and metrics collection.
#[macro_use]
extern crate tracing;
pub mod callback_based;
mod metrics;
/// Visible only for tests
#[doc(hidden)]
pub mod proxy;
mod raw;
mod retry;
mod worker_registry;
mod workflow_handle;
pub use crate::{
proxy::HttpConnectProxyOptions,
retry::{CallType, RETRYABLE_ERROR_CODES, RetryClient},
};
pub use metrics::{LONG_REQUEST_LATENCY_HISTOGRAM_NAME, REQUEST_LATENCY_HISTOGRAM_NAME};
pub use raw::{CloudService, HealthService, OperatorService, TestService, WorkflowService};
pub use temporal_sdk_core_protos::temporal::api::{
enums::v1::ArchivalState,
filter::v1::{StartTimeFilter, StatusFilter, WorkflowExecutionFilter, WorkflowTypeFilter},
workflowservice::v1::{
list_closed_workflow_executions_request::Filters as ListClosedFilters,
list_open_workflow_executions_request::Filters as ListOpenFilters,
},
};
pub use tonic;
pub use worker_registry::{Slot, SlotManager, SlotProvider, WorkerKey};
pub use workflow_handle::{
GetWorkflowResultOpts, WorkflowExecutionInfo, WorkflowExecutionResult, WorkflowHandle,
};
use crate::{
metrics::{ChannelOrGrpcOverride, GrpcMetricSvc, MetricsContext},
raw::{AttachMetricLabels, sealed::RawClientLike},
sealed::WfHandleClient,
workflow_handle::UntypedWorkflowHandle,
};
use backoff::{ExponentialBackoff, SystemClock, exponential};
use http::{Uri, uri::InvalidUri};
use parking_lot::RwLock;
use std::{
collections::HashMap,
fmt::{Debug, Formatter},
ops::{Deref, DerefMut},
str::FromStr,
sync::{Arc, OnceLock},
time::{Duration, Instant},
};
use temporal_sdk_core_api::telemetry::metrics::TemporalMeter;
use temporal_sdk_core_protos::{
TaskToken,
coresdk::IntoPayloadsExt,
grpc::health::v1::health_client::HealthClient,
temporal::api::{
cloud::cloudservice::v1::cloud_service_client::CloudServiceClient,
common,
common::v1::{Header, Payload, Payloads, RetryPolicy, WorkflowExecution, WorkflowType},
enums::v1::{TaskQueueKind, WorkflowIdConflictPolicy, WorkflowIdReusePolicy},
operatorservice::v1::operator_service_client::OperatorServiceClient,
query::v1::WorkflowQuery,
replication::v1::ClusterReplicationConfig,
taskqueue::v1::TaskQueue,
testservice::v1::test_service_client::TestServiceClient,
update,
workflowservice::v1::{workflow_service_client::WorkflowServiceClient, *},
},
};
use tonic::{
Code,
body::Body,
client::GrpcService,
codegen::InterceptedService,
metadata::{
AsciiMetadataKey, AsciiMetadataValue, BinaryMetadataKey, BinaryMetadataValue, MetadataMap,
MetadataValue,
},
service::Interceptor,
transport::{Certificate, Channel, Endpoint, Identity},
};
use tower::ServiceBuilder;
use url::Url;
use uuid::Uuid;
static CLIENT_NAME_HEADER_KEY: &str = "client-name";
static CLIENT_VERSION_HEADER_KEY: &str = "client-version";
static TEMPORAL_NAMESPACE_HEADER_KEY: &str = "temporal-namespace";
/// Key used to communicate when a GRPC message is too large
pub static MESSAGE_TOO_LARGE_KEY: &str = "message-too-large";
/// Key used to indicate a error was returned by the retryer because of the short-circuit predicate
pub static ERROR_RETURNED_DUE_TO_SHORT_CIRCUIT: &str = "short-circuit";
/// The server times out polls after 60 seconds. Set our timeout to be slightly beyond that.
const LONG_POLL_TIMEOUT: Duration = Duration::from_secs(70);
const OTHER_CALL_TIMEOUT: Duration = Duration::from_secs(30);
type Result<T, E = tonic::Status> = std::result::Result<T, E>;
/// Options for the connection to the temporal server. Construct with [ClientOptionsBuilder]
#[derive(Clone, Debug, derive_builder::Builder)]
#[non_exhaustive]
pub struct ClientOptions {
/// The URL of the Temporal server to connect to
#[builder(setter(into))]
pub target_url: Url,
/// The name of the SDK being implemented on top of core. Is set as `client-name` header in
/// all RPC calls
#[builder(setter(into))]
pub client_name: String,
/// The version of the SDK being implemented on top of core. Is set as `client-version` header
/// in all RPC calls. The server decides if the client is supported based on this.
#[builder(setter(into))]
pub client_version: String,
/// A human-readable string that can identify this process. Defaults to empty string.
#[builder(setter(into), default)]
pub identity: String,
/// If specified, use TLS as configured by the [TlsConfig] struct. If this is set core will
/// attempt to use TLS when connecting to the Temporal server. Lang SDK is expected to pass any
/// certs or keys as bytes, loading them from disk itself if needed.
#[builder(setter(strip_option), default)]
pub tls_cfg: Option<TlsConfig>,
/// Retry configuration for the server client. Default is [RetryConfig::default]
#[builder(default)]
pub retry_config: RetryConfig,
/// If set, override the origin used when connecting. May be useful in rare situations where tls
/// verification needs to use a different name from what should be set as the `:authority`
/// header. If [TlsConfig::domain] is set, and this is not, this will be set to
/// `https://<domain>`, effectively making the `:authority` header consistent with the domain
/// override.
#[builder(default)]
pub override_origin: Option<Uri>,
/// If set (which it is by default), HTTP2 gRPC keep alive will be enabled.
#[builder(default = "Some(ClientKeepAliveConfig::default())")]
pub keep_alive: Option<ClientKeepAliveConfig>,
/// HTTP headers to include on every RPC call.
///
/// These must be valid gRPC metadata keys, and must not be binary metadata keys (ending in
/// `-bin). To set binary headers, use [ClientOptions::binary_headers]. Invalid header keys or
/// values will cause an error to be returned when connecting.
#[builder(default)]
pub headers: Option<HashMap<String, String>>,
/// HTTP headers to include on every RPC call as binary gRPC metadata (encoded as base64).
///
/// These must be valid binary gRPC metadata keys (and end with a `-bin` suffix). Invalid
/// header keys will cause an error to be returned when connecting.
#[builder(default)]
pub binary_headers: Option<HashMap<String, Vec<u8>>>,
/// API key which is set as the "Authorization" header with "Bearer " prepended. This will only
/// be applied if the headers don't already have an "Authorization" header.
#[builder(default)]
pub api_key: Option<String>,
/// HTTP CONNECT proxy to use for this client.
#[builder(default)]
pub http_connect_proxy: Option<HttpConnectProxyOptions>,
/// If set true, error code labels will not be included on request failure metrics.
#[builder(default)]
pub disable_error_code_metric_tags: bool,
/// If set true, get_system_info will not be called upon connection
#[builder(default)]
pub skip_get_system_info: bool,
}
/// Configuration options for TLS
#[derive(Clone, Debug, Default)]
pub struct TlsConfig {
/// Bytes representing the root CA certificate used by the server. If not set, and the server's
/// cert is issued by someone the operating system trusts, verification will still work (ex:
/// Cloud offering).
pub server_root_ca_cert: Option<Vec<u8>>,
/// Sets the domain name against which to verify the server's TLS certificate. If not provided,
/// the domain name will be extracted from the URL used to connect.
pub domain: Option<String>,
/// TLS info for the client. If specified, core will attempt to use mTLS.
pub client_tls_config: Option<ClientTlsConfig>,
}
/// If using mTLS, both the client cert and private key must be specified, this contains them.
#[derive(Clone)]
pub struct ClientTlsConfig {
/// The certificate for this client, encoded as PEM
pub client_cert: Vec<u8>,
/// The private key for this client, encoded as PEM
pub client_private_key: Vec<u8>,
}
/// Client keep alive configuration.
#[derive(Clone, Debug)]
pub struct ClientKeepAliveConfig {
/// Interval to send HTTP2 keep alive pings.
pub interval: Duration,
/// Timeout that the keep alive must be responded to within or the connection will be closed.
pub timeout: Duration,
}
impl Default for ClientKeepAliveConfig {
fn default() -> Self {
Self {
interval: Duration::from_secs(30),
timeout: Duration::from_secs(15),
}
}
}
/// Configuration for retrying requests to the server
#[derive(Clone, Debug, PartialEq)]
pub struct RetryConfig {
/// initial wait time before the first retry.
pub initial_interval: Duration,
/// randomization jitter that is used as a multiplier for the current retry interval
/// and is added or subtracted from the interval length.
pub randomization_factor: f64,
/// rate at which retry time should be increased, until it reaches max_interval.
pub multiplier: f64,
/// maximum amount of time to wait between retries.
pub max_interval: Duration,
/// maximum total amount of time requests should be retried for, if None is set then no limit
/// will be used.
pub max_elapsed_time: Option<Duration>,
/// maximum number of retry attempts.
pub max_retries: usize,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
initial_interval: Duration::from_millis(100), // 100 ms wait by default.
randomization_factor: 0.2, // +-20% jitter.
multiplier: 1.7, // each next retry delay will increase by 70%
max_interval: Duration::from_secs(5), // until it reaches 5 seconds.
max_elapsed_time: Some(Duration::from_secs(10)), // 10 seconds total allocated time for all retries.
max_retries: 10,
}
}
}
impl RetryConfig {
pub(crate) const fn task_poll_retry_policy() -> Self {
Self {
initial_interval: Duration::from_millis(200),
randomization_factor: 0.2,
multiplier: 2.0,
max_interval: Duration::from_secs(10),
max_elapsed_time: None,
max_retries: 0,
}
}
pub(crate) const fn throttle_retry_policy() -> Self {
Self {
initial_interval: Duration::from_secs(1),
randomization_factor: 0.2,
multiplier: 2.0,
max_interval: Duration::from_secs(10),
max_elapsed_time: None,
max_retries: 0,
}
}
/// A retry policy that never retires
pub const fn no_retries() -> Self {
Self {
initial_interval: Duration::from_secs(0),
randomization_factor: 0.0,
multiplier: 1.0,
max_interval: Duration::from_secs(0),
max_elapsed_time: None,
max_retries: 1,
}
}
pub(crate) fn into_exp_backoff<C>(self, clock: C) -> exponential::ExponentialBackoff<C> {
exponential::ExponentialBackoff {
current_interval: self.initial_interval,
initial_interval: self.initial_interval,
randomization_factor: self.randomization_factor,
multiplier: self.multiplier,
max_interval: self.max_interval,
max_elapsed_time: self.max_elapsed_time,
clock,
start_time: Instant::now(),
}
}
}
impl From<RetryConfig> for ExponentialBackoff {
fn from(c: RetryConfig) -> Self {
c.into_exp_backoff(SystemClock::default())
}
}
/// A request extension that, when set, should make the [RetryClient] consider this call to be a
/// [CallType::TaskLongPoll]
#[derive(Copy, Clone, Debug)]
pub struct IsWorkerTaskLongPoll;
/// A request extension that, when set, and a call is being processed by a [RetryClient], allows the
/// caller to request certain matching errors to short-circuit-return immediately and not follow
/// normal retry logic.
#[derive(Copy, Clone, Debug)]
pub struct NoRetryOnMatching {
/// Return true if the passed-in gRPC error should be immediately returned to the caller
pub predicate: fn(&tonic::Status) -> bool,
}
impl Debug for ClientTlsConfig {
// Intentionally omit details here since they could leak a key if ever printed
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "ClientTlsConfig(..)")
}
}
/// Errors thrown while attempting to establish a connection to the server
#[derive(thiserror::Error, Debug)]
pub enum ClientInitError {
/// Invalid URI. Configuration error, fatal.
#[error("Invalid URI: {0:?}")]
InvalidUri(#[from] InvalidUri),
/// Invalid gRPC metadata headers. Configuration error.
#[error("Invalid headers: {0}")]
InvalidHeaders(#[from] InvalidHeaderError),
/// Server connection error. Crashing and restarting the worker is likely best.
#[error("Server connection error: {0:?}")]
TonicTransportError(#[from] tonic::transport::Error),
/// We couldn't successfully make the `get_system_info` call at connection time to establish
/// server capabilities / verify server is responding.
#[error("`get_system_info` call error after connection: {0:?}")]
SystemInfoCallError(tonic::Status),
}
/// Errors thrown when a gRPC metadata header is invalid.
#[derive(thiserror::Error, Debug)]
pub enum InvalidHeaderError {
/// A binary header key was invalid
#[error("Invalid binary header key '{key}': {source}")]
InvalidBinaryHeaderKey {
/// The invalid key
key: String,
/// The source error from tonic
source: tonic::metadata::errors::InvalidMetadataKey,
},
/// An ASCII header key was invalid
#[error("Invalid ASCII header key '{key}': {source}")]
InvalidAsciiHeaderKey {
/// The invalid key
key: String,
/// The source error from tonic
source: tonic::metadata::errors::InvalidMetadataKey,
},
/// An ASCII header value was invalid
#[error("Invalid ASCII header value for key '{key}': {source}")]
InvalidAsciiHeaderValue {
/// The key
key: String,
/// The invalid value
value: String,
/// The source error from tonic
source: tonic::metadata::errors::InvalidMetadataValue,
},
}
/// A client with [ClientOptions] attached, which can be passed to initialize workers,
/// or can be used directly. Is cheap to clone.
#[derive(Clone, Debug)]
pub struct ConfiguredClient<C> {
client: C,
options: Arc<ClientOptions>,
headers: Arc<RwLock<ClientHeaders>>,
/// Capabilities as read from the `get_system_info` RPC call made on client connection
capabilities: Option<get_system_info_response::Capabilities>,
workers: Arc<SlotManager>,
}
impl<C> ConfiguredClient<C> {
/// Set HTTP request headers overwriting previous headers.
///
/// This will not affect headers set via [ClientOptions::binary_headers].
///
/// # Errors
///
/// Will return an error if any of the provided keys or values are not valid gRPC metadata.
/// If an error is returned, the previous headers will remain unchanged.
pub fn set_headers(&self, headers: HashMap<String, String>) -> Result<(), InvalidHeaderError> {
self.headers.write().user_headers = parse_ascii_headers(headers)?;
Ok(())
}
/// Set binary HTTP request headers overwriting previous headers.
///
/// This will not affect headers set via [ClientOptions::headers].
///
/// # Errors
///
/// Will return an error if any of the provided keys are not valid gRPC binary metadata keys.
/// If an error is returned, the previous headers will remain unchanged.
pub fn set_binary_headers(
&self,
binary_headers: HashMap<String, Vec<u8>>,
) -> Result<(), InvalidHeaderError> {
self.headers.write().user_binary_headers = parse_binary_headers(binary_headers)?;
Ok(())
}
/// Set API key, overwriting previous
pub fn set_api_key(&self, api_key: Option<String>) {
self.headers.write().api_key = api_key;
}
/// Returns the options the client is configured with
pub fn options(&self) -> &ClientOptions {
&self.options
}
/// Returns the server capabilities we (may have) learned about when establishing an initial
/// connection
pub fn capabilities(&self) -> Option<&get_system_info_response::Capabilities> {
self.capabilities.as_ref()
}
/// Returns a cloned reference to a registry with workers using this client instance
pub fn workers(&self) -> Arc<SlotManager> {
self.workers.clone()
}
}
#[derive(Debug)]
struct ClientHeaders {
user_headers: HashMap<AsciiMetadataKey, AsciiMetadataValue>,
user_binary_headers: HashMap<BinaryMetadataKey, BinaryMetadataValue>,
api_key: Option<String>,
}
impl ClientHeaders {
fn apply_to_metadata(&self, metadata: &mut MetadataMap) {
for (key, val) in self.user_headers.iter() {
// Only if not already present
if !metadata.contains_key(key) {
metadata.insert(key, val.clone());
}
}
for (key, val) in self.user_binary_headers.iter() {
// Only if not already present
if !metadata.contains_key(key) {
metadata.insert_bin(key, val.clone());
}
}
if let Some(api_key) = &self.api_key {
// Only if not already present
if !metadata.contains_key("authorization")
&& let Ok(val) = format!("Bearer {api_key}").parse()
{
metadata.insert("authorization", val);
}
}
}
}
// The configured client is effectively a "smart" (dumb) pointer
impl<C> Deref for ConfiguredClient<C> {
type Target = C;
fn deref(&self) -> &Self::Target {
&self.client
}
}
impl<C> DerefMut for ConfiguredClient<C> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.client
}
}
impl ClientOptions {
/// Attempt to establish a connection to the Temporal server in a specific namespace. The
/// returned client is bound to that namespace.
pub async fn connect(
&self,
namespace: impl Into<String>,
metrics_meter: Option<TemporalMeter>,
) -> Result<RetryClient<Client>, ClientInitError> {
let client = self.connect_no_namespace(metrics_meter).await?.into_inner();
let client = Client::new(client, namespace.into());
let retry_client = RetryClient::new(client, self.retry_config.clone());
Ok(retry_client)
}
/// Attempt to establish a connection to the Temporal server and return a gRPC client which is
/// intercepted with retry, default headers functionality, and metrics if provided.
///
/// See [RetryClient] for more
pub async fn connect_no_namespace(
&self,
metrics_meter: Option<TemporalMeter>,
) -> Result<RetryClient<ConfiguredClient<TemporalServiceClientWithMetrics>>, ClientInitError>
{
self.connect_no_namespace_with_service_override(metrics_meter, None)
.await
}
/// Attempt to establish a connection to the Temporal server and return a gRPC client which is
/// intercepted with retry, default headers functionality, and metrics if provided. If a
/// service_override is present, network-specific options are ignored and the callback is
/// invoked for each gRPC call.
///
/// See [RetryClient] for more
pub async fn connect_no_namespace_with_service_override(
&self,
metrics_meter: Option<TemporalMeter>,
service_override: Option<callback_based::CallbackBasedGrpcService>,
) -> Result<RetryClient<ConfiguredClient<TemporalServiceClientWithMetrics>>, ClientInitError>
{
let service = if let Some(service_override) = service_override {
GrpcMetricSvc {
inner: ChannelOrGrpcOverride::GrpcOverride(service_override),
metrics: metrics_meter.clone().map(MetricsContext::new),
disable_errcode_label: self.disable_error_code_metric_tags,
}
} else {
let channel = Channel::from_shared(self.target_url.to_string())?;
let channel = self.add_tls_to_channel(channel).await?;
let channel = if let Some(keep_alive) = self.keep_alive.as_ref() {
channel
.keep_alive_while_idle(true)
.http2_keep_alive_interval(keep_alive.interval)
.keep_alive_timeout(keep_alive.timeout)
} else {
channel
};
let channel = if let Some(origin) = self.override_origin.clone() {
channel.origin(origin)
} else {
channel
};
// If there is a proxy, we have to connect that way
let channel = if let Some(proxy) = self.http_connect_proxy.as_ref() {
proxy.connect_endpoint(&channel).await?
} else {
channel.connect().await?
};
ServiceBuilder::new()
.layer_fn(move |channel| GrpcMetricSvc {
inner: ChannelOrGrpcOverride::Channel(channel),
metrics: metrics_meter.clone().map(MetricsContext::new),
disable_errcode_label: self.disable_error_code_metric_tags,
})
.service(channel)
};
let headers = Arc::new(RwLock::new(ClientHeaders {
user_headers: parse_ascii_headers(self.headers.clone().unwrap_or_default())?,
user_binary_headers: parse_binary_headers(
self.binary_headers.clone().unwrap_or_default(),
)?,
api_key: self.api_key.clone(),
}));
let interceptor = ServiceCallInterceptor {
opts: self.clone(),
headers: headers.clone(),
};
let svc = InterceptedService::new(service, interceptor);
let mut client = ConfiguredClient {
headers,
client: TemporalServiceClient::new(svc),
options: Arc::new(self.clone()),
capabilities: None,
workers: Arc::new(SlotManager::new()),
};
if !self.skip_get_system_info {
match client
.get_system_info(GetSystemInfoRequest::default())
.await
{
Ok(sysinfo) => {
client.capabilities = sysinfo.into_inner().capabilities;
}
Err(status) => match status.code() {
Code::Unimplemented => {}
_ => return Err(ClientInitError::SystemInfoCallError(status)),
},
};
}
Ok(RetryClient::new(client, self.retry_config.clone()))
}
/// If TLS is configured, set the appropriate options on the provided channel and return it.
/// Passes it through if TLS options not set.
async fn add_tls_to_channel(&self, mut channel: Endpoint) -> Result<Endpoint, ClientInitError> {
if let Some(tls_cfg) = &self.tls_cfg {
let mut tls = tonic::transport::ClientTlsConfig::new();
if let Some(root_cert) = &tls_cfg.server_root_ca_cert {
let server_root_ca_cert = Certificate::from_pem(root_cert);
tls = tls.ca_certificate(server_root_ca_cert);
} else {
tls = tls.with_native_roots();
}
if let Some(domain) = &tls_cfg.domain {
tls = tls.domain_name(domain);
// This song and dance ultimately is just to make sure the `:authority` header ends
// up correct on requests while we use TLS. Setting the header directly in our
// interceptor doesn't work since seemingly it is overridden at some point by
// something lower level.
let uri: Uri = format!("https://{domain}").parse()?;
channel = channel.origin(uri);
}
if let Some(client_opts) = &tls_cfg.client_tls_config {
let client_identity =
Identity::from_pem(&client_opts.client_cert, &client_opts.client_private_key);
tls = tls.identity(client_identity);
}
return channel.tls_config(tls).map_err(Into::into);
}
Ok(channel)
}
}
fn parse_ascii_headers(
headers: HashMap<String, String>,
) -> Result<HashMap<AsciiMetadataKey, AsciiMetadataValue>, InvalidHeaderError> {
let mut parsed_headers = HashMap::with_capacity(headers.len());
for (k, v) in headers.into_iter() {
let key = match AsciiMetadataKey::from_str(&k) {
Ok(key) => key,
Err(err) => {
return Err(InvalidHeaderError::InvalidAsciiHeaderKey {
key: k,
source: err,
});
}
};
let value = match MetadataValue::from_str(&v) {
Ok(value) => value,
Err(err) => {
return Err(InvalidHeaderError::InvalidAsciiHeaderValue {
key: k,
value: v,
source: err,
});
}
};
parsed_headers.insert(key, value);
}
Ok(parsed_headers)
}
fn parse_binary_headers(
headers: HashMap<String, Vec<u8>>,
) -> Result<HashMap<BinaryMetadataKey, BinaryMetadataValue>, InvalidHeaderError> {
let mut parsed_headers = HashMap::with_capacity(headers.len());
for (k, v) in headers.into_iter() {
let key = match BinaryMetadataKey::from_str(&k) {
Ok(key) => key,
Err(err) => {
return Err(InvalidHeaderError::InvalidBinaryHeaderKey {
key: k,
source: err,
});
}
};
let value = BinaryMetadataValue::from_bytes(&v);
parsed_headers.insert(key, value);
}
Ok(parsed_headers)
}
/// Interceptor which attaches common metadata (like "client-name") to every outgoing call
#[derive(Clone)]
pub struct ServiceCallInterceptor {
opts: ClientOptions,
/// Only accessed as a reader
headers: Arc<RwLock<ClientHeaders>>,
}
impl Interceptor for ServiceCallInterceptor {
/// This function will get called on each outbound request. Returning a `Status` here will
/// cancel the request and have that status returned to the caller.
fn call(
&mut self,
mut request: tonic::Request<()>,
) -> Result<tonic::Request<()>, tonic::Status> {
let metadata = request.metadata_mut();
if !metadata.contains_key(CLIENT_NAME_HEADER_KEY) {
metadata.insert(
CLIENT_NAME_HEADER_KEY,
self.opts
.client_name
.parse()
.unwrap_or_else(|_| MetadataValue::from_static("")),
);
}
if !metadata.contains_key(CLIENT_VERSION_HEADER_KEY) {
metadata.insert(
CLIENT_VERSION_HEADER_KEY,
self.opts
.client_version
.parse()
.unwrap_or_else(|_| MetadataValue::from_static("")),
);
}
self.headers.read().apply_to_metadata(metadata);
request.set_default_timeout(OTHER_CALL_TIMEOUT);
Ok(request)
}
}
/// Aggregates various services exposed by the Temporal server
#[derive(Debug, Clone)]
pub struct TemporalServiceClient<T> {
svc: T,
workflow_svc_client: OnceLock<WorkflowServiceClient<T>>,
operator_svc_client: OnceLock<OperatorServiceClient<T>>,
cloud_svc_client: OnceLock<CloudServiceClient<T>>,
test_svc_client: OnceLock<TestServiceClient<T>>,
health_svc_client: OnceLock<HealthClient<T>>,
}
/// We up the limit on incoming messages from server from the 4Mb default to 128Mb. If for
/// whatever reason this needs to be changed by the user, we support overriding it via env var.
fn get_decode_max_size() -> usize {
static _DECODE_MAX_SIZE: OnceLock<usize> = OnceLock::new();
*_DECODE_MAX_SIZE.get_or_init(|| {
std::env::var("TEMPORAL_MAX_INCOMING_GRPC_BYTES")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(128 * 1024 * 1024)
})
}
impl<T> TemporalServiceClient<T>
where
T: Clone,
T: GrpcService<Body> + Send + Clone + 'static,
T::ResponseBody: tonic::codegen::Body<Data = tonic::codegen::Bytes> + Send + 'static,
T::Error: Into<tonic::codegen::StdError>,
<T::ResponseBody as tonic::codegen::Body>::Error: Into<tonic::codegen::StdError> + Send,
{
fn new(svc: T) -> Self {
Self {
svc,
workflow_svc_client: OnceLock::new(),
operator_svc_client: OnceLock::new(),
cloud_svc_client: OnceLock::new(),
test_svc_client: OnceLock::new(),
health_svc_client: OnceLock::new(),
}
}
/// Get the underlying workflow service client
pub fn workflow_svc(&self) -> &WorkflowServiceClient<T> {
self.workflow_svc_client.get_or_init(|| {
WorkflowServiceClient::new(self.svc.clone())
.max_decoding_message_size(get_decode_max_size())
})
}
/// Get the underlying operator service client
pub fn operator_svc(&self) -> &OperatorServiceClient<T> {
self.operator_svc_client.get_or_init(|| {
OperatorServiceClient::new(self.svc.clone())
.max_decoding_message_size(get_decode_max_size())
})
}
/// Get the underlying cloud service client
pub fn cloud_svc(&self) -> &CloudServiceClient<T> {
self.cloud_svc_client.get_or_init(|| {
CloudServiceClient::new(self.svc.clone())
.max_decoding_message_size(get_decode_max_size())
})
}
/// Get the underlying test service client
pub fn test_svc(&self) -> &TestServiceClient<T> {
self.test_svc_client.get_or_init(|| {
TestServiceClient::new(self.svc.clone())
.max_decoding_message_size(get_decode_max_size())
})
}
/// Get the underlying health service client
pub fn health_svc(&self) -> &HealthClient<T> {
self.health_svc_client.get_or_init(|| {
HealthClient::new(self.svc.clone()).max_decoding_message_size(get_decode_max_size())
})
}
/// Get the underlying workflow service client mutably
pub fn workflow_svc_mut(&mut self) -> &mut WorkflowServiceClient<T> {
let _ = self.workflow_svc();
self.workflow_svc_client.get_mut().unwrap()
}
/// Get the underlying operator service client mutably
pub fn operator_svc_mut(&mut self) -> &mut OperatorServiceClient<T> {
let _ = self.operator_svc();
self.operator_svc_client.get_mut().unwrap()
}
/// Get the underlying cloud service client mutably
pub fn cloud_svc_mut(&mut self) -> &mut CloudServiceClient<T> {
let _ = self.cloud_svc();
self.cloud_svc_client.get_mut().unwrap()
}
/// Get the underlying test service client mutably
pub fn test_svc_mut(&mut self) -> &mut TestServiceClient<T> {
let _ = self.test_svc();
self.test_svc_client.get_mut().unwrap()
}
/// Get the underlying health service client mutably
pub fn health_svc_mut(&mut self) -> &mut HealthClient<T> {
let _ = self.health_svc();
self.health_svc_client.get_mut().unwrap()
}
}
/// A [WorkflowServiceClient] with the default interceptors attached.
pub type WorkflowServiceClientWithMetrics = WorkflowServiceClient<InterceptedMetricsSvc>;
/// An [OperatorServiceClient] with the default interceptors attached.
pub type OperatorServiceClientWithMetrics = OperatorServiceClient<InterceptedMetricsSvc>;
/// An [TestServiceClient] with the default interceptors attached.
pub type TestServiceClientWithMetrics = TestServiceClient<InterceptedMetricsSvc>;
/// A [TemporalServiceClient] with the default interceptors attached.
pub type TemporalServiceClientWithMetrics = TemporalServiceClient<InterceptedMetricsSvc>;
type InterceptedMetricsSvc = InterceptedService<GrpcMetricSvc, ServiceCallInterceptor>;
/// Contains an instance of a namespace-bound client for interacting with the Temporal server
#[derive(Debug, Clone)]
pub struct Client {
/// Client for interacting with workflow service
inner: ConfiguredClient<TemporalServiceClientWithMetrics>,
/// The namespace this client interacts with
namespace: String,
}
impl Client {
/// Create a new client from an existing configured lower level client and a namespace
pub fn new(
client: ConfiguredClient<TemporalServiceClientWithMetrics>,
namespace: String,
) -> Self {
Client {
inner: client,
namespace,
}
}
/// Return an auto-retrying version of the underling grpc client (instrumented with metrics
/// collection, if enabled).
///
/// Note that it is reasonably cheap to clone the returned type if you need to own it. Such
/// clones will keep re-using the same channel.
pub fn raw_retry_client(&self) -> RetryClient<WorkflowServiceClientWithMetrics> {
RetryClient::new(
self.raw_client().clone(),
self.inner.options.retry_config.clone(),
)
}
/// Access the underling grpc client. This raw client is not bound to a specific namespace.
///
/// Note that it is reasonably cheap to clone the returned type if you need to own it. Such
/// clones will keep re-using the same channel.
pub fn raw_client(&self) -> &WorkflowServiceClientWithMetrics {
self.inner.workflow_svc()
}
/// Return the options this client was initialized with
pub fn options(&self) -> &ClientOptions {
&self.inner.options
}
/// Return the options this client was initialized with mutably
pub fn options_mut(&mut self) -> &mut ClientOptions {
Arc::make_mut(&mut self.inner.options)
}
/// Returns a reference to the underlying client
pub fn inner(&self) -> &ConfiguredClient<TemporalServiceClientWithMetrics> {
&self.inner
}
/// Consumes self and returns the underlying client
pub fn into_inner(self) -> ConfiguredClient<TemporalServiceClientWithMetrics> {
self.inner
}
}
impl NamespacedClient for Client {
fn namespace(&self) -> &str {
&self.namespace
}
fn get_identity(&self) -> &str {
&self.inner.options.identity
}
}
/// Enum to help reference a namespace by either the namespace name or the namespace id
#[derive(Clone)]
pub enum Namespace {
/// Namespace name
Name(String),
/// Namespace id
Id(String),
}
impl Namespace {
/// Convert into grpc request
pub fn into_describe_namespace_request(self) -> DescribeNamespaceRequest {
let (namespace, id) = match self {
Namespace::Name(n) => (n, "".to_owned()),
Namespace::Id(n) => ("".to_owned(), n),
};
DescribeNamespaceRequest { namespace, id }
}
}
/// Default workflow execution retention for a Namespace is 3 days
pub const DEFAULT_WORKFLOW_EXECUTION_RETENTION_PERIOD: Duration =
Duration::from_secs(60 * 60 * 24 * 3);
/// Helper struct for `register_namespace`.
#[derive(Clone, derive_builder::Builder)]
pub struct RegisterNamespaceOptions {
/// Name (required)
#[builder(setter(into))]
pub namespace: String,
/// Description (required)
#[builder(setter(into))]
pub description: String,
/// Owner's email
#[builder(setter(into), default)]
pub owner_email: String,
/// Workflow execution retention period
#[builder(default = "DEFAULT_WORKFLOW_EXECUTION_RETENTION_PERIOD")]
pub workflow_execution_retention_period: Duration,
/// Cluster settings
#[builder(setter(strip_option, custom), default)]
pub clusters: Vec<ClusterReplicationConfig>,
/// Active cluster name
#[builder(setter(into), default)]
pub active_cluster_name: String,
/// Custom Data
#[builder(default)]
pub data: HashMap<String, String>,
/// Security Token
#[builder(setter(into), default)]
pub security_token: String,
/// Global namespace
#[builder(default)]
pub is_global_namespace: bool,
/// History Archival setting
#[builder(setter(into), default = "ArchivalState::Unspecified")]
pub history_archival_state: ArchivalState,
/// History Archival uri
#[builder(setter(into), default)]
pub history_archival_uri: String,
/// Visibility Archival setting
#[builder(setter(into), default = "ArchivalState::Unspecified")]
pub visibility_archival_state: ArchivalState,
/// Visibility Archival uri
#[builder(setter(into), default)]
pub visibility_archival_uri: String,
}
impl RegisterNamespaceOptions {
/// Builder convenience. Less `use` imports
pub fn builder() -> RegisterNamespaceOptionsBuilder {
Default::default()
}
}
impl From<RegisterNamespaceOptions> for RegisterNamespaceRequest {
fn from(val: RegisterNamespaceOptions) -> Self {
RegisterNamespaceRequest {
namespace: val.namespace,
description: val.description,
owner_email: val.owner_email,
workflow_execution_retention_period: val
.workflow_execution_retention_period