1use crate::{
2 CancelWorkflowInput, DescribeWorkflowInput, DescribeWorkflowOutput,
3 FetchWorkflowHistoryPageInput, FetchWorkflowHistoryPageOutput, HistoryEventFilterType,
4 NamespacedClient, Next, PollWorkflowUpdateInput, PollWorkflowUpdateOutput, QueryWorkflowInput,
5 QueryWorkflowOutput, RpcOptions, SignalWorkflowInput, StartWorkflowUpdateInput,
6 StartWorkflowUpdateOutput, TerminateWorkflowInput, WorkflowCancelOptions,
7 WorkflowDescribeOptions, WorkflowExecuteUpdateOptions, WorkflowExecutionStatus,
8 WorkflowFetchHistoryOptions, WorkflowGetResultOptions, WorkflowQueryOptions,
9 WorkflowSignalOptions, WorkflowStartUpdateOptions, WorkflowTerminateOptions,
10 errors::{
11 WorkflowGetResultError, WorkflowInteractionError, WorkflowQueryError, WorkflowUpdateError,
12 },
13 grpc::WorkflowService,
14 interceptors,
15};
16use futures_util::{TryStreamExt, future::BoxFuture, stream, stream::Stream};
17use std::{
18 collections::VecDeque,
19 fmt::Debug,
20 marker::PhantomData,
21 pin::Pin,
22 task::{Context, Poll},
23};
24pub use temporalio_common::UntypedWorkflow;
25use temporalio_common::{
26 HasWorkflowDefinition, QueryDefinition, SignalDefinition, UpdateDefinition, WorkflowDefinition,
27 data_converters::{
28 DataConverter, DecodablePayloads, GenericPayloadConverter, PayloadConversionError,
29 PayloadConverter, RawValue, SerializationContext, SerializationContextData,
30 WorkflowSerializationContext,
31 },
32 error::IncomingError,
33 payload_visitor::decode_payloads,
34 protos::{
35 coresdk::FromPayloadsExt,
36 proto_ts_to_system_time,
37 temporal::api::{
38 common::v1::{Header, Payload, Payloads, WorkflowExecution as ProtoWorkflowExecution},
39 enums::v1::{
40 HistoryEventFilterType as ProtoHistoryEventFilterType,
41 QueryRejectCondition as ProtoQueryRejectCondition,
42 UpdateWorkflowExecutionLifecycleStage,
43 },
44 history::{
45 self,
46 v1::{History, HistoryEvent, history_event::Attributes},
47 },
48 query::v1::WorkflowQuery,
49 sdk::v1::UserMetadata,
50 update::{self, v1::WaitPolicy},
51 workflow::v1 as workflow,
52 workflowservice::v1::{
53 DescribeWorkflowExecutionRequest, DescribeWorkflowExecutionResponse,
54 GetWorkflowExecutionHistoryRequest, PollWorkflowExecutionUpdateRequest,
55 QueryWorkflowRequest, RequestCancelWorkflowExecutionRequest,
56 SignalWorkflowExecutionRequest, TerminateWorkflowExecutionRequest,
57 UpdateWorkflowExecutionRequest,
58 },
59 },
60 },
61 search_attributes::SearchAttributes,
62};
63use tonic::IntoRequest;
64use uuid::Uuid;
65
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67struct DecodedUserMetadata {
68 summary: Option<String>,
69 details: Option<String>,
70}
71
72fn decode_user_metadata(
73 context: &SerializationContextData,
74 user_metadata: Option<UserMetadata>,
75) -> Result<DecodedUserMetadata, PayloadConversionError> {
76 let payload_converter = PayloadConverter::default();
77 let context = SerializationContext::new(context, &payload_converter);
78 let (summary, details) = user_metadata
79 .map(|metadata| (metadata.summary, metadata.details))
80 .unwrap_or_default();
81 Ok(DecodedUserMetadata {
82 summary: match summary {
83 Some(payload) => Some(payload_converter.from_payload(&context, payload)?),
84 None => None,
85 },
86 details: match details {
87 Some(payload) => Some(payload_converter.from_payload(&context, payload)?),
88 None => None,
89 },
90 })
91}
92
93#[derive(Clone, Debug)]
95#[non_exhaustive]
96pub struct WorkflowResultDetails {
97 payloads: DecodablePayloads,
98}
99
100impl WorkflowResultDetails {
101 async fn new(
102 payloads: Vec<Payload>,
103 data_converter: &DataConverter,
104 ) -> Result<Self, PayloadConversionError> {
105 let payloads = data_converter
106 .codec()
107 .decode(
108 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
109 payloads,
110 )
111 .await?;
112 Ok(Self {
113 payloads: DecodablePayloads::new(
114 payloads,
115 data_converter.payload_converter().clone(),
116 SerializationContextData::Workflow(WorkflowSerializationContext::new()),
117 ),
118 })
119 }
120
121 pub fn deserialize<T: temporalio_common::data_converters::TemporalDeserializable + 'static>(
123 &self,
124 ) -> Result<T, PayloadConversionError> {
125 self.payloads.deserialize()
126 }
127
128 pub fn raw(&self) -> &[Payload] {
130 self.payloads.raw()
131 }
132
133 pub fn into_raw(self) -> RawValue {
135 self.payloads.into_raw()
136 }
137}
138
139#[derive(Debug)]
141#[allow(clippy::large_enum_variant)]
142pub enum WorkflowExecutionResult<T> {
143 Succeeded(T),
145 Failed(IncomingError),
147 Cancelled {
149 details: WorkflowResultDetails,
151 },
152 Terminated {
154 details: WorkflowResultDetails,
156 },
157 TimedOut,
159 ContinuedAsNew,
161}
162
163#[derive(Debug, Clone)]
167pub struct WorkflowExecutionDescription {
168 pub raw_description: DescribeWorkflowExecutionResponse,
170 history_length: usize,
171 static_summary: Option<String>,
172 static_details: Option<String>,
173 data_converter: DataConverter,
174}
175
176impl WorkflowExecutionDescription {
177 async fn new(
178 mut raw_description: DescribeWorkflowExecutionResponse,
179 data_converter: &DataConverter,
180 ) -> Result<Self, PayloadConversionError> {
181 let raw_user_metadata = raw_description
182 .execution_config
183 .as_ref()
184 .and_then(|cfg| cfg.user_metadata.clone());
185 decode_payloads(
186 &mut raw_description,
187 data_converter.codec(),
188 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
189 )
190 .await?;
191 let decoded_metadata = decode_user_metadata(
192 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
193 raw_user_metadata,
194 )?;
195 let history_length_raw = raw_description
196 .workflow_execution_info
197 .as_ref()
198 .map(|info| info.history_length)
199 .unwrap_or(0);
200 let history_length = history_length_raw.try_into().map_err(|_| {
201 PayloadConversionError::EncodingError(
202 format!("workflow history_length must be non-negative, got {history_length_raw}")
203 .into(),
204 )
205 })?;
206 Ok(Self {
207 raw_description,
208 history_length,
209 static_summary: decoded_metadata.summary,
210 static_details: decoded_metadata.details,
211 data_converter: data_converter.clone(),
212 })
213 }
214
215 pub fn id(&self) -> &str {
217 self.execution().workflow_id.as_str()
218 }
219
220 pub fn run_id(&self) -> &str {
222 self.execution().run_id.as_str()
223 }
224
225 pub fn workflow_type(&self) -> &str {
227 self.workflow_type_info().name.as_str()
228 }
229
230 pub fn status(&self) -> WorkflowExecutionStatus {
232 WorkflowExecutionStatus::from_raw(self.workflow_info().status)
233 }
234
235 pub fn start_time(&self) -> Option<std::time::SystemTime> {
237 self.workflow_info()
238 .start_time
239 .as_ref()
240 .and_then(proto_ts_to_system_time)
241 }
242
243 pub fn execution_time(&self) -> Option<std::time::SystemTime> {
245 self.workflow_info()
246 .execution_time
247 .as_ref()
248 .and_then(proto_ts_to_system_time)
249 }
250
251 pub fn close_time(&self) -> Option<std::time::SystemTime> {
253 self.workflow_info()
254 .close_time
255 .as_ref()
256 .and_then(proto_ts_to_system_time)
257 }
258
259 pub fn task_queue(&self) -> &str {
261 self.workflow_info().task_queue.as_str()
262 }
263
264 pub fn history_length(&self) -> usize {
266 self.history_length
267 }
268
269 pub fn memo(&self) -> crate::Memo {
271 crate::Memo::from_raw(
272 self.workflow_info().memo.clone(),
273 self.data_converter.payload_converter().clone(),
274 SerializationContextData::Workflow(WorkflowSerializationContext::new()),
275 )
276 }
277
278 pub fn parent_id(&self) -> Option<&str> {
280 self.workflow_info()
281 .parent_execution
282 .as_ref()
283 .map(|e| e.workflow_id.as_str())
284 }
285
286 pub fn parent_run_id(&self) -> Option<&str> {
288 self.workflow_info()
289 .parent_execution
290 .as_ref()
291 .map(|e| e.run_id.as_str())
292 }
293
294 pub fn search_attributes(&self) -> SearchAttributes {
296 self.workflow_info()
297 .search_attributes
298 .as_ref()
299 .map(SearchAttributes::from_proto)
300 .unwrap_or_default()
301 }
302
303 pub fn static_summary(&self) -> Option<&str> {
305 self.static_summary.as_deref()
306 }
307
308 pub fn static_details(&self) -> Option<&str> {
310 self.static_details.as_deref()
311 }
312
313 pub fn raw(&self) -> &DescribeWorkflowExecutionResponse {
315 &self.raw_description
316 }
317
318 pub fn into_raw(self) -> DescribeWorkflowExecutionResponse {
320 self.raw_description
321 }
322
323 fn workflow_info(&self) -> &workflow::WorkflowExecutionInfo {
324 self.raw_description
325 .workflow_execution_info
326 .as_ref()
327 .expect("describe response missing workflow_execution_info")
328 }
329
330 fn execution(&self) -> &ProtoWorkflowExecution {
331 self.workflow_info()
332 .execution
333 .as_ref()
334 .expect("describe response missing workflow_execution_info.execution")
335 }
336
337 fn workflow_type_info(
338 &self,
339 ) -> &temporalio_common::protos::temporal::api::common::v1::WorkflowType {
340 self.workflow_info()
341 .r#type
342 .as_ref()
343 .expect("describe response missing workflow_execution_info.type")
344 }
345}
346
347#[derive(derive_more::Debug)]
352pub struct WorkflowHistory {
353 #[debug(skip)]
354 inner: Pin<Box<dyn Stream<Item = Result<HistoryEvent, WorkflowInteractionError>> + Send>>,
355 workflow_id: Option<String>,
356}
357
358impl From<history::v1::History> for WorkflowHistory {
359 fn from(history: history::v1::History) -> Self {
360 let workflow_id =
361 history
362 .events
363 .first()
364 .and_then(|event| match event.attributes.as_ref() {
365 Some(Attributes::WorkflowExecutionStartedEventAttributes(attributes))
366 if !attributes.workflow_id.is_empty() =>
367 {
368 Some(attributes.workflow_id.clone())
369 }
370 _ => None,
371 });
372 Self {
373 inner: Box::pin(stream::iter(history.events.into_iter().map(Ok))),
374 workflow_id,
375 }
376 }
377}
378
379impl Stream for WorkflowHistory {
380 type Item = Result<HistoryEvent, WorkflowInteractionError>;
381
382 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
383 self.inner.as_mut().poll_next(cx)
384 }
385}
386
387#[derive(Debug, thiserror::Error)]
389#[non_exhaustive]
390pub enum WorkflowHistoryError {
391 #[error("failed to fetch workflow history: {0}")]
393 Fetch(#[from] WorkflowInteractionError),
394 #[error("failed to convert workflow history JSON: {0}")]
396 Json(#[from] serde_json::Error),
397}
398
399impl WorkflowHistory {
400 pub fn from_json(bytes: &[u8]) -> Result<Self, WorkflowHistoryError> {
402 let history: History = serde_json::from_slice(bytes)?;
403 Ok(history.into())
404 }
405
406 pub async fn to_json(self) -> Result<Vec<u8>, WorkflowHistoryError> {
408 Ok(serde_json::to_vec(&History {
409 events: self.into_events().await?,
410 })?)
411 }
412
413 pub fn workflow_id(&self) -> Option<&str> {
415 self.workflow_id.as_deref()
416 }
417
418 pub async fn into_events(self) -> Result<Vec<HistoryEvent>, WorkflowInteractionError> {
420 self.inner.try_collect().await
421 }
422}
423
424#[derive(Clone)]
427pub struct WorkflowHandle<ClientT, W> {
428 client: ClientT,
429 info: WorkflowExecutionInfo,
430
431 _wf_type: PhantomData<W>,
432}
433
434impl<CT, W> WorkflowHandle<CT, W> {
435 pub fn run_id(&self) -> Option<&str> {
437 self.info.run_id.as_deref()
438 }
439}
440
441#[derive(Debug, Clone, bon::Builder)]
443#[builder(on(String, into), state_mod(vis = "pub"))]
444#[non_exhaustive]
445pub struct WorkflowExecutionInfo {
446 pub namespace: String,
448 pub workflow_id: String,
450 pub run_id: Option<String>,
452 pub first_execution_run_id: Option<String>,
456}
457
458impl WorkflowExecutionInfo {
459 pub fn bind_untyped<CT>(self, client: CT) -> UntypedWorkflowHandle<CT>
461 where
462 CT: WorkflowService + Clone,
463 {
464 UntypedWorkflowHandle::new(client, self)
465 }
466}
467
468pub type UntypedWorkflowHandle<CT> = WorkflowHandle<CT, UntypedWorkflow>;
471
472pub struct UntypedSignal<W> {
476 name: String,
477 _wf: PhantomData<W>,
478}
479
480impl<W> UntypedSignal<W> {
481 pub fn new(name: impl Into<String>) -> Self {
483 Self {
484 name: name.into(),
485 _wf: PhantomData,
486 }
487 }
488}
489
490impl<W: WorkflowDefinition> SignalDefinition for UntypedSignal<W> {
491 type Workflow = W;
492 type Input = RawValue;
493
494 fn name(&self) -> &str {
495 &self.name
496 }
497}
498
499pub struct UntypedQuery<W> {
503 name: String,
504 _wf: PhantomData<W>,
505}
506
507impl<W> UntypedQuery<W> {
508 pub fn new(name: impl Into<String>) -> Self {
510 Self {
511 name: name.into(),
512 _wf: PhantomData,
513 }
514 }
515}
516
517impl<W: WorkflowDefinition> QueryDefinition for UntypedQuery<W> {
518 type Workflow = W;
519 type Input = RawValue;
520 type Output = RawValue;
521
522 fn name(&self) -> &str {
523 &self.name
524 }
525}
526
527pub struct UntypedUpdate<W> {
531 name: String,
532 _wf: PhantomData<W>,
533}
534
535impl<W> UntypedUpdate<W> {
536 pub fn new(name: impl Into<String>) -> Self {
538 Self {
539 name: name.into(),
540 _wf: PhantomData,
541 }
542 }
543}
544
545impl<W: WorkflowDefinition> UpdateDefinition for UntypedUpdate<W> {
546 type Workflow = W;
547 type Input = RawValue;
548 type Output = RawValue;
549
550 fn name(&self) -> &str {
551 &self.name
552 }
553}
554
555#[allow(clippy::too_many_arguments)]
559pub(crate) fn build_update_workflow_request(
560 namespace: String,
561 identity: String,
562 workflow_id: String,
563 run_id: String,
564 update_id: String,
565 update_name: String,
566 header: Option<Header>,
567 payloads: Vec<Payload>,
568) -> UpdateWorkflowExecutionRequest {
569 UpdateWorkflowExecutionRequest {
570 namespace,
571 workflow_execution: Some(ProtoWorkflowExecution {
572 workflow_id,
573 run_id,
574 }),
575 wait_policy: Some(WaitPolicy {
576 lifecycle_stage: UpdateWorkflowExecutionLifecycleStage::Accepted.into(),
577 }),
578 request: Some(update::v1::Request {
579 meta: Some(update::v1::Meta {
580 update_id,
581 identity,
582 }),
583 input: Some(update::v1::Input {
584 header,
585 name: update_name,
586 args: Some(Payloads { payloads }),
587 }),
588 ..Default::default()
589 }),
590 ..Default::default()
591 }
592}
593
594impl<CT, W> WorkflowHandle<CT, W>
595where
596 CT: WorkflowService + Clone,
597 W: HasWorkflowDefinition,
598{
599 pub fn new(client: CT, info: WorkflowExecutionInfo) -> Self {
601 Self {
602 client,
603 info,
604 _wf_type: PhantomData::<W>,
605 }
606 }
607
608 pub fn info(&self) -> &WorkflowExecutionInfo {
610 &self.info
611 }
612
613 pub fn client(&self) -> &CT {
615 &self.client
616 }
617
618 pub async fn get_result(
620 &self,
621 opts: WorkflowGetResultOptions,
622 ) -> Result<W::Output, WorkflowGetResultError>
623 where
624 CT: WorkflowService + NamespacedClient + Clone + 'static,
625 {
626 let raw = self.get_result_raw(opts).await?;
627 match raw {
628 WorkflowExecutionResult::Succeeded(v) => Ok(v),
629 WorkflowExecutionResult::Failed(f) => Err(WorkflowGetResultError::Failed(Box::new(f))),
630 WorkflowExecutionResult::Cancelled { details } => {
631 Err(WorkflowGetResultError::Cancelled { details })
632 }
633 WorkflowExecutionResult::Terminated { details } => {
634 Err(WorkflowGetResultError::Terminated { details })
635 }
636 WorkflowExecutionResult::TimedOut => Err(WorkflowGetResultError::TimedOut),
637 WorkflowExecutionResult::ContinuedAsNew => Err(WorkflowGetResultError::ContinuedAsNew),
638 }
639 }
640
641 async fn get_result_raw(
645 &self,
646 opts: WorkflowGetResultOptions,
647 ) -> Result<WorkflowExecutionResult<W::Output>, WorkflowInteractionError>
648 where
649 CT: WorkflowService + NamespacedClient + Clone + 'static,
650 {
651 let mut run_id = self.info.run_id.clone().unwrap_or_default();
652 let fetch_opts = WorkflowFetchHistoryOptions::builder()
653 .skip_archival(true)
654 .wait_new_event(true)
655 .event_filter_type(HistoryEventFilterType::CloseEvent)
656 .rpc_options(opts.rpc_options.clone())
657 .build();
658
659 loop {
660 let history = self.fetch_history_for_run(&run_id, fetch_opts.clone());
661 let mut events = history.into_events().await?;
662
663 if events.is_empty() {
664 continue;
665 }
666
667 let event_attrs = events.pop().and_then(|ev| ev.attributes);
668
669 macro_rules! follow {
670 ($attrs:ident) => {
671 if opts.follow_runs && $attrs.new_execution_run_id != "" {
672 run_id = $attrs.new_execution_run_id;
673 continue;
674 }
675 };
676 }
677
678 let dc = self.client.data_converter();
679
680 break match event_attrs {
681 Some(Attributes::WorkflowExecutionCompletedEventAttributes(attrs)) => {
682 follow!(attrs);
683 let payload = attrs
684 .result
685 .and_then(|p| p.payloads.into_iter().next())
686 .unwrap_or_default();
687 let result: W::Output = dc
688 .from_payload(&SerializationContextData::Workflow(WorkflowSerializationContext::new()), payload)
689 .await?;
690 Ok(WorkflowExecutionResult::Succeeded(result))
691 }
692 Some(Attributes::WorkflowExecutionFailedEventAttributes(attrs)) => {
693 follow!(attrs);
694 let mut failure = attrs.failure.unwrap_or_default();
695 decode_payloads(
696 &mut failure,
697 dc.codec(),
698 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
699 )
700 .await?;
701 let error = dc.failure_converter().to_error(
702 failure,
703 dc.payload_converter(),
704 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
705 )?;
706 Ok(WorkflowExecutionResult::Failed(error))
707 }
708 Some(Attributes::WorkflowExecutionCanceledEventAttributes(attrs)) => {
709 Ok(WorkflowExecutionResult::Cancelled {
710 details: WorkflowResultDetails::new(Vec::from_payloads(attrs.details), dc)
711 .await?,
712 })
713 }
714 Some(Attributes::WorkflowExecutionTimedOutEventAttributes(attrs)) => {
715 follow!(attrs);
716 Ok(WorkflowExecutionResult::TimedOut)
717 }
718 Some(Attributes::WorkflowExecutionTerminatedEventAttributes(attrs)) => {
719 Ok(WorkflowExecutionResult::Terminated {
720 details: WorkflowResultDetails::new(Vec::from_payloads(attrs.details), dc)
721 .await?,
722 })
723 }
724 Some(Attributes::WorkflowExecutionContinuedAsNewEventAttributes(attrs)) => {
725 if opts.follow_runs {
726 if !attrs.new_execution_run_id.is_empty() {
727 run_id = attrs.new_execution_run_id;
728 continue;
729 } else {
730 return Err(WorkflowInteractionError::Other(
731 "New execution run id was empty in continue as new event!".into(),
732 ));
733 }
734 } else {
735 Ok(WorkflowExecutionResult::ContinuedAsNew)
736 }
737 }
738 o => Err(WorkflowInteractionError::Other(
739 format!(
740 "Server returned an event that didn't match the CloseEvent filter. \
741 This is either a server bug or a new event the SDK does not understand. \
742 Event details: {o:?}"
743 )
744 .into(),
745 )),
746 };
747 }
748 }
749
750 pub async fn signal<S>(
752 &self,
753 signal: S,
754 input: S::Input,
755 opts: WorkflowSignalOptions,
756 ) -> Result<(), WorkflowInteractionError>
757 where
758 CT: WorkflowService + NamespacedClient + Clone,
759 S: SignalDefinition<Workflow = W::Run>,
760 S::Input: Send,
761 {
762 interceptors::call_signal_workflow(
763 self.client.client_interceptors(),
764 SignalWorkflowInput::new(
765 self.info.workflow_id.clone(),
766 self.info.run_id.clone().unwrap_or_default(),
767 signal.name().to_string(),
768 input,
769 opts,
770 ),
771 Next::new({
772 let mut client = self.client.clone();
773 move |input: SignalWorkflowInput| -> BoxFuture<
774 '_,
775 Result<(), WorkflowInteractionError>,
776 > {
777 Box::pin(async move {
778 let (workflow_id, run_id, signal_name, args, options) =
779 input.into_parts();
780 let data_converter = client.data_converter().clone();
781 let unencoded_payloads = {
782 let payload_converter = data_converter.payload_converter();
783 let context_data = SerializationContextData::Workflow(
784 WorkflowSerializationContext::new(),
785 );
786 let context =
787 SerializationContext::new(&context_data, payload_converter);
788 args.serialize_payloads(&context)
789 };
790 drop(args);
791 let payloads = data_converter
792 .codec()
793 .encode(&SerializationContextData::Workflow(WorkflowSerializationContext::new()), unencoded_payloads?)
794 .await?;
795 let mut request = SignalWorkflowExecutionRequest {
796 namespace: client.namespace(),
797 workflow_execution: Some(ProtoWorkflowExecution {
798 workflow_id,
799 run_id,
800 }),
801 signal_name,
802 input: Some(Payloads { payloads }),
803 identity: client.identity(),
804 request_id: options
805 .request_id
806 .unwrap_or_else(|| Uuid::new_v4().to_string()),
807 header: options.header,
808 ..Default::default()
809 }
810 .into_request();
811 options.rpc_options.apply_to(&mut request);
812 WorkflowService::signal_workflow_execution(&mut client, request)
813 .await
814 .map_err(WorkflowInteractionError::from_status)?;
815 Ok(())
816 })
817 }
818 }),
819 )
820 .await
821 }
822
823 pub async fn query<Q>(
825 &self,
826 query: Q,
827 input: Q::Input,
828 opts: WorkflowQueryOptions,
829 ) -> Result<Q::Output, WorkflowQueryError>
830 where
831 CT: WorkflowService + NamespacedClient + Clone,
832 Q: QueryDefinition<Workflow = W::Run>,
833 Q::Input: Send,
834 {
835 let output = interceptors::call_query_workflow(
836 self.client.client_interceptors(),
837 QueryWorkflowInput::new(
838 self.info.workflow_id.clone(),
839 self.info.run_id.clone().unwrap_or_default(),
840 query.name().to_string(),
841 input,
842 opts,
843 ),
844 Next::new({
845 let mut client = self.client.clone();
846 move |input: QueryWorkflowInput| -> BoxFuture<
847 '_,
848 Result<QueryWorkflowOutput, WorkflowQueryError>,
849 > {
850 Box::pin(async move {
851 let (workflow_id, run_id, query_name, args, options) = input.into_parts();
852 let data_converter = client.data_converter().clone();
853 let unencoded_payloads = {
854 let payload_converter = data_converter.payload_converter();
855 let context_data = SerializationContextData::Workflow(
856 WorkflowSerializationContext::new(),
857 );
858 let context =
859 SerializationContext::new(&context_data, payload_converter);
860 args.serialize_payloads(&context)
861 };
862 drop(args);
863 let payloads = data_converter
864 .codec()
865 .encode(&SerializationContextData::Workflow(WorkflowSerializationContext::new()), unencoded_payloads?)
866 .await?;
867 let mut request = QueryWorkflowRequest {
868 namespace: client.namespace(),
869 execution: Some(ProtoWorkflowExecution {
870 workflow_id,
871 run_id,
872 }),
873 query: Some(WorkflowQuery {
874 query_type: query_name,
875 query_args: Some(Payloads { payloads }),
876 header: options.header,
877 }),
878 query_reject_condition: options
879 .reject_condition
880 .map(|condition| ProtoQueryRejectCondition::from(condition) as i32)
881 .unwrap_or(ProtoQueryRejectCondition::None as i32),
882 }
883 .into_request();
884 options.rpc_options.apply_to(&mut request);
885 let response = client
886 .query_workflow(request)
887 .await
888 .map_err(WorkflowQueryError::from_status)?
889 .into_inner();
890 Ok(QueryWorkflowOutput::new(response))
891 })
892 }
893 }),
894 )
895 .await?;
896 let response = output.response;
897
898 if let Some(rejected) = response.query_rejected {
899 return Err(WorkflowQueryError::Rejected {
900 status: (rejected.status != 0)
901 .then(|| WorkflowExecutionStatus::from_raw(rejected.status)),
902 });
903 }
904
905 let result_payloads = response
906 .query_result
907 .map(|p| p.payloads)
908 .unwrap_or_default();
909
910 self.client
911 .data_converter()
912 .from_payloads(
913 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
914 result_payloads,
915 )
916 .await
917 .map_err(WorkflowQueryError::from)
918 }
919
920 pub async fn execute_update<U>(
922 &self,
923 update: U,
924 input: U::Input,
925 options: WorkflowExecuteUpdateOptions,
926 ) -> Result<U::Output, WorkflowUpdateError>
927 where
928 CT: WorkflowService + NamespacedClient + Clone,
929 U: UpdateDefinition<Workflow = W::Run>,
930 U::Input: Send,
931 U::Output: 'static,
932 {
933 let rpc_options = options.rpc_options.clone();
934 let handle = self.start_update(update, input, options.into()).await?;
935 handle.get_result(rpc_options).await
936 }
937
938 pub async fn start_update<U>(
941 &self,
942 update: U,
943 input: U::Input,
944 options: WorkflowStartUpdateOptions,
945 ) -> Result<WorkflowUpdateHandle<CT, U::Output>, WorkflowUpdateError>
946 where
947 CT: WorkflowService + NamespacedClient + Clone,
948 U: UpdateDefinition<Workflow = W::Run>,
949 U::Input: Send,
950 {
951 let output = interceptors::call_start_workflow_update(
952 self.client.client_interceptors(),
953 StartWorkflowUpdateInput::new(
954 self.info().workflow_id.clone(),
955 self.info().run_id.clone().unwrap_or_default(),
956 update.name().to_string(),
957 input,
958 options,
959 ),
960 Next::new({
961 let mut client = self.client.clone();
962 move |input: StartWorkflowUpdateInput| -> BoxFuture<
963 '_,
964 Result<StartWorkflowUpdateOutput, WorkflowUpdateError>,
965 > {
966 Box::pin(async move {
967 let (workflow_id, run_id, update_name, args, options) =
968 input.into_parts();
969 let data_converter = client.data_converter().clone();
970 let unencoded_payloads = {
971 let payload_converter = data_converter.payload_converter();
972 let context_data = SerializationContextData::Workflow(
973 WorkflowSerializationContext::new(),
974 );
975 let context =
976 SerializationContext::new(&context_data, payload_converter);
977 args.serialize_payloads(&context)
978 };
979 drop(args);
980 let payloads = data_converter
981 .codec()
982 .encode(
983 &SerializationContextData::Workflow(
984 WorkflowSerializationContext::new(),
985 ),
986 unencoded_payloads?,
987 )
988 .await?;
989 let update_id = options
990 .update_id
991 .unwrap_or_else(|| Uuid::new_v4().to_string());
992 let mut request = build_update_workflow_request(
993 client.namespace(),
994 client.identity(),
995 workflow_id.clone(),
996 run_id,
997 update_id.clone(),
998 update_name,
999 options.header,
1000 payloads,
1001 )
1002 .into_request();
1003 options.rpc_options.apply_to(&mut request);
1004 let response =
1005 WorkflowService::update_workflow_execution(&mut client, request)
1006 .await
1007 .map_err(WorkflowUpdateError::from_status)?
1008 .into_inner();
1009 let run_id = response
1010 .update_ref
1011 .as_ref()
1012 .and_then(|reference| reference.workflow_execution.as_ref())
1013 .map(|execution| execution.run_id.clone())
1014 .filter(|run_id| !run_id.is_empty());
1015 Ok(StartWorkflowUpdateOutput::new(
1016 update_id,
1017 workflow_id,
1018 run_id,
1019 response.outcome,
1020 ))
1021 })
1022 }
1023 }),
1024 )
1025 .await?;
1026
1027 Ok(WorkflowUpdateHandle::new(
1028 self.client.clone(),
1029 output.update_id,
1030 output.workflow_id,
1031 output.run_id.or_else(|| self.info().run_id.clone()),
1032 output.known_outcome,
1033 ))
1034 }
1035
1036 pub fn get_update_handle<U>(
1042 &self,
1043 update: U,
1044 update_id: impl Into<String>,
1045 ) -> WorkflowUpdateHandle<CT, U::Output>
1046 where
1047 U: UpdateDefinition<Workflow = W::Run>,
1048 {
1049 let _ = update;
1050 WorkflowUpdateHandle::new(
1051 self.client.clone(),
1052 update_id.into(),
1053 self.info.workflow_id.clone(),
1054 self.info.run_id.clone(),
1055 None,
1056 )
1057 }
1058
1059 pub async fn cancel(&self, opts: WorkflowCancelOptions) -> Result<(), WorkflowInteractionError>
1061 where
1062 CT: NamespacedClient,
1063 {
1064 interceptors::call_cancel_workflow(
1065 self.client.client_interceptors(),
1066 CancelWorkflowInput {
1067 workflow_id: self.info.workflow_id.clone(),
1068 run_id: self.info.run_id.clone().unwrap_or_default(),
1069 first_execution_run_id: self
1070 .info
1071 .first_execution_run_id
1072 .clone()
1073 .unwrap_or_default(),
1074 options: opts,
1075 },
1076 Next::new({
1077 let mut client = self.client.clone();
1078 move |input: CancelWorkflowInput| -> BoxFuture<
1079 '_,
1080 Result<(), WorkflowInteractionError>,
1081 > {
1082 Box::pin(async move {
1083 let mut request = RequestCancelWorkflowExecutionRequest {
1084 namespace: client.namespace(),
1085 workflow_execution: Some(ProtoWorkflowExecution {
1086 workflow_id: input.workflow_id,
1087 run_id: input.run_id,
1088 }),
1089 identity: client.identity(),
1090 request_id: input
1091 .options
1092 .request_id
1093 .clone()
1094 .unwrap_or_else(|| Uuid::new_v4().to_string()),
1095 first_execution_run_id: input.first_execution_run_id,
1096 reason: input.options.reason.clone(),
1097 links: vec![],
1098 }
1099 .into_request();
1100 input.options.rpc_options.apply_to(&mut request);
1101 WorkflowService::request_cancel_workflow_execution(&mut client, request)
1102 .await
1103 .map_err(WorkflowInteractionError::from_status)?;
1104 Ok(())
1105 })
1106 }
1107 }),
1108 )
1109 .await
1110 }
1111
1112 pub async fn terminate(
1114 &self,
1115 opts: WorkflowTerminateOptions,
1116 ) -> Result<(), WorkflowInteractionError>
1117 where
1118 CT: NamespacedClient,
1119 {
1120 interceptors::call_terminate_workflow(
1121 self.client.client_interceptors(),
1122 TerminateWorkflowInput {
1123 workflow_id: self.info.workflow_id.clone(),
1124 run_id: self.info.run_id.clone().unwrap_or_default(),
1125 first_execution_run_id: self
1126 .info
1127 .first_execution_run_id
1128 .clone()
1129 .unwrap_or_default(),
1130 options: opts,
1131 },
1132 Next::new({
1133 let mut client = self.client.clone();
1134 move |input: TerminateWorkflowInput| -> BoxFuture<
1135 '_,
1136 Result<(), WorkflowInteractionError>,
1137 > {
1138 Box::pin(async move {
1139 let mut request = TerminateWorkflowExecutionRequest {
1140 namespace: client.namespace(),
1141 workflow_execution: Some(ProtoWorkflowExecution {
1142 workflow_id: input.workflow_id,
1143 run_id: input.run_id,
1144 }),
1145 reason: input.options.reason.clone(),
1146 details: input.options.details.clone(),
1147 identity: client.identity(),
1148 first_execution_run_id: input.first_execution_run_id,
1149 links: vec![],
1150 }
1151 .into_request();
1152 input.options.rpc_options.apply_to(&mut request);
1153 WorkflowService::terminate_workflow_execution(&mut client, request)
1154 .await
1155 .map_err(WorkflowInteractionError::from_status)?;
1156 Ok(())
1157 })
1158 }
1159 }),
1160 )
1161 .await
1162 }
1163
1164 pub async fn describe(
1166 &self,
1167 opts: WorkflowDescribeOptions,
1168 ) -> Result<WorkflowExecutionDescription, WorkflowInteractionError>
1169 where
1170 CT: NamespacedClient,
1171 {
1172 let output = interceptors::call_describe_workflow(
1173 self.client.client_interceptors(),
1174 DescribeWorkflowInput {
1175 workflow_id: self.info.workflow_id.clone(),
1176 run_id: self.info.run_id.clone().unwrap_or_default(),
1177 options: opts,
1178 },
1179 Next::new({
1180 let mut client = self.client.clone();
1181 move |input: DescribeWorkflowInput| -> BoxFuture<
1182 '_,
1183 Result<DescribeWorkflowOutput, WorkflowInteractionError>,
1184 > {
1185 Box::pin(async move {
1186 let mut request = DescribeWorkflowExecutionRequest {
1187 namespace: client.namespace(),
1188 execution: Some(ProtoWorkflowExecution {
1189 workflow_id: input.workflow_id,
1190 run_id: input.run_id,
1191 }),
1192 }
1193 .into_request();
1194 input.options.rpc_options.apply_to(&mut request);
1195 let response =
1196 WorkflowService::describe_workflow_execution(&mut client, request)
1197 .await
1198 .map_err(WorkflowInteractionError::from_status)?
1199 .into_inner();
1200 Ok(DescribeWorkflowOutput::new(response))
1201 })
1202 }
1203 }),
1204 )
1205 .await?;
1206 WorkflowExecutionDescription::new(output.response, self.client.data_converter())
1207 .await
1208 .map_err(WorkflowInteractionError::from)
1209 }
1210 pub fn fetch_history(&self, opts: WorkflowFetchHistoryOptions) -> WorkflowHistory
1214 where
1215 CT: NamespacedClient + 'static,
1216 {
1217 let run_id = self.info.run_id.clone().unwrap_or_default();
1218 self.fetch_history_for_run(&run_id, opts)
1219 }
1220
1221 fn fetch_history_for_run(
1222 &self,
1223 run_id: &str,
1224 opts: WorkflowFetchHistoryOptions,
1225 ) -> WorkflowHistory
1226 where
1227 CT: NamespacedClient + 'static,
1228 {
1229 let client = self.client.clone();
1230 let workflow_id = self.info.workflow_id.clone();
1231 let history_workflow_id = workflow_id.clone();
1232 let run_id = run_id.to_string();
1233
1234 let stream = stream::unfold(
1235 (Vec::new(), VecDeque::new(), false),
1236 move |(mut next_page_token, mut buffer, mut exhausted)| {
1237 let client = client.clone();
1238 let workflow_id = workflow_id.clone();
1239 let run_id = run_id.clone();
1240 let opts = opts.clone();
1241
1242 async move {
1243 loop {
1244 if let Some(event) = buffer.pop_front() {
1245 return Some((Ok(event), (next_page_token, buffer, exhausted)));
1246 }
1247
1248 if exhausted {
1249 return None;
1250 }
1251
1252 let output = interceptors::call_fetch_workflow_history_page(
1253 client.client_interceptors(),
1254 FetchWorkflowHistoryPageInput {
1255 workflow_id: workflow_id.clone(),
1256 run_id: run_id.clone(),
1257 next_page_token: next_page_token.clone(),
1258 options: opts.clone(),
1259 },
1260 Next::new({
1261 let mut rpc_client = client.clone();
1262 move |input: FetchWorkflowHistoryPageInput| -> BoxFuture<
1263 '_,
1264 Result<
1265 FetchWorkflowHistoryPageOutput,
1266 WorkflowInteractionError,
1267 >,
1268 > {
1269 Box::pin(async move {
1270 let mut request = GetWorkflowExecutionHistoryRequest {
1271 namespace: rpc_client.namespace(),
1272 execution: Some(ProtoWorkflowExecution {
1273 workflow_id: input.workflow_id,
1274 run_id: input.run_id,
1275 }),
1276 next_page_token: input.next_page_token,
1277 skip_archival: input.options.skip_archival,
1278 wait_new_event: input.options.wait_new_event,
1279 history_event_filter_type:
1280 ProtoHistoryEventFilterType::from(
1281 input.options.event_filter_type,
1282 )
1283 as i32,
1284 ..Default::default()
1285 }
1286 .into_request();
1287 input.options.rpc_options.apply_to(&mut request);
1288 let response =
1289 WorkflowService::get_workflow_execution_history(
1290 &mut rpc_client,
1291 request,
1292 )
1293 .await
1294 .map_err(WorkflowInteractionError::from_status)?
1295 .into_inner();
1296 Ok(FetchWorkflowHistoryPageOutput::new(
1297 response
1298 .history
1299 .map(|history| history.events)
1300 .unwrap_or_default(),
1301 response.next_page_token,
1302 ))
1303 })
1304 }
1305 }),
1306 )
1307 .await;
1308
1309 match output {
1310 Ok(output) => {
1311 exhausted = output.next_page_token.is_empty();
1312 next_page_token = output.next_page_token;
1313 buffer = output.events.into();
1314 }
1315 Err(error) => {
1316 return Some((Err(error), (next_page_token, buffer, true)));
1317 }
1318 }
1319 }
1320 }
1321 },
1322 );
1323
1324 WorkflowHistory {
1325 inner: Box::pin(stream),
1326 workflow_id: Some(history_workflow_id),
1327 }
1328 }
1329}
1330
1331pub struct WorkflowUpdateHandle<CT, T> {
1335 client: CT,
1336 update_id: String,
1337 workflow_id: String,
1338 run_id: Option<String>,
1339 known_outcome: Option<update::v1::Outcome>,
1341 _output: PhantomData<T>,
1342}
1343
1344impl<CT, T> WorkflowUpdateHandle<CT, T> {
1345 pub(crate) fn new(
1346 client: CT,
1347 update_id: String,
1348 workflow_id: String,
1349 run_id: Option<String>,
1350 known_outcome: Option<update::v1::Outcome>,
1351 ) -> Self {
1352 Self {
1353 client,
1354 update_id,
1355 workflow_id,
1356 run_id,
1357 known_outcome,
1358 _output: PhantomData,
1359 }
1360 }
1361
1362 pub fn id(&self) -> &str {
1364 &self.update_id
1365 }
1366
1367 pub fn workflow_id(&self) -> &str {
1369 &self.workflow_id
1370 }
1371
1372 pub fn workflow_run_id(&self) -> Option<&str> {
1374 self.run_id.as_deref()
1375 }
1376}
1377
1378impl<CT, T: 'static> WorkflowUpdateHandle<CT, T>
1379where
1380 CT: WorkflowService + NamespacedClient + Clone,
1381{
1382 pub async fn get_result(&self, rpc_options: RpcOptions) -> Result<T, WorkflowUpdateError>
1384 where
1385 T: temporalio_common::data_converters::TemporalDeserializable,
1386 {
1387 let output = interceptors::call_poll_workflow_update(
1388 self.client.client_interceptors(),
1389 PollWorkflowUpdateInput {
1390 update_id: self.update_id.clone(),
1391 workflow_id: self.workflow_id.clone(),
1392 run_id: self.run_id.clone().unwrap_or_default(),
1393 rpc_options,
1394 },
1395 Next::new({
1396 let mut client = self.client.clone();
1397 let known_outcome = self.known_outcome.clone();
1398 move |input: PollWorkflowUpdateInput| -> BoxFuture<
1399 '_,
1400 Result<PollWorkflowUpdateOutput, WorkflowUpdateError>,
1401 > {
1402 Box::pin(async move {
1403 if let Some(outcome) = known_outcome {
1404 return Ok(PollWorkflowUpdateOutput::new(outcome));
1405 }
1406 loop {
1410 let mut request = PollWorkflowExecutionUpdateRequest {
1411 namespace: client.namespace(),
1412 update_ref: Some(update::v1::UpdateRef {
1413 workflow_execution: Some(ProtoWorkflowExecution {
1414 workflow_id: input.workflow_id.clone(),
1415 run_id: input.run_id.clone(),
1416 }),
1417 update_id: input.update_id.clone(),
1418 }),
1419 identity: client.identity(),
1420 wait_policy: Some(WaitPolicy {
1421 lifecycle_stage:
1422 UpdateWorkflowExecutionLifecycleStage::Completed.into(),
1423 }),
1424 }
1425 .into_request();
1426 input.rpc_options.apply_to(&mut request);
1427 let response = WorkflowService::poll_workflow_execution_update(
1428 &mut client,
1429 request,
1430 )
1431 .await
1432 .map_err(WorkflowUpdateError::from_status)?
1433 .into_inner();
1434 if let Some(outcome) = response.outcome {
1435 return Ok(PollWorkflowUpdateOutput::new(outcome));
1436 }
1437 }
1438 })
1439 }
1440 }),
1441 )
1442 .await?;
1443 let outcome = output.outcome;
1444
1445 match outcome.value {
1446 Some(update::v1::outcome::Value::Success(success)) => self
1447 .client
1448 .data_converter()
1449 .from_payloads(
1450 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1451 success.payloads,
1452 )
1453 .await
1454 .map_err(WorkflowUpdateError::from),
1455 Some(update::v1::outcome::Value::Failure(failure)) => {
1456 Err(WorkflowUpdateError::Failed(Box::new(failure)))
1457 }
1458 None => Err(WorkflowUpdateError::Other(
1459 "Update returned no outcome value".into(),
1460 )),
1461 }
1462 }
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467 use super::*;
1468 use crate::{ClientInterceptor, test_helpers::XorCodec};
1469 use futures_util::{FutureExt, StreamExt};
1470 use std::{
1471 collections::{HashMap, VecDeque},
1472 sync::{
1473 Arc, Mutex,
1474 atomic::{AtomicUsize, Ordering},
1475 },
1476 };
1477 use temporalio_common::{
1478 data_converters::DefaultFailureConverter,
1479 protos::temporal::api::{
1480 common::v1::{Memo, SearchAttributes},
1481 enums::v1::WorkflowExecutionStatus as ProtoWorkflowExecutionStatus,
1482 history::v1::WorkflowExecutionStartedEventAttributes,
1483 sdk::v1::UserMetadata,
1484 workflow::v1::WorkflowExecutionConfig,
1485 workflowservice::v1::GetWorkflowExecutionHistoryResponse,
1486 },
1487 };
1488 use tonic::{Request, Response};
1489
1490 #[tokio::test]
1491 async fn workflow_history_workflow_id_roundtrips() {
1492 let event = HistoryEvent {
1493 event_id: 1,
1494 attributes: Some(Attributes::WorkflowExecutionStartedEventAttributes(
1495 WorkflowExecutionStartedEventAttributes {
1496 workflow_id: "workflow-id".to_owned(),
1497 original_execution_run_id: "run-id".to_owned(),
1498 ..Default::default()
1499 },
1500 )),
1501 ..Default::default()
1502 };
1503 let history = WorkflowHistory {
1504 inner: Box::pin(stream::iter(std::iter::once(Ok(event)))),
1505 workflow_id: None,
1506 };
1507
1508 let bytes = history.to_json().await.unwrap();
1509
1510 let decoded = WorkflowHistory::from_json(&bytes).unwrap();
1511 assert_eq!(decoded.workflow_id(), Some("workflow-id"));
1512 }
1513
1514 #[derive(Clone)]
1515 struct MockHistoryClient {
1516 responses: Arc<Mutex<VecDeque<Result<GetWorkflowExecutionHistoryResponse, tonic::Status>>>>,
1517 calls: Arc<AtomicUsize>,
1518 interceptors: Vec<Arc<dyn ClientInterceptor>>,
1519 }
1520
1521 impl NamespacedClient for MockHistoryClient {
1522 fn namespace(&self) -> String {
1523 "test-namespace".to_owned()
1524 }
1525
1526 fn identity(&self) -> String {
1527 "test-identity".to_owned()
1528 }
1529
1530 fn client_interceptors(&self) -> &[Arc<dyn ClientInterceptor>] {
1531 &self.interceptors
1532 }
1533 }
1534
1535 impl WorkflowService for MockHistoryClient {
1536 fn get_workflow_execution_history(
1537 &mut self,
1538 _request: Request<GetWorkflowExecutionHistoryRequest>,
1539 ) -> BoxFuture<'_, Result<Response<GetWorkflowExecutionHistoryResponse>, tonic::Status>>
1540 {
1541 self.calls.fetch_add(1, Ordering::SeqCst);
1542 let response = self.responses.lock().unwrap().pop_front().unwrap();
1543 async move { response.map(Response::new) }.boxed()
1544 }
1545 }
1546
1547 struct CountingHistoryInterceptor(Arc<AtomicUsize>);
1548
1549 impl ClientInterceptor for CountingHistoryInterceptor {
1550 fn fetch_workflow_history_page<'a>(
1551 &'a self,
1552 input: FetchWorkflowHistoryPageInput,
1553 next: Next<
1554 'a,
1555 FetchWorkflowHistoryPageInput,
1556 BoxFuture<'a, Result<FetchWorkflowHistoryPageOutput, WorkflowInteractionError>>,
1557 >,
1558 ) -> BoxFuture<'a, Result<FetchWorkflowHistoryPageOutput, WorkflowInteractionError>>
1559 {
1560 self.0.fetch_add(1, Ordering::SeqCst);
1561 next.run(input)
1562 }
1563 }
1564
1565 fn history_response(
1566 event_ids: impl IntoIterator<Item = i64>,
1567 next_page_token: &[u8],
1568 ) -> GetWorkflowExecutionHistoryResponse {
1569 GetWorkflowExecutionHistoryResponse {
1570 history: Some(History {
1571 events: event_ids
1572 .into_iter()
1573 .map(|event_id| HistoryEvent {
1574 event_id,
1575 ..Default::default()
1576 })
1577 .collect(),
1578 }),
1579 next_page_token: next_page_token.to_vec(),
1580 ..Default::default()
1581 }
1582 }
1583
1584 fn history_handle(
1585 responses: impl IntoIterator<Item = Result<GetWorkflowExecutionHistoryResponse, tonic::Status>>,
1586 calls: Arc<AtomicUsize>,
1587 interceptors: Vec<Arc<dyn ClientInterceptor>>,
1588 ) -> WorkflowHandle<MockHistoryClient, UntypedWorkflow> {
1589 WorkflowHandle::new(
1590 MockHistoryClient {
1591 responses: Arc::new(Mutex::new(responses.into_iter().collect())),
1592 calls,
1593 interceptors,
1594 },
1595 WorkflowExecutionInfo {
1596 namespace: "test-namespace".to_owned(),
1597 workflow_id: "workflow-id".to_owned(),
1598 run_id: Some("run-id".to_owned()),
1599 first_execution_run_id: None,
1600 },
1601 )
1602 }
1603
1604 #[tokio::test]
1605 async fn workflow_history_fetches_pages_lazily() {
1606 let calls = Arc::new(AtomicUsize::new(0));
1607 let interceptor_calls = Arc::new(AtomicUsize::new(0));
1608 let handle = history_handle(
1609 [
1610 Ok(history_response([], b"second-page")),
1611 Ok(history_response([1, 2], b"third-page")),
1612 Ok(history_response([3], b"")),
1613 ],
1614 calls.clone(),
1615 vec![Arc::new(CountingHistoryInterceptor(
1616 interceptor_calls.clone(),
1617 ))],
1618 );
1619
1620 let mut history = handle.fetch_history(WorkflowFetchHistoryOptions::default());
1621 assert_eq!(calls.load(Ordering::SeqCst), 0);
1622
1623 assert_eq!(history.next().await.unwrap().unwrap().event_id, 1);
1624 assert_eq!(calls.load(Ordering::SeqCst), 2);
1625 assert_eq!(history.next().await.unwrap().unwrap().event_id, 2);
1626 assert_eq!(calls.load(Ordering::SeqCst), 2);
1627 assert_eq!(history.next().await.unwrap().unwrap().event_id, 3);
1628 assert_eq!(calls.load(Ordering::SeqCst), 3);
1629 assert!(history.next().await.is_none());
1630 assert_eq!(interceptor_calls.load(Ordering::SeqCst), 3);
1631 }
1632
1633 #[tokio::test]
1634 async fn workflow_history_yields_page_error_then_ends() {
1635 let calls = Arc::new(AtomicUsize::new(0));
1636 let handle = history_handle(
1637 [
1638 Ok(history_response([1], b"second-page")),
1639 Err(tonic::Status::unavailable("history unavailable")),
1640 ],
1641 calls.clone(),
1642 Vec::new(),
1643 );
1644 let mut history = handle.fetch_history(WorkflowFetchHistoryOptions::default());
1645
1646 assert_eq!(history.next().await.unwrap().unwrap().event_id, 1);
1647 assert!(matches!(
1648 history.next().await.unwrap(),
1649 Err(WorkflowInteractionError::Rpc(status)) if status.code() == tonic::Code::Unavailable
1650 ));
1651 assert!(history.next().await.is_none());
1652 assert_eq!(calls.load(Ordering::SeqCst), 2);
1653 }
1654
1655 #[tokio::test]
1656 async fn workflow_result_details_support_typed_decoding() {
1657 let converter = DataConverter::new(
1658 PayloadConverter::default(),
1659 DefaultFailureConverter::default(),
1660 XorCodec,
1661 );
1662 let payloads = converter
1663 .to_payloads(
1664 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1665 &"workflow-result-details".to_owned(),
1666 )
1667 .await
1668 .unwrap();
1669 let details = WorkflowResultDetails::new(payloads.clone(), &converter)
1670 .await
1671 .unwrap();
1672
1673 assert_ne!(details.raw(), payloads);
1674 let decoded_payloads = details.raw().to_vec();
1675 assert_eq!(
1676 details.deserialize::<String>().unwrap(),
1677 "workflow-result-details"
1678 );
1679 assert_eq!(details.into_raw().payloads, decoded_payloads);
1680 }
1681
1682 #[tokio::test]
1683 async fn workflow_result_detail_conversion_errors_are_reported() {
1684 let details =
1685 WorkflowResultDetails::new(vec![Payload::default()], &DataConverter::default())
1686 .await
1687 .unwrap();
1688
1689 assert_eq!(details.raw(), &[Payload::default()]);
1690 assert!(details.deserialize::<String>().is_err());
1691 }
1692
1693 #[tokio::test]
1694 async fn workflow_description_memo_uses_saved_converter() {
1695 let converter = DataConverter::new(
1696 PayloadConverter::default(),
1697 DefaultFailureConverter::default(),
1698 XorCodec,
1699 );
1700 let encoded = converter
1701 .to_payload(
1702 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1703 &"memo-value".to_owned(),
1704 )
1705 .await
1706 .unwrap();
1707 let description = WorkflowExecutionDescription::new(
1708 DescribeWorkflowExecutionResponse {
1709 workflow_execution_info: Some(workflow::WorkflowExecutionInfo {
1710 memo: Some(Memo {
1711 fields: HashMap::from([("memo-key".to_owned(), encoded)]),
1712 }),
1713 ..Default::default()
1714 }),
1715 ..Default::default()
1716 },
1717 &converter,
1718 )
1719 .await
1720 .unwrap();
1721 let memo = description.memo();
1722
1723 assert_eq!(
1724 memo.get::<String>("memo-key").unwrap(),
1725 Some("memo-value".to_owned())
1726 );
1727 }
1728
1729 #[tokio::test]
1730 async fn workflow_description_accessors_expose_decoded_fields() {
1731 let converter = DataConverter::default();
1732 let memo_payload = converter
1733 .to_payload(
1734 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1735 &"memo-value",
1736 )
1737 .await
1738 .unwrap();
1739 let search_attr_payload = converter
1740 .to_payload(
1741 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1742 &"search-value",
1743 )
1744 .await
1745 .unwrap();
1746 let summary_payload = converter
1747 .to_payload(
1748 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1749 &"workflow summary",
1750 )
1751 .await
1752 .unwrap();
1753 let details_payload = converter
1754 .to_payload(
1755 &SerializationContextData::Workflow(WorkflowSerializationContext::new()),
1756 &"workflow details",
1757 )
1758 .await
1759 .unwrap();
1760 let description = WorkflowExecutionDescription::new(
1761 DescribeWorkflowExecutionResponse {
1762 workflow_execution_info: Some(workflow::WorkflowExecutionInfo {
1763 execution: Some(ProtoWorkflowExecution {
1764 workflow_id: "wf-id".to_string(),
1765 run_id: "run-id".to_string(),
1766 }),
1767 r#type: Some(
1768 temporalio_common::protos::temporal::api::common::v1::WorkflowType {
1769 name: "wf-type".to_string(),
1770 },
1771 ),
1772 status: ProtoWorkflowExecutionStatus::Completed as i32,
1773 task_queue: "task-queue".to_string(),
1774 history_length: 42,
1775 memo: Some(Memo {
1776 fields: HashMap::from([("memo-key".to_string(), memo_payload.clone())]),
1777 }),
1778 parent_execution: Some(ProtoWorkflowExecution {
1779 workflow_id: "parent-id".to_string(),
1780 run_id: "parent-run-id".to_string(),
1781 }),
1782 search_attributes: Some(SearchAttributes {
1783 indexed_fields: HashMap::from([(
1784 "CustomKeywordField".to_string(),
1785 search_attr_payload.clone(),
1786 )]),
1787 }),
1788 ..Default::default()
1789 }),
1790 execution_config: Some(WorkflowExecutionConfig {
1791 user_metadata: Some(UserMetadata {
1792 summary: Some(summary_payload),
1793 details: Some(details_payload),
1794 }),
1795 ..Default::default()
1796 }),
1797 ..Default::default()
1798 },
1799 &converter,
1800 )
1801 .await
1802 .unwrap();
1803
1804 assert_eq!(description.id(), "wf-id");
1805 assert_eq!(description.run_id(), "run-id");
1806 assert_eq!(description.workflow_type(), "wf-type");
1807 assert_eq!(description.status(), WorkflowExecutionStatus::Completed);
1808 let mut unknown_status_description = description.clone();
1809 unknown_status_description
1810 .raw_description
1811 .workflow_execution_info
1812 .as_mut()
1813 .unwrap()
1814 .status = 123_456;
1815 assert_eq!(
1816 unknown_status_description.status(),
1817 WorkflowExecutionStatus::Unknown
1818 );
1819 assert_eq!(description.task_queue(), "task-queue");
1820 assert_eq!(description.history_length(), 42);
1821 assert_eq!(description.parent_id(), Some("parent-id"));
1822 assert_eq!(description.parent_run_id(), Some("parent-run-id"));
1823 let memo = description.memo();
1824 assert_eq!(memo.raw_value("memo-key"), Some(&memo_payload));
1825 assert_eq!(
1826 memo.get::<String>("memo-key").unwrap(),
1827 Some("memo-value".to_owned())
1828 );
1829 let search_attributes = description.search_attributes();
1830 assert_eq!(
1831 search_attributes.raw_payload("CustomKeywordField"),
1832 Some(&search_attr_payload)
1833 );
1834 assert_eq!(description.static_summary(), Some("workflow summary"));
1835 assert_eq!(description.static_details(), Some("workflow details"));
1836 }
1837
1838 #[tokio::test]
1839 async fn workflow_description_rejects_negative_history_length() {
1840 let err = WorkflowExecutionDescription::new(
1841 DescribeWorkflowExecutionResponse {
1842 workflow_execution_info: Some(workflow::WorkflowExecutionInfo {
1843 history_length: -1,
1844 ..Default::default()
1845 }),
1846 ..Default::default()
1847 },
1848 &DataConverter::default(),
1849 )
1850 .await
1851 .unwrap_err();
1852
1853 assert_eq!(
1854 err.to_string(),
1855 "Encoding error: workflow history_length must be non-negative, got -1"
1856 );
1857 }
1858}