temporalio-common 0.4.0

Common functionality for the Temporal SDK Core, Client, and Rust SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
//! Shared error types used across Temporal SDK crates.

use crate::{
    data_converters::{
        DecodablePayloads, GenericPayloadConverter, PayloadConversionError, PayloadConverter,
        RawValue, SerializationContext, SerializationContextData, TemporalDeserializable,
        TemporalSerializable,
    },
    protos::{
        coresdk::child_workflow::StartChildWorkflowExecutionFailedCause,
        temporal::api::{
            common::v1::{Payload, Payloads},
            enums::v1::{ApplicationErrorCategory, TimeoutType},
            failure::v1::Failure,
        },
    },
};
use std::time::Duration;

// We cannot store `Box<dyn TemporalSerializable>` directly here because erased values still need
// to be driven back through the active `PayloadConverter` to reach serde-based implementations.
trait SerializableFailurePayload: Send + Sync {
    fn to_payloads(
        &self,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Result<Vec<Payload>, PayloadConversionError>;
}

impl<T> SerializableFailurePayload for T
where
    T: TemporalSerializable + Send + Sync + 'static,
{
    fn to_payloads(
        &self,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Result<Vec<Payload>, PayloadConversionError> {
        payload_converter.to_payloads(
            &SerializationContext {
                data: context,
                converter: payload_converter,
            },
            self,
        )
    }
}

/// Payloads attached to a failure, either as a deferred outbound value or decoded inbound payloads.
#[derive(derive_more::Debug)]
pub struct FailurePayloads {
    repr: FailurePayloadsRepr,
}

#[derive(derive_more::Debug)]
enum FailurePayloadsRepr {
    #[debug("Serializable(...)")]
    Serializable(#[debug(skip)] Box<dyn SerializableFailurePayload>),
    Decoded(DecodablePayloads),
}

impl FailurePayloads {
    pub(crate) fn encode(
        &self,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Result<Payloads, PayloadConversionError> {
        let payloads = match &self.repr {
            FailurePayloadsRepr::Serializable(value) => {
                value.to_payloads(payload_converter, context)?
            }
            FailurePayloadsRepr::Decoded(value) => value.raw().to_vec(),
        };
        Ok(Payloads { payloads })
    }

    /// Deserialize the decoded payloads into a typed value.
    pub fn deserialize<T: TemporalDeserializable + 'static>(
        &self,
    ) -> Result<T, PayloadConversionError> {
        match &self.repr {
            FailurePayloadsRepr::Decoded(value) => value.deserialize(),
            FailurePayloadsRepr::Serializable(_) => Err(PayloadConversionError::WrongEncoding),
        }
    }

    /// Returns the decoded raw payloads, if present.
    pub fn raw(&self) -> Option<&[Payload]> {
        match &self.repr {
            FailurePayloadsRepr::Decoded(value) => Some(value.raw()),
            FailurePayloadsRepr::Serializable(_) => None,
        }
    }

    /// Consume this value and return the decoded payloads as a [`RawValue`], if present.
    pub fn into_raw(self) -> Option<RawValue> {
        match self.repr {
            FailurePayloadsRepr::Decoded(value) => Some(value.into_raw()),
            FailurePayloadsRepr::Serializable(_) => None,
        }
    }
}

impl From<DecodablePayloads> for FailurePayloads {
    fn from(value: DecodablePayloads) -> Self {
        Self {
            repr: FailurePayloadsRepr::Decoded(value),
        }
    }
}

impl<T> From<T> for FailurePayloads
where
    T: TemporalSerializable + Send + Sync + 'static,
{
    fn from(value: T) -> Self {
        Self {
            repr: FailurePayloadsRepr::Serializable(Box::new(value)),
        }
    }
}

/// User-authored application failure metadata that can be converted into a Temporal failure.
#[derive(Debug, bon::Builder)]
#[builder(start_fn = builder, state_mod(vis = "pub"))]
pub struct ApplicationFailure {
    #[builder(start_fn, into)]
    source: anyhow::Error,
    type_name: Option<String>,
    #[builder(default)]
    non_retryable: bool,
    next_retry_delay: Option<Duration>,
    #[builder(default = ApplicationErrorCategory::Unspecified)]
    category: ApplicationErrorCategory,
    #[builder(into)]
    details: Option<FailurePayloads>,
    failure: Option<Failure>,
    cause: Option<Box<IncomingError>>,
}

impl ApplicationFailure {
    /// Construct a retryable application failure with no extra metadata.
    pub fn new(source: impl Into<anyhow::Error>) -> Self {
        Self {
            source: source.into(),
            type_name: None,
            non_retryable: false,
            next_retry_delay: None,
            category: ApplicationErrorCategory::Unspecified,
            details: None,
            failure: None,
            cause: None,
        }
    }

    /// Construct a non-retryable application failure with no extra metadata.
    pub fn non_retryable(source: impl Into<anyhow::Error>) -> Self {
        Self {
            non_retryable: true,
            ..Self::new(source)
        }
    }

    /// Returns the wrapped source error.
    pub fn source_error(&self) -> &anyhow::Error {
        &self.source
    }

    /// Returns the configured application failure type name, if any.
    pub fn type_name(&self) -> Option<&str> {
        self.type_name.as_deref()
    }

    /// Returns true if this failure should be treated as non-retryable.
    pub fn is_non_retryable(&self) -> bool {
        self.non_retryable
    }

    /// Returns the explicitly configured next retry delay, if any.
    pub fn next_retry_delay(&self) -> Option<Duration> {
        self.next_retry_delay
    }

    /// Returns the application error category.
    pub fn category(&self) -> ApplicationErrorCategory {
        self.category
    }

    /// Returns the decoded details deserialized as the requested type, if any.
    pub fn details<T: TemporalDeserializable + 'static>(
        &self,
    ) -> Result<Option<T>, PayloadConversionError> {
        self.details
            .as_ref()
            .map(FailurePayloads::deserialize)
            .transpose()
    }

    /// Returns the raw decoded details payloads, if any.
    pub fn raw_details(&self) -> Option<&[Payload]> {
        self.details.as_ref().and_then(FailurePayloads::raw)
    }

    pub(crate) fn failure_payloads(&self) -> Option<&FailurePayloads> {
        self.details.as_ref()
    }

    /// Returns the original failure proto when this application failure was decoded from one.
    pub fn failure(&self) -> Option<&Failure> {
        self.failure.as_ref()
    }

    /// Consumes this application failure and returns the retained proto failure, if one exists.
    pub fn into_failure(self) -> Option<Failure> {
        self.failure
    }

    /// Returns the normalized cause, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        self.cause.as_deref()
    }

    /// If this [`ApplicationFailure`] was caused by a timeout, returns the associated
    /// [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        self.cause().and_then(IncomingError::as_timeout)
    }

