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
use std::iter::Take;
use std::marker::PhantomData;

use crate::session::SessionError;
use google_cloud_gax::grpc::{Code, Status};
use google_cloud_gax::retry::{CodeCondition, Condition, ExponentialBackoff, Retry, RetrySetting, TryAs};

pub struct TransactionCondition<E>
where
    E: TryAs<Status> + From<SessionError> + From<Status>,
{
    inner: CodeCondition,
    _marker: PhantomData<E>,
}

impl<E> Condition<E> for TransactionCondition<E>
where
    E: TryAs<Status> + From<SessionError> + From<Status>,
{
    fn should_retry(&mut self, error: &E) -> bool {
        if let Some(status) = error.try_as() {
            let code = status.code();
            if code == Code::Internal
                && !status.message().contains("stream terminated by RST_STREAM")
                && !status.message().contains("HTTP/2 error code: INTERNAL_ERROR")
                && !status.message().contains("Connection closed with unknown cause")
                && !status
                    .message()
                    .contains("Received unexpected EOS on DATA frame from server")
            {
                return false;
            }
            return self.inner.should_retry(error);
        }
        false
    }
}

#[derive(Clone)]
pub struct TransactionRetrySetting {
    pub inner: RetrySetting,
}

impl<E> Retry<E, TransactionCondition<E>> for TransactionRetrySetting
where
    E: TryAs<Status> + From<SessionError> + From<Status>,
{
    fn strategy(&self) -> Take<ExponentialBackoff> {
        self.inner.strategy()
    }

    fn condition(&self) -> TransactionCondition<E> {
        TransactionCondition {
            inner: CodeCondition::new(self.inner.codes.clone()),
            _marker: PhantomData::default(),
        }
    }
}

impl TransactionRetrySetting {
    pub fn new(codes: Vec<Code>) -> Self {
        Self {
            inner: RetrySetting {
                codes,
                ..Default::default()
            },
        }
    }
}

impl Default for TransactionRetrySetting {
    fn default() -> Self {
        TransactionRetrySetting::new(vec![Code::Aborted])
    }
}

#[cfg(test)]
mod tests {
    use crate::client::{RunInTxError, TxError};
    use crate::retry::TransactionRetrySetting;
    use google_cloud_gax::grpc::{Code, Status};
    use google_cloud_gax::retry::{Condition, Retry};

    #[test]
    fn test_transaction_condition() {
        let err = &TxError::GRPC(Status::new(Code::Internal, "stream terminated by RST_STREAM"));
        let default = TransactionRetrySetting::default();
        assert!(!default.condition().should_retry(err));

        let err = &RunInTxError::GRPC(Status::new(Code::Aborted, ""));
        assert!(default.condition().should_retry(err));
    }
}