-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathlib.rs
More file actions
1587 lines (1429 loc) · 54.5 KB
/
lib.rs
File metadata and controls
1587 lines (1429 loc) · 54.5 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;
mod async_activity_handle;
pub mod callback_based;
/// Configuration loading from environment variables and TOML files.
#[cfg(feature = "envconfig")]
pub mod envconfig;
pub mod errors;
pub mod grpc;
mod metrics;
mod options_structs;
/// Visible only for tests
#[doc(hidden)]
pub mod proxy;
mod replaceable;
pub mod request_extensions;
mod retry;
/// Schedule operations: create, describe, update, pause, trigger, backfill, list, and delete.
pub mod schedules;
pub mod worker;
mod workflow_handle;
pub use crate::{
proxy::HttpConnectProxyOptions,
retry::{CallType, RETRYABLE_ERROR_CODES},
};
pub use async_activity_handle::{
ActivityHeartbeatResponse, ActivityIdentifier, AsyncActivityHandle,
};
pub use errors::*;
pub use metrics::{LONG_REQUEST_LATENCY_HISTOGRAM_NAME, REQUEST_LATENCY_HISTOGRAM_NAME};
pub use options_structs::*;
pub use replaceable::SharedReplaceableClient;
pub use retry::RetryOptions;
pub use tonic;
pub use workflow_handle::{
UntypedQuery, UntypedSignal, UntypedUpdate, UntypedWorkflow, UntypedWorkflowHandle,
WorkflowExecutionDescription, WorkflowExecutionInfo, WorkflowHandle, WorkflowHistory,
WorkflowUpdateHandle,
};
use crate::{
grpc::{
AttachMetricLabels, CloudService, HealthService, OperatorService, TestService,
WorkflowService,
},
metrics::{ChannelOrGrpcOverride, GrpcMetricSvc, MetricsContext},
request_extensions::RequestExt,
worker::ClientWorkerSet,
};
use futures_util::{stream, stream::Stream};
use http::Uri;
use parking_lot::RwLock;
use std::{
collections::{HashMap, VecDeque},
fmt::Debug,
pin::Pin,
str::FromStr,
sync::{Arc, OnceLock},
task::{Context, Poll},
time::{Duration, SystemTime},
};
use temporalio_common::{
HasWorkflowDefinition,
data_converters::{DataConverter, SerializationContextData},
protos::{
coresdk::IntoPayloadsExt,
grpc::health::v1::health_client::HealthClient,
proto_ts_to_system_time,
temporal::api::{
cloud::cloudservice::v1::cloud_service_client::CloudServiceClient,
common::v1::{Memo, Payload, SearchAttributes, WorkflowType},
enums::v1::{TaskQueueKind, WorkflowExecutionStatus},
errordetails::v1::WorkflowExecutionAlreadyStartedFailure,
operatorservice::v1::operator_service_client::OperatorServiceClient,
taskqueue::v1::TaskQueue,
testservice::v1::test_service_client::TestServiceClient,
workflow::v1 as workflow,
workflowservice::v1::{
count_workflow_executions_response, workflow_service_client::WorkflowServiceClient,
*,
},
},
utilities::decode_status_detail,
},
};
use tonic::{
Code, IntoRequest,
body::Body,
client::GrpcService,
codegen::InterceptedService,
metadata::{
AsciiMetadataKey, AsciiMetadataValue, BinaryMetadataKey, BinaryMetadataValue, MetadataMap,
MetadataValue,
},
service::Interceptor,
transport::{Certificate, Channel, Endpoint, Identity},
};
use tower::ServiceBuilder;
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";
#[doc(hidden)]
/// Key used to communicate when a GRPC message is too large
pub static MESSAGE_TOO_LARGE_KEY: &str = "message-too-large";
#[doc(hidden)]
/// 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);
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A connection to the Temporal service.
///
/// Cloning a connection is cheap (single Arc increment). The underlying connection is shared
/// between clones.
#[derive(Clone)]
pub struct Connection {
inner: Arc<ConnectionInner>,
}
#[derive(Clone)]
struct ConnectionInner {
service: TemporalServiceClient,
retry_options: RetryOptions,
identity: String,
headers: Arc<RwLock<ClientHeaders>>,
client_name: String,
client_version: String,
/// Capabilities as read from the `get_system_info` RPC call made on client connection
capabilities: Option<get_system_info_response::Capabilities>,
workers: Arc<ClientWorkerSet>,
}
impl Connection {
/// Connect to a Temporal service.
pub async fn connect(options: ConnectionOptions) -> Result<Self, ClientConnectError> {
let service = if let Some(service_override) = options.service_override {
GrpcMetricSvc {
inner: ChannelOrGrpcOverride::GrpcOverride(service_override),
metrics: options.metrics_meter.clone().map(MetricsContext::new),
disable_errcode_label: options.disable_error_code_metric_tags,
}
} else {
let channel = Channel::from_shared(options.target.to_string())?;
let channel = add_tls_to_channel(options.tls_options.as_ref(), channel).await?;
let channel = if let Some(keep_alive) = options.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) = options.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) = options.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: options.metrics_meter.clone().map(MetricsContext::new),
disable_errcode_label: options.disable_error_code_metric_tags,
})
.service(channel)
};
let headers = Arc::new(RwLock::new(ClientHeaders {
user_headers: parse_ascii_headers(options.headers.clone().unwrap_or_default())?,
user_binary_headers: parse_binary_headers(
options.binary_headers.clone().unwrap_or_default(),
)?,
api_key: options.api_key.clone(),
}));
let interceptor = ServiceCallInterceptor {
client_name: options.client_name.clone(),
client_version: options.client_version.clone(),
headers: headers.clone(),
};
let svc = InterceptedService::new(service, interceptor);
let mut svc_client = TemporalServiceClient::new(svc);
let capabilities = if !options.skip_get_system_info {
match svc_client
.get_system_info(GetSystemInfoRequest::default().into_request())
.await
{
Ok(sysinfo) => sysinfo.into_inner().capabilities,
Err(status) => match status.code() {
Code::Unimplemented => None,
_ => return Err(ClientConnectError::SystemInfoCallError(status)),
},
}
} else {
None
};
Ok(Self {
inner: Arc::new(ConnectionInner {
service: svc_client,
retry_options: options.retry_options,
identity: options.identity,
headers,
client_name: options.client_name,
client_version: options.client_version,
capabilities,
workers: Arc::new(ClientWorkerSet::new()),
}),
})
}
/// Set API key, overwriting any previous one.
pub fn set_api_key(&self, api_key: Option<String>) {
self.inner.headers.write().api_key = api_key;
}
/// Set HTTP request headers overwriting previous headers.
///
/// This will not affect headers set via [ConnectionOptions::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.inner.headers.write().user_headers = parse_ascii_headers(headers)?;
Ok(())
}
/// Set binary HTTP request headers overwriting previous headers.
///
/// This will not affect headers set via [ConnectionOptions::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.inner.headers.write().user_binary_headers = parse_binary_headers(binary_headers)?;
Ok(())
}
/// Returns the value used for the `client-name` header by this connection.
pub fn client_name(&self) -> &str {
&self.inner.client_name
}
/// Returns the value used for the `client-version` header by this connection.
pub fn client_version(&self) -> &str {
&self.inner.client_version
}
/// 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.inner.capabilities.as_ref()
}
/// Get a mutable reference to the retry options.
///
/// Note: If this connection has been cloned, this will copy-on-write to avoid
/// affecting other clones.
pub fn retry_options_mut(&mut self) -> &mut RetryOptions {
&mut Arc::make_mut(&mut self.inner).retry_options
}
/// Get a reference to the connection identity.
pub fn identity(&self) -> &str {
&self.inner.identity
}
/// Get a mutable reference to the connection identity.
///
/// Note: If this connection has been cloned, this will copy-on-write to avoid
/// affecting other clones.
pub fn identity_mut(&mut self) -> &mut String {
&mut Arc::make_mut(&mut self.inner).identity
}
/// Returns a reference to a registry with workers using this client instance.
pub fn workers(&self) -> Arc<ClientWorkerSet> {
self.inner.workers.clone()
}
/// Returns the client-wide key.
pub fn worker_grouping_key(&self) -> Uuid {
self.inner.workers.worker_grouping_key()
}
/// Get the underlying workflow service client for making raw gRPC calls.
pub fn workflow_service(&self) -> Box<dyn WorkflowService> {
self.inner.service.workflow_service()
}
/// Get the underlying operator service client for making raw gRPC calls.
pub fn operator_service(&self) -> Box<dyn OperatorService> {
self.inner.service.operator_service()
}
/// Get the underlying cloud service client for making raw gRPC calls.
pub fn cloud_service(&self) -> Box<dyn CloudService> {
self.inner.service.cloud_service()
}
/// Get the underlying test service client for making raw gRPC calls.
pub fn test_service(&self) -> Box<dyn TestService> {
self.inner.service.test_service()
}
/// Get the underlying health service client for making raw gRPC calls.
pub fn health_service(&self) -> Box<dyn HealthService> {
self.inner.service.health_service()
}
}
#[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);
}
}
}
}
/// 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(
tls_options: Option<&TlsOptions>,
mut channel: Endpoint,
) -> Result<Endpoint, ClientConnectError> {
if let Some(tls_cfg) = tls_options {
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_options {
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 {
client_name: String,
client_version: String,
/// 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.client_name
.parse()
.unwrap_or_else(|_| MetadataValue::from_static("")),
);
}
if !metadata.contains_key(CLIENT_VERSION_HEADER_KEY) {
metadata.insert(
CLIENT_VERSION_HEADER_KEY,
self.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(Clone)]
pub struct TemporalServiceClient {
workflow_svc_client: Box<dyn WorkflowService>,
operator_svc_client: Box<dyn OperatorService>,
cloud_svc_client: Box<dyn CloudService>,
test_svc_client: Box<dyn TestService>,
health_svc_client: Box<dyn HealthService>,
}
/// 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 TemporalServiceClient {
fn new<T>(svc: T) -> Self
where
T: GrpcService<Body> + Send + Sync + 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,
<T as GrpcService<Body>>::Future: Send,
{
let workflow_svc_client = Box::new(
WorkflowServiceClient::new(svc.clone())
.max_decoding_message_size(get_decode_max_size()),
);
let operator_svc_client = Box::new(
OperatorServiceClient::new(svc.clone())
.max_decoding_message_size(get_decode_max_size()),
);
let cloud_svc_client = Box::new(
CloudServiceClient::new(svc.clone()).max_decoding_message_size(get_decode_max_size()),
);
let test_svc_client = Box::new(
TestServiceClient::new(svc.clone()).max_decoding_message_size(get_decode_max_size()),
);
let health_svc_client = Box::new(
HealthClient::new(svc.clone()).max_decoding_message_size(get_decode_max_size()),
);
Self {
workflow_svc_client,
operator_svc_client,
cloud_svc_client,
test_svc_client,
health_svc_client,
}
}
/// Create a service client from implementations of the individual underlying services. Useful
/// for mocking out service implementations.
pub fn from_services(
workflow: Box<dyn WorkflowService>,
operator: Box<dyn OperatorService>,
cloud: Box<dyn CloudService>,
test: Box<dyn TestService>,
health: Box<dyn HealthService>,
) -> Self {
Self {
workflow_svc_client: workflow,
operator_svc_client: operator,
cloud_svc_client: cloud,
test_svc_client: test,
health_svc_client: health,
}
}
/// Get the underlying workflow service client
pub fn workflow_service(&self) -> Box<dyn WorkflowService> {
self.workflow_svc_client.clone()
}
/// Get the underlying operator service client
pub fn operator_service(&self) -> Box<dyn OperatorService> {
self.operator_svc_client.clone()
}
/// Get the underlying cloud service client
pub fn cloud_service(&self) -> Box<dyn CloudService> {
self.cloud_svc_client.clone()
}
/// Get the underlying test service client
pub fn test_service(&self) -> Box<dyn TestService> {
self.test_svc_client.clone()
}
/// Get the underlying health service client
pub fn health_service(&self) -> Box<dyn HealthService> {
self.health_svc_client.clone()
}
}
/// Contains an instance of a namespace-bound client for interacting with the Temporal server.
/// Cheap to clone.
#[derive(Clone)]
pub struct Client {
connection: Connection,
options: Arc<ClientOptions>,
}
impl Client {
/// Create a new client from a connection and options.
///
/// Currently infallible, but returns a `Result` for future extensibility
/// (e.g., interceptor or plugin validation).
pub fn new(connection: Connection, options: ClientOptions) -> Result<Self, ClientNewError> {
Ok(Client {
connection,
options: Arc::new(options),
})
}
/// Return the options this client was initialized with
pub fn options(&self) -> &ClientOptions {
&self.options
}
/// Return this client's options mutably.
///
/// Note: If this client has been cloned, this will copy-on-write to avoid affecting other
/// clones.
pub fn options_mut(&mut self) -> &mut ClientOptions {
Arc::make_mut(&mut self.options)
}
/// Returns a reference to the underlying connection
pub fn connection(&self) -> &Connection {
&self.connection
}
/// Returns a mutable reference to the underlying connection
pub fn connection_mut(&mut self) -> &mut Connection {
&mut self.connection
}
}
// High-level workflow operations on Client.
// These forward to the internal WorkflowClientTrait blanket impl which is
// available because Client implements WorkflowService + NamespacedClient + Clone.
impl Client {
/// Start a workflow execution.
///
/// Returns a [`WorkflowHandle`] that can be used to interact with the workflow
/// (e.g., get its result, send signals, query, etc.).
pub async fn start_workflow<W>(
&self,
workflow: W,
input: W::Input,
options: WorkflowStartOptions,
) -> Result<WorkflowHandle<Self, W>, WorkflowStartError>
where
W: HasWorkflowDefinition,
W::Input: Send,
{
WorkflowClientTrait::start_workflow(self, workflow, input, options).await
}
/// Get a handle to an existing workflow.
///
/// For untyped access, use `get_workflow_handle::<UntypedWorkflow>(...)`.
pub fn get_workflow_handle<W: HasWorkflowDefinition>(
&self,
workflow_id: impl Into<String>,
) -> WorkflowHandle<Self, W> {
WorkflowClientTrait::get_workflow_handle(self, workflow_id)
}
/// List workflows matching a query.
///
/// Returns a stream that lazily paginates through results.
/// Use `limit` in options to cap the number of results returned.
pub fn list_workflows(
&self,
query: impl Into<String>,
opts: WorkflowListOptions,
) -> ListWorkflowsStream {
WorkflowClientTrait::list_workflows(self, query, opts)
}
/// Count workflows matching a query.
pub async fn count_workflows(
&self,
query: impl Into<String>,
opts: WorkflowCountOptions,
) -> Result<WorkflowExecutionCount, ClientError> {
WorkflowClientTrait::count_workflows(self, query, opts).await
}
/// Get a handle to complete an activity asynchronously.
///
/// An activity returning `ActivityError::WillCompleteAsync` can be completed with this handle.
pub fn get_async_activity_handle(
&self,
identifier: ActivityIdentifier,
) -> AsyncActivityHandle<Self> {
WorkflowClientTrait::get_async_activity_handle(self, identifier)
}
}
impl NamespacedClient for Client {
fn namespace(&self) -> String {
self.options.namespace.clone()
}
fn identity(&self) -> String {
self.connection.identity().to_owned()
}
fn data_converter(&self) -> &DataConverter {
&self.options.data_converter
}
}
/// 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 }
}
}
/// This trait provides higher-level friendlier interaction with the server.
/// See the [WorkflowService] trait for a lower-level client.
pub(crate) trait WorkflowClientTrait: NamespacedClient {
/// Start a workflow execution.
fn start_workflow<W>(
&self,
workflow: W,
input: W::Input,
options: WorkflowStartOptions,
) -> impl Future<Output = Result<WorkflowHandle<Self, W>, WorkflowStartError>>
where
Self: Sized,
W: HasWorkflowDefinition,
W::Input: Send;
/// Get a handle to an existing workflow. `run_id` may be left blank to specify the most recent
/// execution having the provided `workflow_id`.
///
/// For untyped access, use `get_workflow_handle::<UntypedWorkflow>(...)`.
///
/// See also [WorkflowHandle::new], for specifying namespace or first_execution_run_id.
fn get_workflow_handle<W: HasWorkflowDefinition>(
&self,
workflow_id: impl Into<String>,
) -> WorkflowHandle<Self, W>
where
Self: Sized;
/// List workflows matching a query.
/// Returns a stream that lazily paginates through results.
/// Use `limit` in options to cap the number of results returned.
fn list_workflows(
&self,
query: impl Into<String>,
opts: WorkflowListOptions,
) -> ListWorkflowsStream;
/// Count workflows matching a query.
fn count_workflows(
&self,
query: impl Into<String>,
opts: WorkflowCountOptions,
) -> impl Future<Output = Result<WorkflowExecutionCount, ClientError>>;
/// Get a handle to complete an activity asynchronously.
///
/// An activity returning `ActivityError::WillCompleteAsync` can be completed with this handle.
fn get_async_activity_handle(
&self,
identifier: ActivityIdentifier,
) -> AsyncActivityHandle<Self>
where
Self: Sized;
}
/// A client that is bound to a namespace
pub trait NamespacedClient {
/// Returns the namespace this client is bound to
fn namespace(&self) -> String;
/// Returns the client identity
fn identity(&self) -> String;
/// Returns the data converter for serializing/deserializing payloads.
/// Default implementation returns a static default converter.
fn data_converter(&self) -> &DataConverter {
static DEFAULT: OnceLock<DataConverter> = OnceLock::new();
DEFAULT.get_or_init(DataConverter::default)
}
}
/// A workflow execution returned from list operations.
/// This represents information about a workflow present in visibility.
#[derive(Debug, Clone)]
pub struct WorkflowExecution {
raw: workflow::WorkflowExecutionInfo,
}
impl WorkflowExecution {
/// Create a new WorkflowExecution from the raw proto.
pub fn new(raw: workflow::WorkflowExecutionInfo) -> Self {
Self { raw }
}
/// The workflow ID.
pub fn id(&self) -> &str {
self.raw
.execution
.as_ref()
.map(|e| e.workflow_id.as_str())
.unwrap_or("")
}
/// The run ID.
pub fn run_id(&self) -> &str {
self.raw
.execution
.as_ref()
.map(|e| e.run_id.as_str())
.unwrap_or("")
}
/// The workflow type name.
pub fn workflow_type(&self) -> &str {
self.raw
.r#type
.as_ref()
.map(|t| t.name.as_str())
.unwrap_or("")
}
/// The current status of the workflow execution.
pub fn status(&self) -> WorkflowExecutionStatus {
self.raw.status()
}
/// When the workflow was created.
pub fn start_time(&self) -> Option<SystemTime> {
self.raw
.start_time
.as_ref()
.and_then(proto_ts_to_system_time)
}
/// When the workflow run started or should start.
pub fn execution_time(&self) -> Option<SystemTime> {
self.raw
.execution_time
.as_ref()
.and_then(proto_ts_to_system_time)
}
/// When the workflow was closed, if closed.
pub fn close_time(&self) -> Option<SystemTime> {
self.raw
.close_time
.as_ref()
.and_then(proto_ts_to_system_time)
}
/// The task queue the workflow runs on.
pub fn task_queue(&self) -> &str {
&self.raw.task_queue
}
/// Number of events in history.
pub fn history_length(&self) -> i64 {
self.raw.history_length
}
/// Workflow memo.
pub fn memo(&self) -> Option<&Memo> {
self.raw.memo.as_ref()
}
/// Parent workflow ID, if this is a child workflow.
pub fn parent_id(&self) -> Option<&str> {
self.raw
.parent_execution
.as_ref()
.map(|e| e.workflow_id.as_str())
}
/// Parent run ID, if this is a child workflow.
pub fn parent_run_id(&self) -> Option<&str> {
self.raw
.parent_execution
.as_ref()
.map(|e| e.run_id.as_str())
}
/// Search attributes on the workflow.
pub fn search_attributes(&self) -> Option<&SearchAttributes> {
self.raw.search_attributes.as_ref()
}
/// Access the raw proto for additional fields not exposed via accessors.
pub fn raw(&self) -> &workflow::WorkflowExecutionInfo {
&self.raw
}
/// Consume the wrapper and return the raw proto.
pub fn into_raw(self) -> workflow::WorkflowExecutionInfo {
self.raw
}
}
impl From<workflow::WorkflowExecutionInfo> for WorkflowExecution {
fn from(raw: workflow::WorkflowExecutionInfo) -> Self {
Self::new(raw)
}
}
/// A stream of workflow executions from a list query.
/// Internally paginates through results from the server.
pub struct ListWorkflowsStream {
inner: Pin<Box<dyn Stream<Item = Result<WorkflowExecution, ClientError>> + Send>>,
}
impl ListWorkflowsStream {
fn new(
inner: Pin<Box<dyn Stream<Item = Result<WorkflowExecution, ClientError>> + Send>>,
) -> Self {
Self { inner }
}
}
impl Stream for ListWorkflowsStream {
type Item = Result<WorkflowExecution, ClientError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.inner.as_mut().poll_next(cx)
}
}
/// Result of a workflow count operation.
///
/// If the query includes a group-by clause, `groups` will contain the aggregated
/// counts and `count` will be the sum of all group counts.
#[derive(Debug, Clone)]
pub struct WorkflowExecutionCount {
count: usize,
groups: Vec<WorkflowCountAggregationGroup>,
}
impl WorkflowExecutionCount {
pub(crate) fn from_response(resp: CountWorkflowExecutionsResponse) -> Self {
Self {
count: resp.count as usize,
groups: resp
.groups
.into_iter()
.map(WorkflowCountAggregationGroup::from_proto)
.collect(),
}
}
/// The approximate number of workflows matching the query.
/// If grouping was applied, this is the sum of all group counts.
pub fn count(&self) -> usize {
self.count
}
/// The groups if the query had a group-by clause, or empty if not.
pub fn groups(&self) -> &[WorkflowCountAggregationGroup] {
&self.groups
}
}
/// Aggregation group from a workflow count query with a group-by clause.
#[derive(Debug, Clone)]
pub struct WorkflowCountAggregationGroup {
group_values: Vec<Payload>,
count: usize,
}
impl WorkflowCountAggregationGroup {
fn from_proto(proto: count_workflow_executions_response::AggregationGroup) -> Self {
Self {
group_values: proto.group_values,
count: proto.count as usize,
}
}
/// The search attribute values for this group.