    /// If this [`ApplicationFailure`] was caused by a cancellation, returns the associated
    /// [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        self.cause().and_then(IncomingError::as_cancelled)
    }

    pub(crate) fn from_failure(
        failure: Failure,
        cause: Option<IncomingError>,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Self {
        let app_info = failure
            .maybe_application_failure()
            .cloned()
            .unwrap_or_default();
        let type_name = (!app_info.r#type.is_empty()).then_some(app_info.r#type.clone());
        Self {
            source: anyhow::anyhow!(failure.message.clone()),
            type_name,
            non_retryable: app_info.non_retryable,
            next_retry_delay: app_info.next_retry_delay.and_then(|d| d.try_into().ok()),
            category: app_info.category(),
            details: app_info.details.map(|details| {
                FailurePayloads::from(DecodablePayloads::new(
                    details.payloads,
                    payload_converter.clone(),
                    *context,
                ))
            }),
            failure: Some(failure),
            cause: cause.map(Box::new),
        }
    }
}

impl std::fmt::Display for ApplicationFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.source)
    }
}

impl std::error::Error for ApplicationFailure {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.cause
            .as_deref()
            .map(|cause| cause as &(dyn std::error::Error + 'static))
            .or_else(|| Some(self.source.as_ref()))
    }
}

impl From<anyhow::Error> for ApplicationFailure {
    fn from(value: anyhow::Error) -> Self {
        Self::new(value)
    }
}

impl From<PayloadConversionError> for ApplicationFailure {
    fn from(value: PayloadConversionError) -> Self {
        Self::new(value)
    }
}

/// A typed outbound error surface used before encoding to a Temporal failure proto.
#[derive(Debug, thiserror::Error)]
pub enum OutgoingError {
    /// An error produced while completing an activity.
    #[error(transparent)]
    Activity(#[from] OutgoingActivityError),
    /// An error produced from a workflow.
    #[error(transparent)]
    Workflow(#[from] OutgoingWorkflowError),
}

/// A typed outbound activity error.
#[derive(Debug, thiserror::Error)]
pub enum OutgoingActivityError {
    /// An activity application failure.
    #[error(transparent)]
    Application(#[from] Box<ApplicationFailure>),
    /// An activity cancellation with optional details.
    #[error("Activity cancelled")]
    Cancelled {
        /// Optional cancellation details.
        details: Option<FailurePayloads>,
    },
}

/// A typed outbound workflow failure.
#[derive(Debug, thiserror::Error)]
pub enum OutgoingWorkflowError {
    /// A workflow application failure.
    #[error(transparent)]
    Application(#[from] Box<ApplicationFailure>),
    /// A workflow failure sourced from an activity execution.
    #[error(transparent)]
    ActivityExecution(#[from] Box<ActivityExecutionError>),
    /// A workflow failure sourced from a child-workflow execution.
    #[error(transparent)]
    ChildWorkflowExecution(#[from] Box<ChildWorkflowExecutionError>),
    /// A workflow failure sourced from child-workflow start.
    #[error(transparent)]
    ChildWorkflowStart(#[from] Box<ChildWorkflowStartError>),
    /// A workflow failure sourced from child-workflow signaling.
    #[error(transparent)]
    ChildWorkflowSignal(#[from] Box<ChildWorkflowSignalError>),
}

impl From<anyhow::Error> for OutgoingWorkflowError {
    fn from(value: anyhow::Error) -> Self {
        Self::Application(Box::new(ApplicationFailure::new(value)))
    }
}

impl From<PayloadConversionError> for OutgoingWorkflowError {
    fn from(value: PayloadConversionError) -> Self {
        Self::Application(Box::new(value.into()))
    }
}

impl From<ApplicationFailure> for OutgoingWorkflowError {
    fn from(value: ApplicationFailure) -> Self {
        Self::Application(Box::new(value))
    }
}

impl From<ActivityExecutionError> for OutgoingWorkflowError {
    fn from(value: ActivityExecutionError) -> Self {
        Self::ActivityExecution(Box::new(value))
    }
}

impl From<ChildWorkflowExecutionError> for OutgoingWorkflowError {
    fn from(value: ChildWorkflowExecutionError) -> Self {
        Self::ChildWorkflowExecution(Box::new(value))
    }
}

impl From<ChildWorkflowStartError> for OutgoingWorkflowError {
    fn from(value: ChildWorkflowStartError) -> Self {
        Self::ChildWorkflowStart(Box::new(value))
    }
}

impl From<ChildWorkflowSignalError> for OutgoingWorkflowError {
    fn from(value: ChildWorkflowSignalError) -> Self {
        Self::ChildWorkflowSignal(Box::new(value))
    }
}

/// A normalized incoming Temporal failure decoded from a protobuf [`Failure`].
#[derive(Debug)]
pub enum IncomingError {
    /// A decoded application failure.
    Application(ApplicationFailure),
    /// A decoded timeout failure.
    Timeout(TimeoutError),
    /// A decoded cancellation failure.
    Cancelled(CancelledError),
    /// A decoded terminated failure.
    Terminated(TerminatedError),
    /// A decoded server failure.
    Server(ServerError),
    /// A decoded reset-workflow failure.
    ResetWorkflow(ResetWorkflowError),
    /// A decoded activity failure wrapper.
    Activity(ActivityFailureError),
    /// A decoded child-workflow failure wrapper.
    ChildWorkflowExecution(ChildWorkflowFailureError),
    /// A decoded nexus operation failure wrapper.
    NexusOperationExecution(IncomingNexusOperationExecutionError),
    /// A decoded nexus handler failure wrapper.
    NexusHandler(IncomingNexusHandlerError),
}

impl IncomingError {
    /// Returns the original failure proto for this normalized error.
    pub fn failure(&self) -> &Failure {
        match self {
            IncomingError::Application(err) => err
                .failure()
                .expect("decoded application failures retain their original proto"),
            IncomingError::Timeout(err) => err.failure(),
            IncomingError::Cancelled(err) => err.failure(),
            IncomingError::Terminated(err) => err.failure(),
            IncomingError::Server(err) => err.failure(),
            IncomingError::ResetWorkflow(err) => err.failure(),
            IncomingError::Activity(err) => err.failure(),
            IncomingError::ChildWorkflowExecution(err) => err.failure(),
            IncomingError::NexusOperationExecution(err) => err.failure(),
            IncomingError::NexusHandler(err) => err.failure(),
        }
    }

    /// Returns the normalized cause, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        match self {
            IncomingError::Application(err) => err.cause(),
            IncomingError::Timeout(err) => err.cause(),
            IncomingError::Cancelled(err) => err.cause(),
            IncomingError::Terminated(err) => err.cause(),
            IncomingError::Server(err) => err.cause(),
            IncomingError::ResetWorkflow(err) => err.cause(),
            IncomingError::Activity(err) => err.cause(),
            IncomingError::ChildWorkflowExecution(err) => err.cause(),
            IncomingError::NexusOperationExecution(err) => err.cause(),
            IncomingError::NexusHandler(err) => err.cause(),
        }
    }

    /// Consumes this normalized error and returns the retained proto failure.
    pub fn into_failure(self) -> Failure {
        match self {
            IncomingError::Application(err) => err
                .into_failure()
                .expect("decoded application failures retain their original proto"),
            IncomingError::Timeout(err) => err.into_failure(),
            IncomingError::Cancelled(err) => err.into_failure(),
            IncomingError::Terminated(err) => err.into_failure(),
            IncomingError::Server(err) => err.into_failure(),
            IncomingError::ResetWorkflow(err) => err.into_failure(),
            IncomingError::Activity(err) => err.into_failure(),
            IncomingError::ChildWorkflowExecution(err) => err.into_failure(),
            IncomingError::NexusOperationExecution(err) => err.into_failure(),
            IncomingError::NexusHandler(err) => err.into_failure(),
        }
    }

    /// If the [`IncomingError`] is a timeout, returns the associated [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        match self {
            IncomingError::Timeout(err) => Some(err),
            _ => None,
        }
    }

    /// If the [`IncomingError`] is a cancellation, returns the associated [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        match self {
            IncomingError::Cancelled(err) => Some(err),
            _ => None,
        }
    }
}

impl std::fmt::Display for IncomingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IncomingError::Application(err) => err.fmt(f),
            IncomingError::Timeout(err) => err.fmt(f),
            IncomingError::Cancelled(err) => err.fmt(f),
            IncomingError::Terminated(err) => err.fmt(f),
            IncomingError::Server(err) => err.fmt(f),
            IncomingError::ResetWorkflow(err) => err.fmt(f),
            IncomingError::Activity(err) => err.fmt(f),
            IncomingError::ChildWorkflowExecution(err) => err.fmt(f),
            IncomingError::NexusOperationExecution(err) => err.fmt(f),
            IncomingError::NexusHandler(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for IncomingError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            IncomingError::Application(err) => Some(err),
            IncomingError::Timeout(err) => Some(err),
            IncomingError::Cancelled(err) => Some(err),
            IncomingError::Terminated(err) => Some(err),
            IncomingError::Server(err) => Some(err),
            IncomingError::ResetWorkflow(err) => Some(err),
            IncomingError::Activity(err) => Some(err),
            IncomingError::ChildWorkflowExecution(err) => Some(err),
            IncomingError::NexusOperationExecution(err) => Some(err),
            IncomingError::NexusHandler(err) => Some(err),
        }
    }
}

macro_rules! impl_incoming_failure_wrapper {
    ($name:ident) => {
        impl $name {
            /// Returns the original failure proto.
            pub fn failure(&self) -> &Failure {
                &self.failure
            }

            /// Returns the normalized cause, if any.
            pub fn cause(&self) -> Option<&IncomingError> {
                self.cause.as_deref()
            }

            /// Consumes this wrapper and returns the retained proto failure.
            pub fn into_failure(self) -> Failure {
                self.failure
            }

            /// Consumes this wrapper and returns the retained proto failure and normalized cause.
            pub fn into_parts(self) -> (Failure, Option<IncomingError>) {
                (self.failure, self.cause.map(|cause| *cause))
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                self.failure.fmt(f)
            }
        }

        impl std::error::Error for $name {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                self.cause
                    .as_deref()
                    .map(|cause| cause as &(dyn std::error::Error + 'static))
            }
        }
    };
}

macro_rules! incoming_failure_wrapper {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[derive(Debug)]
        pub struct $name {
            failure: Failure,
            cause: Option<Box<IncomingError>>,
        }

        impl $name {
            /// Creates a new normalized incoming error wrapper.
            pub(crate) fn new(failure: Failure, cause: Option<IncomingError>) -> Self {
                Self {
                    failure,
                    cause: cause.map(Box::new),
                }
            }
        }

        impl_incoming_failure_wrapper!($name);
    };
}

/// A normalized timeout failure.
#[derive(Debug)]
pub struct TimeoutError {
    failure: Failure,
    cause: Option<Box<IncomingError>>,
    timeout_type: TimeoutType,
    last_heartbeat_details: Option<DecodablePayloads>,
}

impl TimeoutError {
    /// Creates a new normalized timeout error wrapper.
    pub(crate) fn new(
        failure: Failure,
        failure_info: crate::protos::temporal::api::failure::v1::TimeoutFailureInfo,
        cause: Option<IncomingError>,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Self {
        Self {
            failure,
            cause: cause.map(Box::new),
            timeout_type: failure_info.timeout_type(),
            last_heartbeat_details: failure_info.last_heartbeat_details.map(|details| {
                DecodablePayloads::new(details.payloads, payload_converter.clone(), *context)
            }),
        }
    }

    /// Returns the timeout kind described by the failure.
    pub fn timeout_type(&self) -> TimeoutType {
        self.timeout_type
    }

    /// Returns the last heartbeat details carried by the timeout, if any.
    pub fn last_heartbeat_details<T: TemporalDeserializable + 'static>(
        &self,
    ) -> Result<Option<T>, PayloadConversionError> {
        self.last_heartbeat_details
            .as_ref()
            .map(DecodablePayloads::deserialize)
            .transpose()
    }

