-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathgrpc.rs
More file actions
2284 lines (2187 loc) · 78.8 KB
/
grpc.rs
File metadata and controls
2284 lines (2187 loc) · 78.8 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
//! gRPC service traits for direct access to Temporal services.
//!
//! Most users should use the higher-level methods on [`Client`] or [`Connection`] instead.
//! These traits are useful for advanced scenarios like custom interceptors, testing with mocks,
//! or making raw gRPC calls not covered by the higher-level API.
use crate::{
Client, Connection, LONG_POLL_TIMEOUT, RequestExt, SharedReplaceableClient,
TEMPORAL_NAMESPACE_HEADER_KEY, TemporalServiceClient,
metrics::namespace_kv,
retry::make_future_retry,
worker::{ClientWorkerSet, Slot},
};
use dyn_clone::DynClone;
use futures_util::{FutureExt, TryFutureExt, future::BoxFuture};
use std::{any::Any, marker::PhantomData, sync::Arc};
use temporalio_common::{
protos::{
grpc::health::v1::{health_client::HealthClient, *},
temporal::api::{
cloud::cloudservice::{v1 as cloudreq, v1::cloud_service_client::CloudServiceClient},
operatorservice::v1::{operator_service_client::OperatorServiceClient, *},
taskqueue::v1::TaskQueue,
testservice::v1::{test_service_client::TestServiceClient, *},
workflowservice::v1::{workflow_service_client::WorkflowServiceClient, *},
},
},
telemetry::metrics::MetricKeyValue,
};
use tonic::{
Request, Response, Status,
body::Body,
client::GrpcService,
metadata::{AsciiMetadataValue, KeyAndValueRef},
};
/// Something that has access to the raw grpc services
pub(crate) trait RawClientProducer {
/// Returns information about workers associated with this client. Implementers outside of
/// core can safely return `None`.
fn get_workers_info(&self) -> Option<Arc<ClientWorkerSet>>;
/// Return a workflow service client instance
fn workflow_client(&mut self) -> Box<dyn WorkflowService>;
/// Return a mutable ref to the operator service client instance
fn operator_client(&mut self) -> Box<dyn OperatorService>;
/// Return a mutable ref to the cloud service client instance
fn cloud_client(&mut self) -> Box<dyn CloudService>;
/// Return a mutable ref to the test service client instance
fn test_client(&mut self) -> Box<dyn TestService>;
/// Return a mutable ref to the health service client instance
fn health_client(&mut self) -> Box<dyn HealthService>;
}
/// Any client that can make gRPC calls. The default implementation simply invokes the passed-in
/// function. Implementers may override this to provide things like retry behavior.
#[async_trait::async_trait]
pub(crate) trait RawGrpcCaller: Send + Sync + 'static {
/// Make a gRPC call. The default implementation simply invokes the provided function.
async fn call<F, Req, Resp>(
&mut self,
_call_name: &'static str,
mut callfn: F,
req: Request<Req>,
) -> Result<Response<Resp>, Status>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
callfn(req).await
}
}
trait ErasedRawClient: Send + Sync + 'static {
fn erased_call(
&mut self,
call_name: &'static str,
op: &mut dyn ErasedCallOp,
) -> BoxFuture<'static, Result<Response<Box<dyn Any + Send>>, Status>>;
}
trait ErasedCallOp: Send {
fn invoke(
&mut self,
raw: &mut dyn ErasedRawClient,
call_name: &'static str,
) -> BoxFuture<'static, Result<Response<Box<dyn Any + Send>>, Status>>;
}
struct CallShim<F, Req, Resp> {
callfn: F,
seed_req: Option<Request<Req>>,
_resp: PhantomData<Resp>,
}
impl<F, Req, Resp> CallShim<F, Req, Resp> {
fn new(callfn: F, seed_req: Request<Req>) -> Self {
Self {
callfn,
seed_req: Some(seed_req),
_resp: PhantomData,
}
}
}
impl<F, Req, Resp> ErasedCallOp for CallShim<F, Req, Resp>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
fn invoke(
&mut self,
_raw: &mut dyn ErasedRawClient,
_call_name: &'static str,
) -> BoxFuture<'static, Result<Response<Box<dyn Any + Send>>, Status>> {
(self.callfn)(
self.seed_req
.take()
.expect("CallShim must have request populated"),
)
.map(|res| res.map(|payload| payload.map(|t| Box::new(t) as Box<dyn Any + Send>)))
.boxed()
}
}
#[async_trait::async_trait]
impl RawGrpcCaller for Connection {
async fn call<F, Req, Resp>(
&mut self,
call_name: &'static str,
mut callfn: F,
mut req: Request<Req>,
) -> Result<Response<Resp>, Status>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
let info = self
.inner
.retry_options
.get_call_info(call_name, Some(&req));
req.extensions_mut().insert(info.call_type);
if info.call_type.is_long() {
req.set_default_timeout(LONG_POLL_TIMEOUT);
}
let fact = || {
let req_clone = req_cloner(&req);
callfn(req_clone)
};
let res = make_future_retry(info, fact);
res.map_err(|(e, _attempt)| e).map_ok(|x| x.0).await
}
}
/// Helper for cloning a tonic request as long as the inner message may be cloned.
fn req_cloner<T: Clone>(cloneme: &Request<T>) -> Request<T> {
let msg = cloneme.get_ref().clone();
let mut new_req = Request::new(msg);
let new_met = new_req.metadata_mut();
for kv in cloneme.metadata().iter() {
match kv {
KeyAndValueRef::Ascii(k, v) => {
new_met.insert(k, v.clone());
}
KeyAndValueRef::Binary(k, v) => {
new_met.insert_bin(k, v.clone());
}
}
}
*new_req.extensions_mut() = cloneme.extensions().clone();
new_req
}
#[async_trait::async_trait]
impl RawGrpcCaller for dyn ErasedRawClient {
async fn call<F, Req, Resp>(
&mut self,
call_name: &'static str,
callfn: F,
req: Request<Req>,
) -> Result<Response<Resp>, Status>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
let mut shim = CallShim::new(callfn, req);
let erased_resp = ErasedRawClient::erased_call(self, call_name, &mut shim).await?;
Ok(erased_resp.map(|boxed| {
*boxed
.downcast()
.expect("RawGrpcCaller erased response type mismatch")
}))
}
}
impl<T> ErasedRawClient for T
where
T: RawGrpcCaller + 'static,
{
fn erased_call(
&mut self,
call_name: &'static str,
op: &mut dyn ErasedCallOp,
) -> BoxFuture<'static, Result<Response<Box<dyn Any + Send>>, Status>> {
let raw: &mut dyn ErasedRawClient = self;
op.invoke(raw, call_name)
}
}
impl RawClientProducer for Connection {
fn get_workers_info(&self) -> Option<Arc<ClientWorkerSet>> {
Some(self.workers())
}
fn workflow_client(&mut self) -> Box<dyn WorkflowService> {
self.inner.service.workflow_service()
}
fn operator_client(&mut self) -> Box<dyn OperatorService> {
self.inner.service.operator_service()
}
fn cloud_client(&mut self) -> Box<dyn CloudService> {
self.inner.service.cloud_service()
}
fn test_client(&mut self) -> Box<dyn TestService> {
self.inner.service.test_service()
}
fn health_client(&mut self) -> Box<dyn HealthService> {
self.inner.service.health_service()
}
}
impl RawClientProducer for TemporalServiceClient {
fn get_workers_info(&self) -> Option<Arc<ClientWorkerSet>> {
None
}
fn workflow_client(&mut self) -> Box<dyn WorkflowService> {
self.workflow_service()
}
fn operator_client(&mut self) -> Box<dyn OperatorService> {
self.operator_service()
}
fn cloud_client(&mut self) -> Box<dyn CloudService> {
self.cloud_service()
}
fn test_client(&mut self) -> Box<dyn TestService> {
self.test_service()
}
fn health_client(&mut self) -> Box<dyn HealthService> {
self.health_service()
}
}
impl RawGrpcCaller for TemporalServiceClient {}
impl RawClientProducer for Client {
fn get_workers_info(&self) -> Option<Arc<ClientWorkerSet>> {
Some(self.connection.workers())
}
fn workflow_client(&mut self) -> Box<dyn WorkflowService> {
self.connection.workflow_client()
}
fn operator_client(&mut self) -> Box<dyn OperatorService> {
self.connection.operator_client()
}
fn cloud_client(&mut self) -> Box<dyn CloudService> {
self.connection.cloud_client()
}
fn test_client(&mut self) -> Box<dyn TestService> {
self.connection.test_client()
}
fn health_client(&mut self) -> Box<dyn HealthService> {
self.connection.health_client()
}
}
#[async_trait::async_trait]
impl RawGrpcCaller for Client {
async fn call<F, Req, Resp>(
&mut self,
call_name: &'static str,
callfn: F,
req: Request<Req>,
) -> Result<Response<Resp>, Status>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
self.connection.call(call_name, callfn, req).await
}
}
impl<RC> RawClientProducer for SharedReplaceableClient<RC>
where
RC: RawClientProducer + Clone + Send + Sync + 'static,
{
fn get_workers_info(&self) -> Option<Arc<ClientWorkerSet>> {
self.inner_cow().get_workers_info()
}
fn workflow_client(&mut self) -> Box<dyn WorkflowService> {
self.inner_mut_refreshed().workflow_client()
}
fn operator_client(&mut self) -> Box<dyn OperatorService> {
self.inner_mut_refreshed().operator_client()
}
fn cloud_client(&mut self) -> Box<dyn CloudService> {
self.inner_mut_refreshed().cloud_client()
}
fn test_client(&mut self) -> Box<dyn TestService> {
self.inner_mut_refreshed().test_client()
}
fn health_client(&mut self) -> Box<dyn HealthService> {
self.inner_mut_refreshed().health_client()
}
}
#[async_trait::async_trait]
impl<RC> RawGrpcCaller for SharedReplaceableClient<RC>
where
RC: RawGrpcCaller + Clone + Sync + 'static,
{
async fn call<F, Req, Resp>(
&mut self,
call_name: &'static str,
callfn: F,
req: Request<Req>,
) -> Result<Response<Resp>, Status>
where
Req: Clone + Unpin + Send + Sync + 'static,
Resp: Send + 'static,
F: FnMut(Request<Req>) -> BoxFuture<'static, Result<Response<Resp>, Status>>,
F: Send + Sync + Unpin + 'static,
{
self.inner_mut_refreshed()
.call(call_name, callfn, req)
.await
}
}
#[derive(Clone, Debug)]
pub(super) struct AttachMetricLabels {
pub(super) labels: Vec<MetricKeyValue>,
pub(super) normal_task_queue: Option<String>,
pub(super) sticky_task_queue: Option<String>,
}
impl AttachMetricLabels {
pub(super) fn new(kvs: impl Into<Vec<MetricKeyValue>>) -> Self {
Self {
labels: kvs.into(),
normal_task_queue: None,
sticky_task_queue: None,
}
}
pub(super) fn namespace(ns: impl Into<String>) -> Self {
AttachMetricLabels::new(vec![namespace_kv(ns.into())])
}
pub(super) fn task_q(&mut self, tq: Option<TaskQueue>) -> &mut Self {
if let Some(tq) = tq {
if !tq.normal_name.is_empty() {
self.sticky_task_queue = Some(tq.name);
self.normal_task_queue = Some(tq.normal_name);
} else {
self.normal_task_queue = Some(tq.name);
}
}
self
}
pub(super) fn task_q_str(&mut self, tq: impl Into<String>) -> &mut Self {
self.normal_task_queue = Some(tq.into());
self
}
}
/// A request extension that, when set, should make the [RetryClient] consider this call to be a
/// [super::retry::CallType::UserLongPoll]
#[derive(Copy, Clone, Debug)]
pub(super) struct IsUserLongPoll;
macro_rules! proxy_def {
($client_type:tt, $client_meth:ident, $method:ident, $req:ty, $resp:ty, defaults) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
_request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>> {
async { Ok(tonic::Response::new(<$resp>::default())) }.boxed()
}
};
($client_type:tt, $client_meth:ident, $method:ident, $req:ty, $resp:ty) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
_request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>>;
};
}
/// Helps re-declare gRPC client methods
///
/// There are four forms:
///
/// * The first takes a closure that can modify the request. This is only called once, before the
/// actual rpc call is made, and before determinations are made about the kind of call (long poll
/// or not) and retry policy.
/// * The second takes three closures. The first can modify the request like in the first form.
/// The second can modify the request and return a value, and is called right before every call
/// (including on retries). The third is called with the response to the call after it resolves.
/// * The third and fourth are equivalents of the above that skip calling through the `call` method
/// and are implemented directly on the generated gRPC clients (IE: the bottom of the stack).
macro_rules! proxy_impl {
($client_type:tt, $client_meth:ident, $method:ident, $req:ty, $resp:ty $(, $closure:expr)?) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
#[allow(unused_mut)]
mut request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>> {
$( type_closure_arg(&mut request, $closure); )*
let mut self_clone = self.clone();
#[allow(unused_mut)]
let fact = move |mut req: tonic::Request<$req>| {
let mut c = self_clone.$client_meth();
async move { c.$method(req).await }.boxed()
};
self.call(stringify!($method), fact, request)
}
};
($client_type:tt, $client_meth:ident, $method:ident, $req:ty, $resp:ty,
$closure_request:expr, $closure_before:expr, $closure_after:expr) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
mut request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>> {
type_closure_arg(&mut request, $closure_request);
let workers_info = self.get_workers_info();
let mut self_clone = self.clone();
#[allow(unused_mut)]
let fact = move |mut req: tonic::Request<$req>| {
let data = type_closure_two_arg(&mut req, workers_info.clone(), $closure_before);
let mut c = self_clone.$client_meth();
async move {
type_closure_two_arg(c.$method(req).await, data, $closure_after)
}.boxed()
};
self.call(stringify!($method), fact, request)
}
};
($client_type:tt, $method:ident, $req:ty, $resp:ty $(, $closure:expr)?) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
#[allow(unused_mut)]
mut request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>> {
$( type_closure_arg(&mut request, $closure); )*
async move { <$client_type<_>>::$method(self, request).await }.boxed()
}
};
($client_type:tt, $method:ident, $req:ty, $resp:ty,
$closure_request:expr, $closure_before:expr, $closure_after:expr) => {
#[doc = concat!("See [", stringify!($client_type), "::", stringify!($method), "]")]
fn $method(
&mut self,
mut request: tonic::Request<$req>,
) -> BoxFuture<'_, Result<tonic::Response<$resp>, tonic::Status>> {
type_closure_arg(&mut request, $closure_request);
let data = type_closure_two_arg(&mut request, Option::<Arc<ClientWorkerSet>>::None,
$closure_before);
async move {
type_closure_two_arg(<$client_type<_>>::$method(self, request).await,
data, $closure_after)
}.boxed()
}
};
}
macro_rules! proxier_impl {
($trait_name:ident; $impl_list_name:ident; $client_type:tt; $client_meth:ident;
[$( proxy_def!($($def_args:tt)*); )*];
$(($method:ident, $req:ty, $resp:ty
$(, $closure:expr $(, $closure_before:expr, $closure_after:expr)?)? );)* ) => {
#[cfg(test)]
const $impl_list_name: &'static [&'static str] = &[$(stringify!($method)),*];
#[doc = concat!("Trait version of [", stringify!($client_type), "]")]
pub trait $trait_name: Send + Sync + DynClone
{
$( proxy_def!($($def_args)*); )*
}
dyn_clone::clone_trait_object!($trait_name);
// `allow(deprecated)`: upstream proto deprecations (e.g. cloud-api
// AddNamespaceRegion) generate calls to deprecated tonic client
// methods inside the impls; we still wire them for back-compat.
#[allow(deprecated)]
impl<RC> $trait_name for RC
where
RC: RawGrpcCaller + RawClientProducer + Clone + Unpin,
{
$(
proxy_impl!($client_type, $client_meth, $method, $req, $resp
$(,$closure $(,$closure_before, $closure_after)*)*);
)*
}
impl<T: Send + Sync + 'static> RawGrpcCaller for $client_type<T> {}
#[allow(deprecated)]
impl<T> $trait_name for $client_type<T>
where
T: GrpcService<Body> + Clone + Send + Sync + '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 tonic::client::GrpcService<Body>>::Future: Send
{
$(
proxy_impl!($client_type, $method, $req, $resp
$(,$closure $(,$closure_before, $closure_after)*)*);
)*
}
};
}
macro_rules! proxier {
( $trait_name:ident; $impl_list_name:ident; $client_type:tt; $client_meth:ident;
$(($method:ident, $req:ty, $resp:ty
$(, $closure:expr $(, $closure_before:expr, $closure_after:expr)?)? );)* ) => {
proxier_impl!($trait_name; $impl_list_name; $client_type; $client_meth;
[$(proxy_def!($client_type, $client_meth, $method, $req, $resp);)*];
$(($method, $req, $resp $(, $closure $(, $closure_before, $closure_after)?)?);)*);
};
( $trait_name:ident; $impl_list_name:ident; $client_type:tt; $client_meth:ident; defaults;
$(($method:ident, $req:ty, $resp:ty
$(, $closure:expr $(, $closure_before:expr, $closure_after:expr)?)? );)* ) => {
proxier_impl!($trait_name; $impl_list_name; $client_type; $client_meth;
[$(proxy_def!($client_type, $client_meth, $method, $req, $resp, defaults);)*];
$(($method, $req, $resp $(, $closure $(, $closure_before, $closure_after)?)?);)*);
};
}
macro_rules! namespaced_request {
($req:ident) => {{
let ns_str = $req.get_ref().namespace.clone();
// Attach namespace header
$req.metadata_mut().insert(
TEMPORAL_NAMESPACE_HEADER_KEY,
ns_str.parse().unwrap_or_else(|e| {
warn!("Unable to parse namespace for header: {e:?}");
AsciiMetadataValue::from_static("")
}),
);
// Init metric labels
AttachMetricLabels::namespace(ns_str)
}};
}
// Nice little trick to avoid the callsite asking to type the closure parameter
fn type_closure_arg<T, R>(arg: T, f: impl FnOnce(T) -> R) -> R {
f(arg)
}
fn type_closure_two_arg<T, R, S>(arg1: R, arg2: T, f: impl FnOnce(R, T) -> S) -> S {
f(arg1, arg2)
}
proxier! {
WorkflowService; ALL_IMPLEMENTED_WORKFLOW_SERVICE_RPCS; WorkflowServiceClient; workflow_client; defaults;
(
register_namespace,
RegisterNamespaceRequest,
RegisterNamespaceResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
describe_namespace,
DescribeNamespaceRequest,
DescribeNamespaceResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_namespaces,
ListNamespacesRequest,
ListNamespacesResponse
);
(
update_namespace,
UpdateNamespaceRequest,
UpdateNamespaceResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
deprecate_namespace,
DeprecateNamespaceRequest,
DeprecateNamespaceResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
start_workflow_execution,
StartWorkflowExecutionRequest,
StartWorkflowExecutionResponse,
|r| {
let mut labels = namespaced_request!(r);
labels.task_q(r.get_ref().task_queue.clone());
r.extensions_mut().insert(labels);
},
|r, workers| {
if let Some(workers) = workers {
let mut slot: Option<Box<dyn Slot + Send>> = None;
let req_mut = r.get_mut();
if req_mut.request_eager_execution {
let namespace = req_mut.namespace.clone();
let task_queue = req_mut.task_queue.as_ref()
.map(|tq| tq.name.clone()).unwrap_or_default();
match workers.try_reserve_wft_slot(namespace, task_queue) {
Some(reservation) => {
// Populate eager_worker_deployment_options from the slot reservation
if let Some(opts) = reservation.deployment_options {
req_mut.eager_worker_deployment_options = Some(temporalio_common::protos::temporal::api::deployment::v1::WorkerDeploymentOptions {
deployment_name: opts.version.deployment_name,
build_id: opts.version.build_id,
worker_versioning_mode: if opts.use_worker_versioning {
temporalio_common::protos::temporal::api::enums::v1::WorkerVersioningMode::Versioned.into()
} else {
temporalio_common::protos::temporal::api::enums::v1::WorkerVersioningMode::Unversioned.into()
},
}); }
slot = Some(reservation.slot);
}
None => req_mut.request_eager_execution = false
}
}
slot
} else {
None
}
},
|resp, slot| {
if let Some(s) = slot
&& let Ok(response) = resp.as_ref()
&& let Some(task) = response.get_ref().clone().eager_workflow_task
&& let Err(e) = s.schedule_wft(task) {
// This is a latency issue, i.e., the client does not need to handle
// this error, because the WFT will be retried after a timeout.
warn!(details = ?e, "Eager workflow task rejected by worker.");
}
resp
}
);
(
get_workflow_execution_history,
GetWorkflowExecutionHistoryRequest,
GetWorkflowExecutionHistoryResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
if r.get_ref().wait_new_event {
r.extensions_mut().insert(IsUserLongPoll);
}
}
);
(
get_workflow_execution_history_reverse,
GetWorkflowExecutionHistoryReverseRequest,
GetWorkflowExecutionHistoryReverseResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
poll_workflow_task_queue,
PollWorkflowTaskQueueRequest,
PollWorkflowTaskQueueResponse,
|r| {
let mut labels = namespaced_request!(r);
labels.task_q(r.get_ref().task_queue.clone());
r.extensions_mut().insert(labels);
}
);
(
respond_workflow_task_completed,
RespondWorkflowTaskCompletedRequest,
RespondWorkflowTaskCompletedResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_workflow_task_failed,
RespondWorkflowTaskFailedRequest,
RespondWorkflowTaskFailedResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
poll_activity_task_queue,
PollActivityTaskQueueRequest,
PollActivityTaskQueueResponse,
|r| {
let mut labels = namespaced_request!(r);
labels.task_q(r.get_ref().task_queue.clone());
r.extensions_mut().insert(labels);
}
);
(
record_activity_task_heartbeat,
RecordActivityTaskHeartbeatRequest,
RecordActivityTaskHeartbeatResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
record_activity_task_heartbeat_by_id,
RecordActivityTaskHeartbeatByIdRequest,
RecordActivityTaskHeartbeatByIdResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_completed,
RespondActivityTaskCompletedRequest,
RespondActivityTaskCompletedResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_completed_by_id,
RespondActivityTaskCompletedByIdRequest,
RespondActivityTaskCompletedByIdResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_failed,
RespondActivityTaskFailedRequest,
RespondActivityTaskFailedResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_failed_by_id,
RespondActivityTaskFailedByIdRequest,
RespondActivityTaskFailedByIdResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_canceled,
RespondActivityTaskCanceledRequest,
RespondActivityTaskCanceledResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
respond_activity_task_canceled_by_id,
RespondActivityTaskCanceledByIdRequest,
RespondActivityTaskCanceledByIdResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
request_cancel_workflow_execution,
RequestCancelWorkflowExecutionRequest,
RequestCancelWorkflowExecutionResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
signal_workflow_execution,
SignalWorkflowExecutionRequest,
SignalWorkflowExecutionResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
signal_with_start_workflow_execution,
SignalWithStartWorkflowExecutionRequest,
SignalWithStartWorkflowExecutionResponse,
|r| {
let mut labels = namespaced_request!(r);
labels.task_q(r.get_ref().task_queue.clone());
r.extensions_mut().insert(labels);
}
);
(
reset_workflow_execution,
ResetWorkflowExecutionRequest,
ResetWorkflowExecutionResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
terminate_workflow_execution,
TerminateWorkflowExecutionRequest,
TerminateWorkflowExecutionResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
delete_workflow_execution,
DeleteWorkflowExecutionRequest,
DeleteWorkflowExecutionResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_open_workflow_executions,
ListOpenWorkflowExecutionsRequest,
ListOpenWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_closed_workflow_executions,
ListClosedWorkflowExecutionsRequest,
ListClosedWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_workflow_executions,
ListWorkflowExecutionsRequest,
ListWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_archived_workflow_executions,
ListArchivedWorkflowExecutionsRequest,
ListArchivedWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
scan_workflow_executions,
ScanWorkflowExecutionsRequest,
ScanWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
count_workflow_executions,
CountWorkflowExecutionsRequest,
CountWorkflowExecutionsResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
create_workflow_rule,
CreateWorkflowRuleRequest,
CreateWorkflowRuleResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
describe_workflow_rule,
DescribeWorkflowRuleRequest,
DescribeWorkflowRuleResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
delete_workflow_rule,
DeleteWorkflowRuleRequest,
DeleteWorkflowRuleResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
list_workflow_rules,
ListWorkflowRulesRequest,
ListWorkflowRulesResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
trigger_workflow_rule,
TriggerWorkflowRuleRequest,
TriggerWorkflowRuleResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
get_search_attributes,
GetSearchAttributesRequest,
GetSearchAttributesResponse
);
(
respond_query_task_completed,
RespondQueryTaskCompletedRequest,
RespondQueryTaskCompletedResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);
}
);
(
reset_sticky_task_queue,
ResetStickyTaskQueueRequest,
ResetStickyTaskQueueResponse,
|r| {
let labels = namespaced_request!(r);
r.extensions_mut().insert(labels);