-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathtransaction.rs
More file actions
1482 lines (1386 loc) · 53.2 KB
/
transaction.rs
File metadata and controls
1482 lines (1386 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::{
backoff::{Backoff, DEFAULT_REGION_BACKOFF},
pd::{PdClient, PdRpcClient},
request::{
Collect, CollectError, CollectSingle, CollectWithShard, Plan, PlanBuilder, RetryOptions,
},
timestamp::TimestampExt,
transaction::{buffer::Buffer, lowering::*},
BoundRange, Error, Key, KvPair, Result, Value,
};
use derive_new::new;
use fail::fail_point;
use futures::prelude::*;
use slog::Logger;
use std::{iter, sync::Arc, time::Instant};
use tikv_client_proto::{kvrpcpb, pdpb::Timestamp};
use tokio::{sync::RwLock, time::Duration};
/// An undo-able set of actions on the dataset.
///
/// Create a transaction using a [`TransactionClient`](crate::TransactionClient), then run actions
/// (such as `get`, or `put`) on the transaction. Reads are executed immediately, writes are
/// buffered locally. Once complete, `commit` the transaction. Behind the scenes, the client will
/// perform a two phase commit and return success as soon as the writes are guaranteed to be
/// committed (some finalisation may continue in the background after the return, but no data can be
/// lost).
///
/// TiKV transactions use multi-version concurrency control. All reads logically happen at the start
/// of the transaction (at the start timestamp, `start_ts`). Once a transaction is commited, a
/// its writes atomically become visible to other transactions at (logically) the commit timestamp.
///
/// In other words, a transaction can read data that was committed at `commit_ts` < its `start_ts`,
/// and its writes are readable by transactions with `start_ts` >= its `commit_ts`.
///
/// Mutations are buffered locally and sent to the TiKV cluster at the time of commit.
/// In a pessimistic transaction, all write operations and `xxx_for_update` operations will immediately
/// acquire locks from TiKV. Such a lock blocks other transactions from writing to that key.
/// A lock exists until the transaction is committed or rolled back, or the lock reaches its time to
/// live (TTL).
///
/// For details, the [SIG-Transaction](https://github.com/tikv/sig-transaction)
/// provides materials explaining designs and implementations of TiKV transactions.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// let client = TransactionClient::new(vec!["192.168.0.100"], None)
/// .await
/// .unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let foo = txn.get("foo".to_owned()).await.unwrap().unwrap();
/// txn.put("bar".to_owned(), foo).await.unwrap();
/// txn.commit().await.unwrap();
/// # });
/// ```
pub struct Transaction<PdC: PdClient = PdRpcClient> {
status: Arc<RwLock<TransactionStatus>>,
timestamp: Timestamp,
buffer: Buffer,
rpc: Arc<PdC>,
options: TransactionOptions,
is_heartbeat_started: bool,
start_instant: Instant,
logger: Logger,
}
impl<PdC: PdClient> Transaction<PdC> {
pub(crate) fn new(
timestamp: Timestamp,
rpc: Arc<PdC>,
options: TransactionOptions,
logger: Logger,
) -> Transaction<PdC> {
let status = if options.read_only {
TransactionStatus::ReadOnly
} else {
TransactionStatus::Active
};
Transaction {
status: Arc::new(RwLock::new(status)),
timestamp,
buffer: Buffer::new(options.is_pessimistic()),
rpc,
options,
is_heartbeat_started: false,
start_instant: std::time::Instant::now(),
logger,
}
}
/// Create a new 'get' request
///
/// Once resolved this request will result in the fetching of the value associated with the
/// given key.
///
/// Retuning `Ok(None)` indicates the key does not exist in TiKV.
///
/// # Examples
/// ```rust,no_run
/// # use tikv_client::{Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key = "TiKV".to_owned();
/// let result: Option<Value> = txn.get(key).await.unwrap();
/// # });
/// ```
pub async fn get(&mut self, key: impl Into<Key>) -> Result<Option<Value>> {
debug!(self.logger, "invoking transactional get request");
self.check_allow_operation(true).await?;
let timestamp = self.timestamp.clone();
let rpc = self.rpc.clone();
let key = key.into();
let retry_options = self.options.retry_options.clone();
self.buffer
.get_or_else(key, |key| async move {
let request = new_get_request(key, timestamp);
let plan = PlanBuilder::new(rpc, request)
.resolve_lock(retry_options.lock_backoff)
.retry_multi_region(DEFAULT_REGION_BACKOFF)
.merge(CollectSingle)
.post_process_default()
.plan();
plan.execute().await
})
.await
}
/// Create a `get for update` request.
///
/// The request reads and "locks" a key. It is similar to `SELECT ... FOR
/// UPDATE` in TiDB, and has different behavior in optimistic and
/// pessimistic transactions.
///
/// # Optimistic transaction
///
/// It reads at the "start timestamp" and caches the value, just like normal
/// get requests. The lock is written in prewrite and commit, so it cannot
/// prevent concurrent transactions from writing the same key, but can only
/// prevent itself from committing.
///
/// # Pessimistic transaction
///
/// It reads at the "current timestamp" and thus does not cache the value.
/// So following read requests won't be affected by the `get_for_udpate`.
/// A lock will be acquired immediately with this request, which prevents
/// concurrent transactions from mutating the keys.
///
/// The "current timestamp" (also called `for_update_ts` of the request) is fetched from PD.
///
/// Note: The behavior of this command under pessimistic transaction does not follow snapshot.
/// It reads the latest value (using current timestamp), and the value is not cached in the
/// local buffer. So normal `get`-like commands after `get_for_update` will not be influenced,
/// they still read values at the transaction's `start_ts`.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_pessimistic().await.unwrap();
/// let key = "TiKV".to_owned();
/// let result: Value = txn.get_for_update(key).await.unwrap().unwrap();
/// // now the key "TiKV" is locked, other transactions cannot modify it
/// // Finish the transaction...
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn get_for_update(&mut self, key: impl Into<Key>) -> Result<Option<Value>> {
debug!(self.logger, "invoking transactional get_for_update request");
self.check_allow_operation(false).await?;
if !self.is_pessimistic() {
let key = key.into();
self.lock_keys(iter::once(key.clone())).await?;
self.get(key).await
} else {
let mut pairs = self.pessimistic_lock(iter::once(key.into()), true).await?;
debug_assert!(pairs.len() <= 1);
match pairs.pop() {
Some(pair) => Ok(Some(pair.1)),
None => Ok(None),
}
}
}
/// Check whether a key exists.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_pessimistic().await.unwrap();
/// let exists = txn.key_exists("k1".to_owned()).await.unwrap();
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn key_exists(&mut self, key: impl Into<Key>) -> Result<bool> {
debug!(self.logger, "invoking transactional key_exists request");
Ok(self.get(key).await?.is_some())
}
/// Create a new 'batch get' request.
///
/// Once resolved this request will result in the fetching of the values associated with the
/// given keys.
///
/// Non-existent entries will not appear in the result. The order of the keys is not retained in
/// the result.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # use std::collections::HashMap;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let keys = vec!["TiKV".to_owned(), "TiDB".to_owned()];
/// let result: HashMap<Key, Value> = txn
/// .batch_get(keys)
/// .await
/// .unwrap()
/// .map(|pair| (pair.0, pair.1))
/// .collect();
/// // Finish the transaction...
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn batch_get(
&mut self,
keys: impl IntoIterator<Item = impl Into<Key>>,
) -> Result<impl Iterator<Item = KvPair>> {
debug!(self.logger, "invoking transactional batch_get request");
self.check_allow_operation(true).await?;
let timestamp = self.timestamp.clone();
let rpc = self.rpc.clone();
let retry_options = self.options.retry_options.clone();
self.buffer
.batch_get_or_else(keys.into_iter().map(|k| k.into()), move |keys| async move {
let request = new_batch_get_request(keys, timestamp);
let plan = PlanBuilder::new(rpc, request)
.resolve_lock(retry_options.lock_backoff)
.retry_multi_region(retry_options.region_backoff)
.merge(Collect)
.plan();
plan.execute()
.await
.map(|r| r.into_iter().map(Into::into).collect())
})
.await
}
/// Create a new 'batch get for update' request.
///
/// Similar to [`get_for_update`](Transaction::get_for_update), but it works
/// for a batch of keys.
///
/// Non-existent entries will not appear in the result. The order of the
/// keys is not retained in the result.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, Value, Config, TransactionClient, KvPair};
/// # use futures::prelude::*;
/// # use std::collections::HashMap;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_pessimistic().await.unwrap();
/// let keys = vec!["foo".to_owned(), "bar".to_owned()];
/// let result: Vec<KvPair> = txn
/// .batch_get_for_update(keys)
/// .await
/// .unwrap();
/// // now "foo" and "bar" are both locked
/// // Finish the transaction...
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn batch_get_for_update(
&mut self,
keys: impl IntoIterator<Item = impl Into<Key>>,
) -> Result<Vec<KvPair>> {
debug!(
self.logger,
"invoking transactional batch_get_for_update request"
);
self.check_allow_operation(false).await?;
let keys: Vec<Key> = keys.into_iter().map(|k| k.into()).collect();
if !self.is_pessimistic() {
self.lock_keys(keys.clone()).await?;
Ok(self.batch_get(keys).await?.collect())
} else {
self.pessimistic_lock(keys, true).await
}
}
/// Create a new 'scan' request.
///
/// Once resolved this request will result in a `Vec` of all key-value pairs that lie in the
/// specified range.
///
/// If the number of eligible key-value pairs are greater than `limit`,
/// only the first `limit` pairs are returned, ordered by key.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, KvPair, Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # use std::collections::HashMap;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key1: Key = b"foo".to_vec().into();
/// let key2: Key = b"bar".to_vec().into();
/// let result: Vec<KvPair> = txn
/// .scan(key1..key2, 10)
/// .await
/// .unwrap()
/// .collect();
/// // Finish the transaction...
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn scan(
&mut self,
range: impl Into<BoundRange>,
limit: u32,
) -> Result<impl Iterator<Item = KvPair>> {
debug!(self.logger, "invoking transactional scan request");
self.scan_inner(range, limit, false, false).await
}
/// Create a new 'scan' request that only returns the keys.
///
/// Once resolved this request will result in a `Vec` of keys that lies in the specified range.
///
/// If the number of eligible keys are greater than `limit`,
/// only the first `limit` keys are returned, ordered by key.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, KvPair, Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # use std::collections::HashMap;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key1: Key = b"foo".to_vec().into();
/// let key2: Key = b"bar".to_vec().into();
/// let result: Vec<Key> = txn
/// .scan_keys(key1..key2, 10)
/// .await
/// .unwrap()
/// .collect();
/// // Finish the transaction...
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn scan_keys(
&mut self,
range: impl Into<BoundRange>,
limit: u32,
) -> Result<impl Iterator<Item = Key>> {
debug!(self.logger, "invoking transactional scan_keys request");
Ok(self
.scan_inner(range, limit, true, false)
.await?
.map(KvPair::into_key))
}
/// Create a 'scan_reverse' request.
///
/// Similar to [`scan`](Transaction::scan), but scans in the reverse direction.
pub async fn scan_reverse(
&mut self,
range: impl Into<BoundRange>,
limit: u32,
) -> Result<impl Iterator<Item = KvPair>> {
debug!(self.logger, "invoking transactional scan_reverse request");
self.scan_inner(range, limit, false, true).await
}
/// Create a 'scan_keys_reverse' request.
///
/// Similar to [`scan`](Transaction::scan_keys), but scans in the reverse direction.
pub async fn scan_keys_reverse(
&mut self,
range: impl Into<BoundRange>,
limit: u32,
) -> Result<impl Iterator<Item = Key>> {
debug!(
self.logger,
"invoking transactional scan_keys_reverse request"
);
Ok(self
.scan_inner(range, limit, true, true)
.await?
.map(KvPair::into_key))
}
/// Sets the value associated with the given key.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key = "foo".to_owned();
/// let val = "FOO".to_owned();
/// txn.put(key, val);
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn put(&mut self, key: impl Into<Key>, value: impl Into<Value>) -> Result<()> {
debug!(self.logger, "invoking transactional put request");
self.check_allow_operation(false).await?;
let key = key.into();
if self.is_pessimistic() {
self.pessimistic_lock(iter::once(key.clone()), false)
.await?;
}
self.buffer.put(key, value.into());
Ok(())
}
/// Inserts the value associated with the given key.
///
/// Similar to [`put'], but it has an additional constraint that the key should not exist
/// before this operation.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, Value, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key = "foo".to_owned();
/// let val = "FOO".to_owned();
/// txn.insert(key, val);
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn insert(&mut self, key: impl Into<Key>, value: impl Into<Value>) -> Result<()> {
debug!(self.logger, "invoking transactional insert request");
self.check_allow_operation(false).await?;
let key = key.into();
if self.buffer.get(&key).is_some() {
return Err(Error::DuplicateKeyInsertion);
}
if self.is_pessimistic() {
self.pessimistic_lock(
iter::once((key.clone(), kvrpcpb::Assertion::NotExist)),
false,
)
.await?;
}
self.buffer.insert(key, value.into());
Ok(())
}
/// Deletes the given key and its value from the database.
///
/// Deleting a non-existent key will not result in an error.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Key, Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100", "192.168.0.101"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// let key = "foo".to_owned();
/// txn.delete(key);
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn delete(&mut self, key: impl Into<Key>) -> Result<()> {
debug!(self.logger, "invoking transactional delete request");
self.check_allow_operation(false).await?;
let key = key.into();
if self.is_pessimistic() {
self.pessimistic_lock(iter::once(key.clone()), false)
.await?;
}
self.buffer.delete(key);
Ok(())
}
/// Lock the given keys without mutating their values.
///
/// In optimistic mode, write conflicts are not checked until commit.
/// So use this command to indicate that
/// "I do not want to commit if the value associated with this key has been modified".
/// It's useful to avoid the *write skew* anomaly.
///
/// In pessimistic mode, it is similar to [`batch_get_for_update`](Transaction::batch_get_for_update),
/// except that it does not read values.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Config, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// txn.lock_keys(vec!["TiKV".to_owned(), "Rust".to_owned()]);
/// // ... Do some actions.
/// txn.commit().await.unwrap();
/// # });
/// ```
pub async fn lock_keys(
&mut self,
keys: impl IntoIterator<Item = impl Into<Key>>,
) -> Result<()> {
debug!(self.logger, "invoking transactional lock_keys request");
self.check_allow_operation(false).await?;
match self.options.kind {
TransactionKind::Optimistic => {
for key in keys {
self.buffer.lock(key.into());
}
}
TransactionKind::Pessimistic(_) => {
self.pessimistic_lock(keys.into_iter().map(|k| k.into()), false)
.await?;
}
}
Ok(())
}
/// Commits the actions of the transaction. On success, we return the commit timestamp (or
/// `None` if there was nothing to commit).
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Config, Timestamp, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// // ... Do some actions.
/// let result: Timestamp = txn.commit().await.unwrap().unwrap();
/// # });
/// ```
pub async fn commit(&mut self) -> Result<Option<Timestamp>> {
debug!(self.logger, "commiting transaction");
{
// readonly transaction no need to commit
let status = self.status.read().await;
if *status == TransactionStatus::ReadOnly {
return Ok(None);
}
}
{
let mut status = self.status.write().await;
if !matches!(
*status,
TransactionStatus::StartedCommit | TransactionStatus::Active
) {
return Err(Error::OperationAfterCommitError);
}
*status = TransactionStatus::StartedCommit;
}
let primary_key = self.buffer.get_primary_key();
let mutations = self.buffer.to_proto_mutations();
if mutations.is_empty() {
assert!(primary_key.is_none());
return Ok(None);
}
self.start_auto_heartbeat().await;
let res = Committer::new(
primary_key,
mutations,
self.timestamp.clone(),
self.rpc.clone(),
self.options.clone(),
self.buffer.get_write_size() as u64,
self.start_instant,
self.logger.new(o!("child" => 1)),
)
.commit()
.await;
if res.is_ok() {
let mut status = self.status.write().await;
*status = TransactionStatus::Committed;
}
res
}
/// Rollback the transaction.
///
/// If it succeeds, all mutations made by this transaction will be discarded.
///
/// # Examples
///
/// ```rust,no_run
/// # use tikv_client::{Config, Timestamp, TransactionClient};
/// # use futures::prelude::*;
/// # futures::executor::block_on(async {
/// # let client = TransactionClient::new(vec!["192.168.0.100"], None).await.unwrap();
/// let mut txn = client.begin_optimistic().await.unwrap();
/// // ... Do some actions.
/// txn.rollback().await.unwrap();
/// # });
/// ```
pub async fn rollback(&mut self) -> Result<()> {
debug!(self.logger, "rolling back transaction");
{
let status = self.status.read().await;
if !matches!(
*status,
TransactionStatus::StartedRollback
| TransactionStatus::Active
| TransactionStatus::StartedCommit
) {
return Err(Error::OperationAfterCommitError);
}
}
{
let mut status = self.status.write().await;
*status = TransactionStatus::StartedRollback;
}
let primary_key = self.buffer.get_primary_key();
let mutations = self.buffer.to_proto_mutations();
let res = Committer::new(
primary_key,
mutations,
self.timestamp.clone(),
self.rpc.clone(),
self.options.clone(),
self.buffer.get_write_size() as u64,
self.start_instant,
self.logger.new(o!("child" => 1)),
)
.rollback()
.await;
if res.is_ok() {
let mut status = self.status.write().await;
*status = TransactionStatus::Rolledback;
}
res
}
/// Get the start timestamp of this transaction.
pub fn start_timestamp(&self) -> Timestamp {
self.timestamp.clone()
}
/// Send a heart beat message to keep the transaction alive on the server and update its TTL.
///
/// Returns the TTL set on the transaction's locks by TiKV.
#[doc(hidden)]
pub async fn send_heart_beat(&mut self) -> Result<u64> {
debug!(self.logger, "sending heart_beat");
self.check_allow_operation(true).await?;
let primary_key = match self.buffer.get_primary_key() {
Some(k) => k,
None => return Err(Error::NoPrimaryKey),
};
let request = new_heart_beat_request(
self.timestamp.clone(),
primary_key,
self.start_instant.elapsed().as_millis() as u64 + MAX_TTL,
);
let plan = PlanBuilder::new(self.rpc.clone(), request)
.resolve_lock(self.options.retry_options.lock_backoff.clone())
.retry_multi_region(self.options.retry_options.region_backoff.clone())
.merge(CollectSingle)
.post_process_default()
.plan();
plan.execute().await
}
async fn scan_inner(
&mut self,
range: impl Into<BoundRange>,
limit: u32,
key_only: bool,
reverse: bool,
) -> Result<impl Iterator<Item = KvPair>> {
self.check_allow_operation(true).await?;
let timestamp = self.timestamp.clone();
let rpc = self.rpc.clone();
let retry_options = self.options.retry_options.clone();
self.buffer
.scan_and_fetch(
range.into(),
limit,
!key_only,
reverse,
move |new_range, new_limit| async move {
let request =
new_scan_request(new_range, timestamp, new_limit, key_only, reverse);
let plan = PlanBuilder::new(rpc, request)
.resolve_lock(retry_options.lock_backoff)
.retry_multi_region(retry_options.region_backoff)
.merge(Collect)
.plan();
plan.execute()
.await
.map(|r| r.into_iter().map(Into::into).collect())
},
)
.await
}
/// Pessimistically lock the keys, and optionally retrieve corresponding values.
/// If a key does not exist, the corresponding pair will not appear in the result.
///
/// Once resolved it acquires locks on the keys in TiKV.
/// A lock prevents other transactions from mutating the entry until it is released.
///
/// # Panics
///
/// Only valid for pessimistic transactions, panics if called on an optimistic transaction.
async fn pessimistic_lock(
&mut self,
keys: impl IntoIterator<Item = impl PessimisticLock>,
need_value: bool,
) -> Result<Vec<KvPair>> {
debug!(self.logger, "acquiring pessimistic lock");
assert!(
matches!(self.options.kind, TransactionKind::Pessimistic(_)),
"`pessimistic_lock` is only valid to use with pessimistic transactions"
);
let keys: Vec<_> = keys.into_iter().collect();
if keys.is_empty() {
return Ok(vec![]);
}
let first_key = keys[0].clone().key();
// we do not set the primary key here, because pessimistic lock request
// can fail, in which case the keys may not be part of the transaction.
let primary_lock = self
.buffer
.get_primary_key()
.unwrap_or_else(|| first_key.clone());
let for_update_ts = self.rpc.clone().get_timestamp().await?;
self.options.push_for_update_ts(for_update_ts.clone());
let request = new_pessimistic_lock_request(
keys.clone().into_iter(),
primary_lock,
self.timestamp.clone(),
MAX_TTL,
for_update_ts.clone(),
need_value,
);
let plan = PlanBuilder::new(self.rpc.clone(), request)
.resolve_lock(self.options.retry_options.lock_backoff.clone())
.preserve_shard()
.retry_multi_region_preserve_results(self.options.retry_options.region_backoff.clone())
.merge(CollectWithShard)
.plan();
let pairs = plan.execute().await;
if let Err(err) = pairs {
match err {
Error::PessimisticLockError {
inner,
success_keys,
} if !success_keys.is_empty() => {
let keys = success_keys.into_iter().map(Key::from);
self.pessimistic_lock_rollback(keys, self.timestamp.clone(), for_update_ts)
.await?;
Err(*inner)
}
_ => Err(err),
}
} else {
// primary key will be set here if needed
self.buffer.primary_key_or(&first_key);
self.start_auto_heartbeat().await;
for key in keys {
self.buffer.lock(key.key());
}
pairs
}
}
/// Rollback pessimistic lock
async fn pessimistic_lock_rollback(
&mut self,
keys: impl Iterator<Item = Key>,
start_version: Timestamp,
for_update_ts: Timestamp,
) -> Result<()> {
debug!(self.logger, "rollback pessimistic lock");
let keys: Vec<_> = keys.into_iter().collect();
if keys.is_empty() {
return Ok(());
}
let req = new_pessimistic_rollback_request(
keys.clone().into_iter(),
start_version,
for_update_ts,
);
let plan = PlanBuilder::new(self.rpc.clone(), req)
.resolve_lock(self.options.retry_options.lock_backoff.clone())
.retry_multi_region(self.options.retry_options.region_backoff.clone())
.extract_error()
.plan();
plan.execute().await?;
for key in keys {
self.buffer.unlock(&key);
}
Ok(())
}
/// Checks if the transaction can perform arbitrary operations.
async fn check_allow_operation(&self, readonly: bool) -> Result<()> {
let status = self.status.read().await;
match *status {
TransactionStatus::Active => Ok(()),
TransactionStatus::ReadOnly => {
if readonly {
Ok(())
} else {
Err(Error::OperationReadOnlyError)
}
}
TransactionStatus::Committed
| TransactionStatus::Rolledback
| TransactionStatus::StartedCommit
| TransactionStatus::StartedRollback
| TransactionStatus::Dropped => Err(Error::OperationAfterCommitError),
}
}
fn is_pessimistic(&self) -> bool {
matches!(self.options.kind, TransactionKind::Pessimistic(_))
}
async fn start_auto_heartbeat(&mut self) {
debug!(self.logger, "starting auto_heartbeat");
if !self.options.heartbeat_option.is_auto_heartbeat() || self.is_heartbeat_started {
return;
}
self.is_heartbeat_started = true;
let status = self.status.clone();
let primary_key = self
.buffer
.get_primary_key()
.expect("Primary key should exist");
let start_ts = self.timestamp.clone();
let region_backoff = self.options.retry_options.region_backoff.clone();
let rpc = self.rpc.clone();
let heartbeat_interval = match self.options.heartbeat_option {
HeartbeatOption::NoHeartbeat => DEFAULT_HEARTBEAT_INTERVAL,
HeartbeatOption::FixedTime(heartbeat_interval) => heartbeat_interval,
};
let start_instant = self.start_instant;
let heartbeat_task = async move {
loop {
tokio::time::sleep(heartbeat_interval).await;
{
let status = status.read().await;
if matches!(
*status,
TransactionStatus::Rolledback
| TransactionStatus::Committed
| TransactionStatus::Dropped
) {
break;
}
}
let request = new_heart_beat_request(
start_ts.clone(),
primary_key.clone(),
start_instant.elapsed().as_millis() as u64 + MAX_TTL,
);
let plan = PlanBuilder::new(rpc.clone(), request)
.retry_multi_region(region_backoff.clone())
.merge(CollectSingle)
.plan();
plan.execute().await?;
}
Ok::<(), Error>(())
};
tokio::spawn(async {
if let Err(err) = heartbeat_task.await {
log::error!("Error: While sending heartbeat. {}", err);
}
});
}
}
impl<PdC: PdClient> Drop for Transaction<PdC> {
fn drop(&mut self) {
debug!(self.logger, "dropping transaction");
if std::thread::panicking() {
return;
}
let mut status = futures::executor::block_on(self.status.write());
if *status == TransactionStatus::Active {
match self.options.check_level {
CheckLevel::Panic => {
panic!("Dropping an active transaction. Consider commit or rollback it.")
}
CheckLevel::Warn => warn!(
self.logger,
"Dropping an active transaction. Consider commit or rollback it."
),
CheckLevel::None => {}
}
}
*status = TransactionStatus::Dropped;
}
}
/// The default max TTL of a lock in milliseconds. Also called `ManagedLockTTL` in TiDB.
const MAX_TTL: u64 = 20000;
/// The default TTL of a lock in milliseconds.
const DEFAULT_LOCK_TTL: u64 = 3000;
/// The default heartbeat interval
const DEFAULT_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(MAX_TTL / 2);
/// TiKV recommends each RPC packet should be less than around 1MB. We keep KV size of
/// each request below 16KB.
const TXN_COMMIT_BATCH_SIZE: u64 = 16 * 1024;
const TTL_FACTOR: f64 = 6000.0;
/// Optimistic or pessimistic transaction.
#[derive(Clone, PartialEq, Debug)]
pub enum TransactionKind {
Optimistic,
/// Argument is the transaction's for_update_ts
Pessimistic(Timestamp),
}
/// Options for configuring a transaction.
///
/// `TransactionOptions` has a builder-style API.
#[derive(Clone, PartialEq, Debug)]
pub struct TransactionOptions {
/// Optimistic or pessimistic (default) transaction.
kind: TransactionKind,
/// Try using 1pc rather than 2pc (default is to always use 2pc).
try_one_pc: bool,
/// Try to use async commit (default is not to).
async_commit: bool,
/// Is the transaction read only? (Default is no).
read_only: bool,
/// How to retry in the event of certain errors.
retry_options: RetryOptions,
/// What to do if the transaction is dropped without an attempt to commit or rollback
check_level: CheckLevel,
#[doc(hidden)]
heartbeat_option: HeartbeatOption,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum HeartbeatOption {
NoHeartbeat,
FixedTime(Duration),
}