    /// Returns the raw decoded heartbeat details carried by the timeout, if any.
    pub fn raw_last_heartbeat_details(&self) -> Option<&[Payload]> {
        self.last_heartbeat_details
            .as_ref()
            .map(DecodablePayloads::raw)
    }
}

impl_incoming_failure_wrapper!(TimeoutError);

/// A normalized cancellation failure.
#[derive(Debug)]
pub struct CancelledError {
    failure: Failure,
    cause: Option<Box<IncomingError>>,
    details: Option<DecodablePayloads>,
}

impl CancelledError {
    /// Creates a new normalized cancellation error wrapper.
    pub(crate) fn new(
        failure: Failure,
        failure_info: crate::protos::temporal::api::failure::v1::CanceledFailureInfo,
        cause: Option<IncomingError>,
        payload_converter: &PayloadConverter,
        context: &SerializationContextData,
    ) -> Self {
        Self {
            failure,
            cause: cause.map(Box::new),
            details: failure_info.details.map(|details| {
                DecodablePayloads::new(details.payloads, payload_converter.clone(), *context)
            }),
        }
    }

    /// Returns the cancellation details carried by the failure, deserialized as the requested
    /// type, if any.
    pub fn details<T: TemporalDeserializable + 'static>(
        &self,
    ) -> Result<Option<T>, PayloadConversionError> {
        self.details
            .as_ref()
            .map(DecodablePayloads::deserialize)
            .transpose()
    }

