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
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use log::{debug, trace};
use tokio::sync::broadcast::{self, Sender};
use tokio::sync::{OwnedRwLockReadGuard, OwnedRwLockWriteGuard, RwLock};
use tc_error::*;
use crate::{Transact, TxnId, MIN_ID};
#[derive(Copy, Clone)]
struct Wake;
pub struct TxnLockReadGuard<T: Clone + PartialEq> {
lock: TxnLock<T>,
txn_id: TxnId,
guard: OwnedRwLockReadGuard<T>,
}
impl<T: Clone + PartialEq> Clone for TxnLockReadGuard<T> {
fn clone(&self) -> Self {
trace!("TxnLockReadGuard::clone {}", self.lock.inner.name);
let mut lock_state = self
.lock
.inner
.state
.lock()
.expect("TxnLockReadGuard::clone");
let num_readers = lock_state
.readers
.get_mut(&self.txn_id)
.expect("read lock count");
*num_readers += 1;
let guard = lock_state
.versions
.get(self.txn_id)
.try_read_owned()
.expect("transaction version read guard");
Self {
lock: self.lock.clone(),
txn_id: self.txn_id,
guard,
}
}
}
impl<T: Clone + PartialEq> Deref for TxnLockReadGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.deref()
}
}
impl<T: Clone + PartialEq> Drop for TxnLockReadGuard<T> {
fn drop(&mut self) {
trace!("TxnLockReadGuard::drop {}", self.lock.inner.name);
let num_readers = {
let mut lock_state = self
.lock
.inner
.state
.lock()
.expect("TxnLockReadGuard::drop");
lock_state.drop_read(&self.txn_id, false)
};
if num_readers == 0 {
self.lock.wake();
}
}
}
pub struct TxnLockReadGuardExclusive<T: Clone + PartialEq> {
lock: TxnLock<T>,
txn_id: TxnId,
guard: OwnedRwLockWriteGuard<T>,
pending_upgrade: bool,
}
impl<T: Clone + PartialEq> TxnLockReadGuardExclusive<T> {
pub fn upgrade(mut self) -> TxnLockWriteGuard<T> {
let lock = self.lock.clone();
let txn_id = self.txn_id;
self.pending_upgrade = true;
std::mem::drop(self);
lock.try_write(txn_id).expect("upgrade exclusive read lock")
}
}
impl<T: Clone + PartialEq> Deref for TxnLockReadGuardExclusive<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.guard
}
}
impl<T: Clone + PartialEq> Drop for TxnLockReadGuardExclusive<T> {
fn drop(&mut self) {
trace!("TxnLockReadGuardExclusive::drop {}", self.lock.inner.name);
let num_readers = {
let mut lock_state = self
.lock
.inner
.state
.lock()
.expect("TxnLockReadGuardExclusive::drop");
lock_state.drop_read(&self.txn_id, true)
};
if self.pending_upgrade {
trace!("TxnLockReadGuardExclusive::drop pending upgrade, not waking subscribers...");
} else if num_readers == 0 {
trace!("TxnLockReadGuardExclusive::drop waking subscribers...");
self.lock.wake();
}
}
}
pub struct TxnLockWriteGuard<T: Clone + PartialEq> {
lock: TxnLock<T>,
txn_id: TxnId,
guard: OwnedRwLockWriteGuard<T>,
pending_downgrade: bool,
}
impl<T: Clone + PartialEq> TxnLockWriteGuard<T> {
fn new(lock: TxnLock<T>, txn_id: TxnId, guard: OwnedRwLockWriteGuard<T>) -> Self {
Self {
lock,
txn_id,
guard,
pending_downgrade: false,
}
}
pub fn downgrade(mut self) -> TxnLockReadGuardExclusive<T> {
let lock = self.lock.clone();
let txn_id = self.txn_id;
self.pending_downgrade = true;
std::mem::drop(self);
lock.try_read_exclusive(txn_id)
.expect("downgrade write lock")
}
}
impl<T: Clone + PartialEq> Deref for TxnLockWriteGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.deref()
}
}
impl<T: Clone + PartialEq> DerefMut for TxnLockWriteGuard<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard.deref_mut()
}
}
impl<T: Clone + PartialEq> Drop for TxnLockWriteGuard<T> {
fn drop(&mut self) {
trace!("TxnLockWriteGuard::drop {}", self.lock.inner.name);
{
let mut lock_state = self
.lock
.inner
.state
.lock()
.expect("TxnLockWriteGuard::drop");
if let Some(readers) = lock_state.readers.get(&self.txn_id) {
assert_eq!(readers, &0);
}
lock_state.writer = None;
}
if !self.pending_downgrade {
self.lock.wake();
}
}
}
struct Versions<T> {
canon: T,
versions: HashMap<TxnId, Arc<RwLock<T>>>,
}
impl<T: Clone + PartialEq<T>> Versions<T> {
fn commit(&mut self, txn_id: &TxnId) -> bool {
if let Some(version) = self.versions.get(txn_id) {
let version = version.try_read().expect("transaction version");
if version.deref() == &self.canon {
false
} else {
self.canon = version.clone();
true
}
} else {
let canon = self.canon.clone();
self.versions.insert(*txn_id, Arc::new(RwLock::new(canon)));
false
}
}
fn finalize(&mut self, txn_id: &TxnId) {
self.versions.remove(txn_id);
}
fn get(self: &mut Versions<T>, txn_id: TxnId) -> Arc<RwLock<T>> {
if let Some(version) = self.versions.get(&txn_id) {
version.clone()
} else {
let version = self.canon.clone();
let version = Arc::new(RwLock::new(version));
self.versions.insert(txn_id, version.clone());
version
}
}
}
struct LockState<T> {
versions: Versions<T>,
readers: BTreeMap<TxnId, usize>,
exclusive: BTreeSet<TxnId>,
writer: Option<TxnId>,
pending_writes: BTreeSet<TxnId>,
last_commit: TxnId,
}
impl<T: Clone + PartialEq> LockState<T> {
fn drop_read(&mut self, txn_id: &TxnId, exclusive: bool) -> usize {
if let Some(writer) = &self.writer {
assert_ne!(writer, txn_id);
}
let num_readers = self.readers.get_mut(txn_id).expect("read lock count");
*num_readers -= 1;
trace!(
"txn lock has {} readers remaining after dropping one read guard",
num_readers
);
if exclusive {
assert_eq!(*num_readers, 0);
self.exclusive.remove(txn_id);
}
*num_readers
}
fn try_read(&mut self, txn_id: &TxnId, exclusive: bool) -> TCResult<Option<Arc<RwLock<T>>>> {
if self.exclusive.contains(txn_id) {
debug!("TxnLock is locked exclusively for reading");
return Ok(None);
}
for reserved in self.pending_writes.iter().rev() {
debug_assert!(reserved <= &txn_id);
if reserved > &self.last_commit && reserved < &txn_id {
debug!("TxnLock waiting on a pending write at {}", reserved);
return Ok(None);
}
}
if self.writer.as_ref() == Some(txn_id) {
debug!("TxnLock waiting on a write lock at {}", txn_id);
return Ok(None);
}
if !self.versions.versions.contains_key(&txn_id) {
if txn_id <= &self.last_commit {
return Err(TCError::conflict(format!(
"transaction {} is already finalized, can't acquire read lock",
txn_id
)));
}
}
let num_readers = self.readers.entry(*txn_id).or_insert(0);
if exclusive {
if *num_readers == 0 {
self.exclusive.insert(*txn_id);
} else {
trace!("TxnLock is locked non-exclusively for reading");
return Ok(None);
}
}
*num_readers += 1;
Ok(Some(self.versions.get(*txn_id).clone()))
}
fn try_write(&mut self, txn_id: &TxnId) -> TCResult<Option<Arc<RwLock<T>>>> {
if &self.last_commit >= txn_id {
return Err(TCError::conflict(format!(
"can't acquire write lock at {} because of a commit at {}",
txn_id, self.last_commit
)));
}
if let Some(reader) = self.readers.keys().max() {
if reader > &txn_id {
return Err(TCError::conflict(format!(
"can't acquire write lock at {} since it already has a read lock at {}",
txn_id, reader
)));
}
}
for pending in self.pending_writes.iter().rev() {
if pending > &txn_id {
return Err(TCError::conflict(format!(
"can't write at {} since there's already a lock at {}",
txn_id, pending
)));
} else if pending > &self.last_commit && pending < &txn_id {
debug!(
"can't acquire write lock due to a pending write at {}",
pending
);
return Ok(None);
}
}
if let Some(writer) = &self.writer {
assert!(writer <= txn_id);
debug!("TxnLock has an active write lock at {}", writer);
return Ok(None);
} else if let Some(readers) = self.readers.get(&txn_id) {
if readers > &0 {
debug!("TxnLock has {} active readers at {}", readers, txn_id);
return Ok(None);
}
}
self.writer = Some(*txn_id);
self.pending_writes.insert(*txn_id);
Ok(Some(self.versions.get(*txn_id).clone()))
}
}
impl<T: Clone + Eq> LockState<T> {
fn commit(&mut self, txn_id: &TxnId) {
if self.versions.commit(txn_id) {
self.last_commit = *txn_id;
}
self.pending_writes.remove(txn_id);
}
fn finalize(&mut self, txn_id: &TxnId) {
self.versions.finalize(txn_id);
self.pending_writes.remove(txn_id);
}
}
struct Inner<T> {
name: String,
state: Mutex<LockState<T>>,
tx: Sender<Wake>,
}
#[derive(Clone)]
pub struct TxnLock<T> {
inner: Arc<Inner<T>>,
}
impl<T> TxnLock<T> {
pub fn new<I: fmt::Display>(name: I, canon: T) -> Self {
let (tx, _) = broadcast::channel(16);
let versions = Versions {
canon,
versions: HashMap::new(),
};
let state = LockState {
versions,
readers: BTreeMap::new(),
exclusive: BTreeSet::new(),
writer: None,
pending_writes: BTreeSet::new(),
last_commit: MIN_ID,
};
Self {
inner: Arc::new(Inner {
name: name.to_string(),
state: Mutex::new(state),
tx,
}),
}
}
fn wake(&self) -> usize {
trace!(
"TxnLock {} waking {} subscribers",
self.inner.name,
self.inner.tx.receiver_count()
);
match self.inner.tx.send(Wake) {
Err(broadcast::error::SendError(_)) => 0,
Ok(num_subscribed) => {
trace!(
"TxnLock {} woke {} subscribers",
self.inner.name,
num_subscribed
);
num_subscribed
}
}
}
}
impl<T: Clone + PartialEq> TxnLock<T> {
pub async fn read(&self, txn_id: TxnId) -> TCResult<TxnLockReadGuard<T>> {
debug!("lock {} to read at {}...", self.inner.name, txn_id);
let version = {
let mut rx = self.inner.tx.subscribe();
loop {
{
let mut lock_state = self.inner.state.lock().expect("TxnLock::await_readable");
if let Some(version) = lock_state.try_read(&txn_id, false)? {
break version;
}
}
if let Err(cause) = rx.recv().await {
debug!("TxnLock wake error: {}", cause);
}
}
};
let guard = version.read_owned().await;
let guard = TxnLockReadGuard {
lock: self.clone(),
txn_id,
guard,
};
debug!("locked {} for reading at {}", self.inner.name, txn_id);
Ok(guard)
}
pub async fn read_exclusive(&self, txn_id: TxnId) -> TCResult<TxnLockReadGuardExclusive<T>> {
debug!(
"lock {} exclusively to read at {}...",
self.inner.name, txn_id
);
let version = {
let mut rx = self.inner.tx.subscribe();
loop {
{
let mut lock_state = self.inner.state.lock().expect("TxnLock::await_readable");
if let Some(version) = lock_state.try_read(&txn_id, true)? {
break version;
}
}
if let Err(cause) = rx.recv().await {
debug!("TxnLock wake error: {}", cause);
}
}
};
let guard = version.write_owned().await;
let guard = TxnLockReadGuardExclusive {
lock: self.clone(),
txn_id,
guard,
pending_upgrade: false,
};
debug!("locked {} for reading at {}", self.inner.name, txn_id);
Ok(guard)
}
pub fn try_read_exclusive(&self, txn_id: TxnId) -> TCResult<TxnLockReadGuardExclusive<T>> {
debug!(
"try to lock {} exclusively to read at {}...",
self.inner.name, txn_id
);
const ERR: &str = "could not acquire transactional exclusive-read lock";
let version = {
let mut lock_state = self.inner.state.lock().expect("TxnLock::await_readable");
if let Some(version) = lock_state.try_read(&txn_id, true)? {
Ok(version)
} else {
Err(TCError::conflict(ERR))
}
}?;
let guard = version
.try_write_owned()
.map_err(|cause| TCError::conflict(format!("{}: {}", ERR, cause)))?;
let guard = TxnLockReadGuardExclusive {
lock: self.clone(),
txn_id,
guard,
pending_upgrade: false,
};
debug!("locked {} for reading at {}", self.inner.name, txn_id);
Ok(guard)
}
pub fn try_write(&self, txn_id: TxnId) -> TCResult<TxnLockWriteGuard<T>> {
const ERR: &str = "could not acquire transactional read lock";
let version = {
let mut lock_state = self.inner.state.lock().expect("TxnLock::await_readable");
if let Some(version) = lock_state.try_write(&txn_id)? {
version
} else {
return Err(TCError::conflict(ERR));
}
};
let guard = version
.try_write_owned()
.map_err(|cause| TCError::conflict(format!("{}: {}", ERR, cause)))?;
Ok(TxnLockWriteGuard::new(self.clone(), txn_id, guard))
}
pub async fn write(&self, txn_id: TxnId) -> TCResult<TxnLockWriteGuard<T>> {
debug!("locking {} for writing at {}...", self.inner.name, txn_id);
let version = {
let mut rx = self.inner.tx.subscribe();
loop {
{
let mut lock_state = self.inner.state.lock().expect("TxnLock::await_writable");
if let Some(version) = lock_state.try_write(&txn_id)? {
break version;
};
}
if let Err(cause) = rx.recv().await {
debug!("TxnLock wake error: {}", cause);
}
}
};
let guard = version.write_owned().await;
let guard = TxnLockWriteGuard::new(self.clone(), txn_id, guard);
debug!("locked {} for writing at {}", self.inner.name, txn_id);
Ok(guard)
}
}
#[async_trait]
impl<T: Eq + Clone + Send + Sync> Transact for TxnLock<T> {
async fn commit(&self, txn_id: &TxnId) {
debug!("TxnLock::commit {} at {}", self.inner.name, txn_id);
{
let mut lock_state = self.inner.state.lock().expect("TxnLock::commit");
lock_state.commit(txn_id);
}
self.wake();
}
async fn finalize(&self, txn_id: &TxnId) {
debug!("finalize {} at {}", self.inner.name, txn_id);
{
let mut lock_state = self.inner.state.lock().expect("TxnLock::finalize");
lock_state.finalize(txn_id);
}
self.wake();
}
}