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
use std::time::Duration;
use std::time::SystemTime;

use google_api_proto::google::spanner::v1 as proto;

/// Specifies the bounds withing wich to make reads in Spanner.
///
/// See [the Spanner Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions.ReadOnly)
#[derive(Clone, Debug)]
pub enum TimestampBound {
    /// Read at a timestamp where all previously committed transactions are visible.
    ///
    /// Strong reads are guaranteed to see the effects of all transactions that have committed before the start of the read.
    /// Furthermore, all rows yielded by a single read are consistent with each other -- if any part of the read observes a transaction, all parts of the read see the transaction.
    Strong,

    /// Executes all reads at the given timestamp.
    ///
    /// Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data.
    /// If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.
    ///
    /// Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.
    ReadTimestamp(SystemTime),

    /// Executes all reads at a timestamp >= the provided timestamp.
    ///
    /// This is useful for requesting fresher data than some previous read,
    /// or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.
    MinReadTimestamp(SystemTime),

    /// Executes all reads at a timestamp that is `ExactStaleness` old. The timestamp is chosen soon after the read is started.
    ///
    /// Guarantees that all writes that have committed more than the specified number of seconds ago are visible.
    ExactStaleness(Duration),

    /// Read data at a timestamp `>= now() - MaxStaleness` seconds.
    ///
    /// Guarantees that all writes that have committed more than the specified number of seconds ago are visible.
    MaxStaleness(Duration),
}

impl TryFrom<TimestampBound> for proto::transaction_options::read_only::TimestampBound {
    type Error = super::Error;

    fn try_from(value: TimestampBound) -> Result<Self, Self::Error> {
        match value {
            TimestampBound::Strong => {
                Ok(proto::transaction_options::read_only::TimestampBound::Strong(true))
            }
            TimestampBound::ReadTimestamp(timestamp) => Ok(
                proto::transaction_options::read_only::TimestampBound::ReadTimestamp(
                    timestamp.into(),
                ),
            ),
            TimestampBound::MinReadTimestamp(timestamp) => Ok(
                proto::transaction_options::read_only::TimestampBound::MinReadTimestamp(
                    timestamp.into(),
                ),
            ),
            TimestampBound::MaxStaleness(duration) => Ok(
                proto::transaction_options::read_only::TimestampBound::MaxStaleness(
                    duration
                        .try_into()
                        .map_err(|_| super::Error::Client(format!("invalid bound {duration:?}")))?,
                ),
            ),
            TimestampBound::ExactStaleness(duration) => Ok(
                proto::transaction_options::read_only::TimestampBound::ExactStaleness(
                    duration
                        .try_into()
                        .map_err(|_| super::Error::Client(format!("invalid bound {duration:?}")))?,
                ),
            ),
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) enum TransactionSelector {
    SingleUse(Option<TimestampBound>),
    Id(Transaction),
    Begin,
}

impl TryFrom<TransactionSelector> for proto::TransactionSelector {
    type Error = super::Error;
    fn try_from(value: TransactionSelector) -> Result<Self, Self::Error> {
        match value {
            TransactionSelector::SingleUse(bound) => Ok(proto::TransactionSelector {
                selector: Some(proto::transaction_selector::Selector::SingleUse(
                    proto::TransactionOptions {
                        mode: Some(proto::transaction_options::Mode::ReadOnly(
                            proto::transaction_options::ReadOnly {
                                return_read_timestamp: false,
                                timestamp_bound: match bound {
                                    Some(bound) => Some(bound.try_into()?),
                                    None => None,
                                },
                            },
                        )),
                    },
                )),
            }),
            TransactionSelector::Id(tx) => Ok(proto::TransactionSelector {
                selector: Some(proto::transaction_selector::Selector::Id(tx.spanner_tx.id)),
            }),
            TransactionSelector::Begin => Ok(proto::TransactionSelector {
                selector: Some(proto::transaction_selector::Selector::Begin(
                    proto::TransactionOptions {
                        mode: Some(proto::transaction_options::Mode::ReadWrite(
                            proto::transaction_options::ReadWrite {
                                read_lock_mode: proto::transaction_options::read_write::ReadLockMode::Unspecified.into(),
                            },
                        )),
                    },
                )),
            }),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Transaction {
    spanner_tx: proto::Transaction,
}

impl Transaction {
    pub(crate) fn id(&self) -> &prost::bytes::Bytes {
        &self.spanner_tx.id
    }
}

impl From<proto::Transaction> for Transaction {
    fn from(spanner_tx: proto::Transaction) -> Self {
        Transaction { spanner_tx }
    }
}

impl From<Transaction> for proto::Transaction {
    fn from(tx: Transaction) -> Self {
        tx.spanner_tx
    }
}