    /// Returns the raw decoded cancellation details carried by the failure, if any.
    pub fn raw_details(&self) -> Option<&[Payload]> {
        self.details.as_ref().map(DecodablePayloads::raw)
    }
}

impl_incoming_failure_wrapper!(CancelledError);
incoming_failure_wrapper!(TerminatedError, "A normalized terminated failure.");
incoming_failure_wrapper!(ServerError, "A normalized server failure.");
incoming_failure_wrapper!(ResetWorkflowError, "A normalized reset-workflow failure.");

/// A normalized activity failure wrapper.
#[derive(Debug)]
pub struct ActivityFailureError {
    failure: Failure,
    cause: Option<Box<IncomingError>>,
    activity_id: String,
    activity_type: Option<crate::protos::temporal::api::common::v1::ActivityType>,
    scheduled_event_id: i64,
    started_event_id: i64,
    identity: String,
    retry_state: crate::protos::temporal::api::enums::v1::RetryState,
}

impl ActivityFailureError {
    /// Creates a new normalized activity failure wrapper.
    pub(crate) fn new(
        failure: Failure,
        failure_info: crate::protos::temporal::api::failure::v1::ActivityFailureInfo,
        cause: Option<IncomingError>,
    ) -> Self {
        let retry_state = failure_info.retry_state();
        Self {
            failure,
            cause: cause.map(Box::new),
            activity_id: failure_info.activity_id,
            activity_type: failure_info.activity_type,
            scheduled_event_id: failure_info.scheduled_event_id,
            started_event_id: failure_info.started_event_id,
            identity: failure_info.identity,
            retry_state,
        }
    }

    /// Returns the activity id reported by the failure.
    pub fn activity_id(&self) -> &str {
        &self.activity_id
    }

    /// Returns the activity type, if present.
    pub fn activity_type(&self) -> Option<&crate::protos::temporal::api::common::v1::ActivityType> {
        self.activity_type.as_ref()
    }

    /// Returns the scheduled event id.
    pub fn scheduled_event_id(&self) -> i64 {
        self.scheduled_event_id
    }

    /// Returns the started event id.
    pub fn started_event_id(&self) -> i64 {
        self.started_event_id
    }

    /// Returns the worker identity captured on the failure.
    pub fn identity(&self) -> &str {
        &self.identity
    }

    /// Returns the retry state reported by core.
    pub fn retry_state(&self) -> crate::protos::temporal::api::enums::v1::RetryState {
        self.retry_state
    }

    /// If this [`ActivityFailureError`] was caused by a timeout, returns the associated
    /// [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        self.cause().and_then(IncomingError::as_timeout)
    }

    /// If this [`ActivityFailureError`] was caused by a cancellation, returns the associated
    /// [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        self.cause().and_then(IncomingError::as_cancelled)
    }
}

impl_incoming_failure_wrapper!(ActivityFailureError);
/// A normalized child-workflow execution failure wrapper.
#[derive(Debug)]
pub struct ChildWorkflowFailureError {
    failure: Failure,
    cause: Option<Box<IncomingError>>,
    namespace: String,
    workflow_execution: Option<crate::protos::temporal::api::common::v1::WorkflowExecution>,
    workflow_type: Option<crate::protos::temporal::api::common::v1::WorkflowType>,
    initiated_event_id: i64,
    started_event_id: i64,
    retry_state: crate::protos::temporal::api::enums::v1::RetryState,
}

impl ChildWorkflowFailureError {
    /// Creates a new normalized child-workflow execution failure wrapper.
    pub(crate) fn new(
        failure: Failure,
        failure_info: crate::protos::temporal::api::failure::v1::ChildWorkflowExecutionFailureInfo,
        cause: Option<IncomingError>,
    ) -> Self {
        let retry_state = failure_info.retry_state();
        Self {
            failure,
            cause: cause.map(Box::new),
            namespace: failure_info.namespace,
            workflow_execution: failure_info.workflow_execution,
            workflow_type: failure_info.workflow_type,
            initiated_event_id: failure_info.initiated_event_id,
            started_event_id: failure_info.started_event_id,
            retry_state,
        }
    }

    /// Returns the namespace of the child workflow.
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Returns the child workflow execution, if present.
    pub fn workflow_execution(
        &self,
    ) -> Option<&crate::protos::temporal::api::common::v1::WorkflowExecution> {
        self.workflow_execution.as_ref()
    }

    /// Returns the child workflow type, if present.
    pub fn workflow_type(&self) -> Option<&crate::protos::temporal::api::common::v1::WorkflowType> {
        self.workflow_type.as_ref()
    }

    /// Returns the initiated event id.
    pub fn initiated_event_id(&self) -> i64 {
        self.initiated_event_id
    }

    /// Returns the started event id.
    pub fn started_event_id(&self) -> i64 {
        self.started_event_id
    }

    /// Returns the retry state reported by core.
    pub fn retry_state(&self) -> crate::protos::temporal::api::enums::v1::RetryState {
        self.retry_state
    }

    /// If this [`ChildWorkflowFailureError`] was caused by a timeout, returns the associated
    /// [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        self.cause().and_then(IncomingError::as_timeout)
    }

    /// If this [`ChildWorkflowFailureError`] was caused by a cancellation, returns the associated
    /// [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        self.cause().and_then(IncomingError::as_cancelled)
    }
}

impl_incoming_failure_wrapper!(ChildWorkflowFailureError);
incoming_failure_wrapper!(
    IncomingNexusOperationExecutionError,
    "A normalized nexus operation failure wrapper."
);
incoming_failure_wrapper!(
    IncomingNexusHandlerError,
    "A normalized nexus handler failure wrapper."
);

/// Error type for activity execution outcomes.
#[derive(Debug, thiserror::Error)]
pub enum ActivityExecutionError {
    /// The activity failed with the given failure details.
    #[error("Activity failed: {}", .0.failure().message)]
    Failed(#[source] ActivityFailureError),
    /// The activity was cancelled.
    #[error("Activity cancelled: {}", .0.failure().message)]
    Cancelled(#[source] CancelledError),
    /// Failed to serialize input or deserialize result payload.
    #[error("Payload conversion failed: {0}")]
    Serialization(#[from] PayloadConversionError),
}

impl ActivityExecutionError {
    /// Returns the retained top-level activity failure proto, if one exists.
    pub fn failure(&self) -> Option<&Failure> {
        match self {
            ActivityExecutionError::Failed(err) => Some(err.failure()),
            ActivityExecutionError::Cancelled(err) => Some(err.failure()),
            ActivityExecutionError::Serialization(_) => None,
        }
    }

    /// Returns the normalized cause of the top-level activity failure, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        match self {
            ActivityExecutionError::Failed(err) => err.cause(),
            ActivityExecutionError::Cancelled(err) => err.cause(),
            ActivityExecutionError::Serialization(_) => None,
        }
    }

    /// Returns the underlying failure reason for wrapper-shaped activity failures.
    pub fn reason(&self) -> Option<&IncomingError> {
        match self {
            ActivityExecutionError::Failed(err) => err.cause(),
            ActivityExecutionError::Cancelled(_) | ActivityExecutionError::Serialization(_) => None,
        }
    }

    /// If this [`ActivityExecutionError`] was caused by a timeout, returns the associated
    /// [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        match self {
            ActivityExecutionError::Failed(err) => err.as_timeout(),
            ActivityExecutionError::Serialization(_) | ActivityExecutionError::Cancelled(_) => None,
        }
    }

    /// If this [`ActivityExecutionError`] was caused by a cancellation, returns the associated
    /// [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        match self {
            ActivityExecutionError::Failed(err) => err.as_cancelled(),
            ActivityExecutionError::Cancelled(err) => Some(err),
            ActivityExecutionError::Serialization(_) => None,
        }
    }
}

/// Error returned when starting a child workflow fails.
#[derive(Debug, thiserror::Error)]
pub enum ChildWorkflowStartError {
    /// The child workflow start was cancelled before the normal execution wrapper path existed.
    #[error("Child workflow start cancelled: {}", .0.failure().message)]
    Cancelled(#[source] Box<CancelledError>),
    /// The child workflow failed to start (e.g., workflow ID already exists).
    #[error(
        "Child workflow start failed: workflow_id={workflow_id}, workflow_type={workflow_type}, cause={cause:?}"
    )]
    StartFailed {
        /// The workflow ID that was requested.
        workflow_id: String,
        /// The workflow type that was requested.
        workflow_type: String,
        /// The cause of the start failure.
        cause: StartChildWorkflowExecutionFailedCause,
    },
    /// Failed to serialize child workflow input payloads.
    #[error("Payload conversion failed: {0}")]
    Serialization(#[from] PayloadConversionError),
}

impl ChildWorkflowStartError {
    /// Returns the retained top-level failure proto, if one exists.
    pub fn failure(&self) -> Option<&Failure> {
        match self {
            ChildWorkflowStartError::Cancelled(err) => Some(err.failure()),
            ChildWorkflowStartError::StartFailed { .. }
            | ChildWorkflowStartError::Serialization(_) => None,
        }
    }

    /// Returns the normalized cause of the retained failure proto, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        match self {
            ChildWorkflowStartError::Cancelled(err) => err.cause(),
            ChildWorkflowStartError::StartFailed { .. }
            | ChildWorkflowStartError::Serialization(_) => None,
        }
    }
}

/// Error returned when a child workflow execution fails.
#[derive(Debug, thiserror::Error)]
pub enum ChildWorkflowExecutionError {
    /// The child workflow failed.
    #[error("Child workflow failed: {}", .0.failure().message)]
    Failed(#[source] Box<ChildWorkflowFailureError>),
    /// Failed to serialize input or deserialize the child workflow result payload.
    #[error("Payload conversion failed: {0}")]
    Serialization(#[from] PayloadConversionError),
}

impl ChildWorkflowExecutionError {
    /// Returns the retained top-level child-workflow failure proto, if one exists.
    pub fn failure(&self) -> Option<&Failure> {
        match self {
            ChildWorkflowExecutionError::Failed(err) => Some(err.failure()),
            ChildWorkflowExecutionError::Serialization(_) => None,
        }
    }

    /// Returns the normalized cause of the top-level child-workflow failure, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        match self {
            ChildWorkflowExecutionError::Failed(err) => err.cause(),
            ChildWorkflowExecutionError::Serialization(_) => None,
        }
    }

    /// Returns the underlying failure reason for wrapper-shaped child-workflow failures.
    pub fn reason(&self) -> Option<&IncomingError> {
        match self {
            ChildWorkflowExecutionError::Failed(err) => err.cause(),
            ChildWorkflowExecutionError::Serialization(_) => None,
        }
    }

    /// If this [`ChildWorkflowExecutionError`] was caused by a timeout, returns the associated
    /// [`TimeoutError`].
    pub fn as_timeout(&self) -> Option<&TimeoutError> {
        match self {
            ChildWorkflowExecutionError::Failed(err) => err.as_timeout(),
            ChildWorkflowExecutionError::Serialization(_) => None,
        }
    }

    /// If this [`ChildWorkflowExecutionError`] was caused by a cancellation, returns the associated
    /// [`CancelledError`].
    pub fn as_cancelled(&self) -> Option<&CancelledError> {
        match self {
            ChildWorkflowExecutionError::Failed(err) => err.as_cancelled(),
            ChildWorkflowExecutionError::Serialization(_) => None,
        }
    }
}

/// Error returned when signaling a child workflow fails.
#[derive(Debug, thiserror::Error)]
pub enum ChildWorkflowSignalError {
    /// The signal delivery failed.
    #[error("Child workflow signal failed: {}", .0.failure().message)]
    Failed(#[source] Box<ChildWorkflowSignalFailureError>),
    /// Failed to serialize the signal input payload.
    #[error("Signal payload conversion failed: {0}")]
    Serialization(#[from] PayloadConversionError),
}

impl ChildWorkflowSignalError {
    /// Returns the retained top-level child-workflow signal failure proto, if one exists.
    pub fn failure(&self) -> Option<&Failure> {
        match self {
            ChildWorkflowSignalError::Failed(err) => Some(err.failure()),
            ChildWorkflowSignalError::Serialization(_) => None,
        }
    }

    /// Returns the normalized cause of the child-workflow signal failure, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        match self {
            ChildWorkflowSignalError::Failed(err) => err.cause(),
            ChildWorkflowSignalError::Serialization(_) => None,
        }
    }

    /// Returns the underlying failure reason for wrapper-shaped signal failures.
    pub fn reason(&self) -> Option<&IncomingError> {
        match self {
            ChildWorkflowSignalError::Failed(err) => Some(err.error()),
            ChildWorkflowSignalError::Serialization(_) => None,
        }
    }
}

/// A normalized child-workflow signal failure wrapper.
#[derive(Debug)]
pub struct ChildWorkflowSignalFailureError {
    failure: Failure,
    error: Box<IncomingError>,
}

impl ChildWorkflowSignalFailureError {
    /// Creates a child-workflow signal failure wrapper.
    pub(crate) fn new(failure: Failure, error: IncomingError) -> Self {
        Self {
            failure,
            error: Box::new(error),
        }
    }

    /// Returns the retained top-level proto failure.
    pub fn failure(&self) -> &Failure {
        &self.failure
    }

    /// Returns the normalized direct cause of the child-workflow signal failure, if any.
    pub fn cause(&self) -> Option<&IncomingError> {
        self.error.cause()
    }

    /// Returns the direct decoded incoming error represented by the top-level proto failure.
    pub fn error(&self) -> &IncomingError {
        &self.error
    }
}

impl std::fmt::Display for ChildWorkflowSignalFailureError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.failure.fmt(f)
    }
}

impl std::error::Error for ChildWorkflowSignalFailureError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.cause()
            .map(|cause| cause as &(dyn std::error::Error + 'static))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        data_converters::{
            DefaultFailureConverter, FailureConverter, GenericPayloadConverter, PayloadConverter,
            SerializationContext, SerializationContextData,
        },
        protos::temporal::api::{common::v1::Payload, failure::v1::failure::FailureInfo},
    };

    struct AlwaysFailsSerialize;

    impl serde::Serialize for AlwaysFailsSerialize {
        fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("serialize boom"))
        }
    }

    #[test]
    fn constructors_set_retryability_defaults() {
        assert!(!ApplicationFailure::new(anyhow::anyhow!("retryable")).is_non_retryable());
        assert!(
            ApplicationFailure::non_retryable(anyhow::anyhow!("non-retryable")).is_non_retryable()
        );
    }

    #[test]
    fn conversion_preserves_application_metadata() {
        let payloads = Payloads {
            payloads: vec![Payload {
                data: b"details".to_vec(),
                ..Default::default()
            }],
        };
        let failure = DefaultFailureConverter.to_failure(
            OutgoingError::Workflow(OutgoingWorkflowError::Application(Box::new(
                ApplicationFailure::builder(anyhow::anyhow!("oops"))
                    .type_name("MyType".to_owned())
                    .non_retryable(true)
                    .next_retry_delay(Duration::from_secs(3))
                    .category(ApplicationErrorCategory::Benign)
                    .details(RawValue::new(payloads.payloads.clone()))
                    .build(),
            ))),
            &PayloadConverter::default(),
            &SerializationContextData::None,
        );
        let Some(FailureInfo::ApplicationFailureInfo(info)) = failure.failure_info else {
            panic!("expected application failure info");
        };
        assert_eq!(failure.message, "oops");
        assert_eq!(info.r#type, "MyType");
        assert!(info.non_retryable);
        assert_eq!(info.details, Some(payloads));
        assert_eq!(info.category(), ApplicationErrorCategory::Benign);
        assert_eq!(info.next_retry_delay.unwrap().seconds, 3);
    }

    #[test]
    fn builder_accepts_raw_payload_details() {
        let payload = Payload {
            data: b"details".to_vec(),
            ..Default::default()
        };
        let failure = DefaultFailureConverter.to_failure(
            OutgoingError::Workflow(OutgoingWorkflowError::Application(Box::new(
                ApplicationFailure::builder(anyhow::anyhow!("oops"))
                    .details(RawValue::new(vec![payload.clone()]))
                    .build(),
            ))),
            &PayloadConverter::default(),
            &SerializationContextData::None,
        );

        let Some(FailureInfo::ApplicationFailureInfo(info)) = failure.failure_info else {
            panic!("expected application failure info");
        };
        assert_eq!(info.details.unwrap().payloads, vec![payload]);
    }

    #[test]
    fn builder_accepts_serializable_details() {
        let failure = DefaultFailureConverter.to_failure(
            OutgoingError::Workflow(OutgoingWorkflowError::Application(Box::new(
                ApplicationFailure::builder(anyhow::anyhow!("oops"))
                    .details("details".to_string())
                    .build(),
            ))),
            &PayloadConverter::default(),
            &SerializationContextData::None,
        );

        let Some(FailureInfo::ApplicationFailureInfo(info)) = failure.failure_info else {
            panic!("expected application failure info");
        };
        let payloads = info.details.expect("expected details").payloads;
        let converter = PayloadConverter::default();
        let details: String = converter
            .from_payloads(
                &SerializationContext {
                    data: &SerializationContextData::None,
                    converter: &converter,
                },
                payloads,
            )
            .unwrap();
        assert_eq!(details, "details");
    }

    #[test]
    fn application_failure_encoding_surfaces_detail_encoding_errors() {
        let failure = DefaultFailureConverter.to_failure(
            OutgoingError::Workflow(OutgoingWorkflowError::Application(Box::new(
                ApplicationFailure::builder(anyhow::anyhow!("oops"))
                    .details(AlwaysFailsSerialize)
                    .build(),
            ))),
            &PayloadConverter::default(),
            &SerializationContextData::None,
        );

        assert_eq!(
            failure.message,
            "Failed converting error to failure: Encoding error: serialize boom, original error message: oops"
        );
        assert!(matches!(
            failure.failure_info,
            Some(FailureInfo::ApplicationFailureInfo(_))
        ));
    }

    #[test]
    fn anyhow_workflow_errors_default_to_application_outgoing_errors() {
        let outgoing: OutgoingWorkflowError = anyhow::anyhow!("workflow boom").into();

        let OutgoingWorkflowError::Application(app) = outgoing else {
            panic!("plain workflow errors should default to application failures");
        };
        assert_eq!(app.to_string(), "workflow boom");
    }

    #[test]
    fn payload_conversion_errors_default_to_application_outgoing_errors() {
        let outgoing: OutgoingWorkflowError =
            PayloadConversionError::EncodingError(anyhow::anyhow!("encode boom").into()).into();

        let OutgoingWorkflowError::Application(app) = outgoing else {
            panic!("payload conversion errors should default to application failures");
        };
        assert_eq!(app.to_string(), "Encoding error: encode boom");
    }
}