| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | #![cfg_attr(not(debug_assertions), allow(dead_code))] |
| 22 | use crate::sync::ThreadLocal; |
| 23 | use crate::sync::{Mutex, MutexGuard}; |
| 24 | #[cfg(debug_assertions)] |
| 25 | use std::backtrace::Backtrace; |
| 26 | use std::fmt::{Debug, Display}; |
| 27 | use std::ops::{Deref, DerefMut}; |
| 28 | use std::panic::Location; |
| 29 | use std::sync::atomic::Ordering; |
| 30 | use std::sync::Arc; |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | #[derive(Debug)] |
| 44 | pub struct LoroMutex<T> { |
| 45 | lock: Mutex<T>, |
| 46 | kind: u8, |
| 47 | currently_locked_in_this_thread: Arc<ThreadLocal<Mutex<LockInfo>>>, |
| 48 | |
| 49 | |
| 50 | txn_gate: TxnGate, |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | #[derive(Debug)] |
| 58 | struct TxnGate { |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | active: std::sync::atomic::AtomicBool, |
| 64 | |
| 65 | |
| 66 | exclusive: Mutex<()>, |
| 67 | |
| 68 | owner: Mutex<Option<(crate::sync::thread::ThreadId, usize)>>, |
| 69 | } |
| 70 | |
| 71 | impl TxnGate { |
| 72 | fn new() -> Self { |
| 73 | Self { |
| 74 | active: std::sync::atomic::AtomicBool::new(false), |
| 75 | exclusive: Mutex::new(()), |
| 76 | owner: Mutex::new(None), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | fn owner(&self) -> MutexGuard<'_, Option<(crate::sync::thread::ThreadId, usize)>> { |
| 83 | self.owner.lock_ignoring_poison() |
| 84 | } |
| 85 | |
| 86 | fn wait_exclusive(&self) -> MutexGuard<'_, ()> { |
| 87 | self.exclusive.lock_ignoring_poison() |
| 88 | } |
| 89 | |
| 90 | fn is_owned_by_current_thread(&self) -> bool { |
| 91 | let me = crate::sync::thread::current().id(); |
| 92 | matches!(*self.owner(), Some((owner, _)) if owner == me) |
| 93 | } |
| 94 | |
| 95 | |
| 96 | |
| 97 | fn must_wait(&self) -> bool { |
| 98 | self.active.load(Ordering::SeqCst) && !self.is_owned_by_current_thread() |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | |
| 103 | pub(crate) struct TxnExclusiveGuard<'a> { |
| 104 | gate: &'a TxnGate, |
| 105 | |
| 106 | held: Option<MutexGuard<'a, ()>>, |
| 107 | } |
| 108 | |
| 109 | impl Drop for TxnExclusiveGuard<'_> { |
| 110 | fn drop(&mut self) { |
| 111 | let mut owner = self.gate.owner(); |
| 112 | if let Some((_, depth)) = owner.as_mut() { |
| 113 | *depth -= 1; |
| 114 | } |
| 115 | if self.held.is_some() { |
| 116 | debug_assert!(matches!(*owner, Some((_, 0)))); |
| 117 | *owner = None; |
| 118 | |
| 119 | |
| 120 | self.gate.active.store(false, Ordering::SeqCst); |
| 121 | } |
| 122 | drop(owner); |
| 123 | self.held.take(); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | |
| 128 | #[derive(Debug, Copy, Clone, Default)] |
| 129 | struct LockInfo { |
| 130 | kind: u8, |
| 131 | caller_location: Option<&'static Location<'static>>, |
| 132 | } |
| 133 | |
| 134 | impl Display for LockInfo { |
| 135 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 136 | match self.caller_location { |
| 137 | Some(location) => write!( |
| 138 | f, |
| 139 | "LockInfo(kind: {}, location: {}:{}:{})", |
| 140 | self.kind, |
| 141 | location.file(), |
| 142 | location.line(), |
| 143 | location.column() |
| 144 | ), |
| 145 | None => write!(f, "LockInfo(kind: {}, location: None)", self.kind), |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | #[derive(Debug)] |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | pub struct LoroLockGroup { |
| 159 | g: Arc<ThreadLocal<Mutex<LockInfo>>>, |
| 160 | } |
| 161 | |
| 162 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | pub enum LockKind { |
| 170 | None = 0, |
| 171 | Txn = 1, |
| 172 | OpLog = 2, |
| 173 | DocState = 3, |
| 174 | DiffCalculator = 4, |
| 175 | } |
| 176 | |
| 177 | impl LoroLockGroup { |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | pub fn new() -> Self { |
| 183 | let g = Arc::new(ThreadLocal::new()); |
| 184 | LoroLockGroup { g } |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | pub fn new_lock<T>(&self, value: T, kind: LockKind) -> LoroMutex<T> { |
| 191 | LoroMutex { |
| 192 | lock: Mutex::new(value), |
| 193 | currently_locked_in_this_thread: self.g.clone(), |
| 194 | kind: kind as u8, |
| 195 | txn_gate: TxnGate::new(), |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl Default for LoroLockGroup { |
| 201 | fn default() -> Self { |
| 202 | Self::new() |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | impl<T> LoroMutex<T> { |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | pub(crate) fn lock_exclusive(&self) -> TxnExclusiveGuard<'_> { |
| 215 | debug_assert_eq!(self.kind, LockKind::Txn as u8); |
| 216 | let gate = &self.txn_gate; |
| 217 | let me = crate::sync::thread::current().id(); |
| 218 | { |
| 219 | let mut owner = gate.owner(); |
| 220 | if let Some((id, depth)) = owner.as_mut() { |
| 221 | if *id == me { |
| 222 | *depth += 1; |
| 223 | return TxnExclusiveGuard { gate, held: None }; |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | let held = gate.wait_exclusive(); |
| 228 | *gate.owner() = Some((me, 1)); |
| 229 | gate.active.store(true, Ordering::SeqCst); |
| 230 | TxnExclusiveGuard { |
| 231 | gate, |
| 232 | held: Some(held), |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | |
| 237 | |
| 238 | #[inline] |
| 239 | fn acquire(&self) -> MutexGuard<'_, T> { |
| 240 | let guard = self.lock.lock_with_kind("LoroMutex"); |
| 241 | if self.kind != LockKind::Txn as u8 || !self.txn_gate.must_wait() { |
| 242 | return guard; |
| 243 | } |
| 244 | self.acquire_after_exclusive(guard) |
| 245 | } |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | #[cold] |
| 252 | fn acquire_after_exclusive<'a>(&'a self, mut guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> { |
| 253 | while self.txn_gate.must_wait() { |
| 254 | drop(guard); |
| 255 | drop(self.txn_gate.wait_exclusive()); |
| 256 | guard = self.lock.lock_with_kind("LoroMutex"); |
| 257 | } |
| 258 | guard |
| 259 | } |
| 260 | |
| 261 | #[track_caller] |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | pub fn lock(&self) -> LoroMutexGuard<'_, T> { |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | #[cfg(debug_assertions)] |
| 279 | { |
| 280 | let caller = Location::caller(); |
| 281 | let v = self.currently_locked_in_this_thread.get_or_default(); |
| 282 | let last = *v.lock(); |
| 283 | let this = LockInfo { |
| 284 | kind: self.kind, |
| 285 | caller_location: Some(caller), |
| 286 | }; |
| 287 | if last.kind >= self.kind { |
| 288 | panic!( |
| 289 | "Locking order violation. Current lock: {}, New lock: {}", |
| 290 | last, this |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | let guard = self.acquire(); |
| 295 | *v.lock() = this; |
| 296 | LoroMutexGuard { |
| 297 | guard, |
| 298 | _inner: LoroMutexGuardInner { |
| 299 | inner: self, |
| 300 | this, |
| 301 | last, |
| 302 | }, |
| 303 | } |
| 304 | } |
| 305 | #[cfg(not(debug_assertions))] |
| 306 | { |
| 307 | let guard = self.acquire(); |
| 308 | LoroMutexGuard { |
| 309 | guard, |
| 310 | _inner: LoroMutexGuardInner { inner: self }, |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | pub fn is_locked(&self) -> bool { |
| 321 | self.lock.is_locked() |
| 322 | } |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | pub(crate) fn can_lock_in_this_thread(&self) -> bool { |
| 330 | #[cfg(debug_assertions)] |
| 331 | { |
| 332 | let v = self.currently_locked_in_this_thread.get_or_default(); |
| 333 | let last = *v.lock(); |
| 334 | last.kind < self.kind |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | #[cfg(not(debug_assertions))] |
| 341 | { |
| 342 | false |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | pub struct LoroMutexGuard<'a, T> { |
| 353 | guard: MutexGuard<'a, T>, |
| 354 | _inner: LoroMutexGuardInner<'a, T>, |
| 355 | } |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | struct LoroMutexGuardInner<'a, T> { |
| 362 | #[cfg_attr(not(debug_assertions), allow(dead_code))] |
| 363 | inner: &'a LoroMutex<T>, |
| 364 | #[cfg(debug_assertions)] |
| 365 | this: LockInfo, |
| 366 | #[cfg(debug_assertions)] |
| 367 | last: LockInfo, |
| 368 | } |
| 369 | |
| 370 | impl<T> Deref for LoroMutexGuard<'_, T> { |
| 371 | type Target = T; |
| 372 | |
| 373 | fn deref(&self) -> &Self::Target { |
| 374 | &self.guard |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | impl<T> DerefMut for LoroMutexGuard<'_, T> { |
| 379 | fn deref_mut(&mut self) -> &mut T { |
| 380 | &mut self.guard |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | impl<T: Debug> std::fmt::Debug for LoroMutexGuard<'_, T> { |
| 385 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 386 | f.debug_struct("LoroMutex") |
| 387 | .field("data", &self.guard) |
| 388 | .finish() |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | impl<'a, T> LoroMutexGuard<'a, T> { |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | pub fn take_guard(self) -> MutexGuard<'a, T> { |
| 404 | self.guard |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | impl<T> Drop for LoroMutexGuardInner<'_, T> { |
| 409 | #[cfg(not(debug_assertions))] |
| 410 | fn drop(&mut self) {} |
| 411 | |
| 412 | #[cfg(debug_assertions)] |
| 413 | fn drop(&mut self) { |
| 414 | let cur = self.inner.currently_locked_in_this_thread.get_or_default(); |
| 415 | let current_lock_info = *cur.lock(); |
| 416 | if current_lock_info.kind != self.this.kind { |
| 417 | let bt = Backtrace::capture(); |
| 418 | eprintln!("Locking release order violation callstack:\n{}", bt); |
| 419 | panic!( |
| 420 | "Locking release order violation. self.this: {}, self.last: {}, current: {}", |
| 421 | self.this, self.last, current_lock_info |
| 422 | ); |
| 423 | } |
| 424 | |
| 425 | *cur.lock() = self.last; |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | |
| 430 | |
| 431 | #[cfg(all(test, debug_assertions))] |
| 432 | mod tests { |
| 433 | use super::*; |
| 434 | |
| 435 | #[test] |
| 436 | #[should_panic(expected = "Locking order violation")] |
| 437 | fn test_locking_order_violation_shows_caller() { |
| 438 | let group = LoroLockGroup::new(); |
| 439 | let mutex1 = group.new_lock(1, LockKind::DocState); |
| 440 | let mutex2 = group.new_lock(2, LockKind::Txn); |
| 441 | |
| 442 | let _guard1 = mutex1.lock(); |
| 443 | let _guard2 = mutex2.lock(); |
| 444 | } |
| 445 | |
| 446 | #[test] |
| 447 | fn test_locking_order_when_dropped_in_order() { |
| 448 | let group = LoroLockGroup::new(); |
| 449 | let mutex1 = group.new_lock(1, LockKind::Txn); |
| 450 | let mutex2 = group.new_lock(2, LockKind::OpLog); |
| 451 | let mutex3 = group.new_lock(3, LockKind::DocState); |
| 452 | let _guard1 = mutex1.lock(); |
| 453 | drop(_guard1); |
| 454 | let _guard2 = mutex2.lock(); |
| 455 | drop(_guard2); |
| 456 | let _guard3 = mutex3.lock(); |
| 457 | } |
| 458 | |
| 459 | #[test] |
| 460 | #[should_panic] |
| 461 | fn test_locking_order_when_not_dropped_in_reverse_order() { |
| 462 | let group = LoroLockGroup::new(); |
| 463 | let mutex1 = group.new_lock(1, LockKind::Txn); |
| 464 | let mutex2 = group.new_lock(2, LockKind::OpLog); |
| 465 | let _guard1 = mutex1.lock(); |
| 466 | let _guard2 = mutex2.lock(); |
| 467 | drop(_guard1); |
| 468 | drop(_guard2); |
| 469 | } |
| 470 | |
| 471 | #[test] |
| 472 | fn test_dropping_should_restore_last_lock_info_0() { |
| 473 | let group = LoroLockGroup::new(); |
| 474 | let mutex1 = group.new_lock(1, LockKind::Txn); |
| 475 | let mutex2 = group.new_lock(2, LockKind::OpLog); |
| 476 | let mutex3 = group.new_lock(3, LockKind::DocState); |
| 477 | let _guard1 = mutex1.lock(); |
| 478 | let _guard3 = mutex3.lock(); |
| 479 | drop(_guard3); |
| 480 | let _guard2 = mutex2.lock(); |
| 481 | drop(_guard2); |
| 482 | } |
| 483 | |
| 484 | #[test] |
| 485 | #[should_panic] |
| 486 | fn test_dropping_should_restore_last_lock_info_1() { |
| 487 | let group = LoroLockGroup::new(); |
| 488 | let mutex1 = group.new_lock(1, LockKind::Txn); |
| 489 | let mutex2 = group.new_lock(2, LockKind::OpLog); |
| 490 | let mutex3 = group.new_lock(3, LockKind::DocState); |
| 491 | let _guard2 = mutex2.lock(); |
| 492 | let _guard3 = mutex3.lock(); |
| 493 | drop(_guard3); |
| 494 | let _guard1 = mutex1.lock(); |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn test_nested_locking_same_kind() { |
| 499 | let group = LoroLockGroup::new(); |
| 500 | let mutex1 = group.new_lock(1, LockKind::Txn); |
| 501 | let mutex2 = group.new_lock(2, LockKind::Txn); |
| 502 | |
| 503 | let guard1 = mutex1.lock(); |
| 504 | |
| 505 | |
| 506 | drop(guard1); |
| 507 | |
| 508 | let _guard2 = mutex2.lock(); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn test_lock_kind_enum_values() { |
| 513 | assert_eq!(LockKind::None as u8, 0); |
| 514 | assert_eq!(LockKind::Txn as u8, 1); |
| 515 | assert_eq!(LockKind::OpLog as u8, 2); |
| 516 | assert_eq!(LockKind::DocState as u8, 3); |
| 517 | assert_eq!(LockKind::DiffCalculator as u8, 4); |
| 518 | } |
| 519 | |
| 520 | #[test] |
| 521 | fn test_is_locked_functionality() { |
| 522 | let group = LoroLockGroup::new(); |
| 523 | let mutex = group.new_lock(42, LockKind::Txn); |
| 524 | |
| 525 | assert!(!mutex.is_locked()); |
| 526 | |
| 527 | let _guard = mutex.lock(); |
| 528 | assert!(mutex.is_locked()); |
| 529 | } |
| 530 | |
| 531 | |
| 532 | #[test] |
| 533 | #[should_panic(expected = "Locking order violation")] |
| 534 | fn test_panic_message_contains_location_info() { |
| 535 | let group = LoroLockGroup::new(); |
| 536 | let mutex1 = group.new_lock(1, LockKind::DocState); |
| 537 | let mutex2 = group.new_lock(2, LockKind::Txn); |
| 538 | |
| 539 | let _guard1 = mutex1.lock(); |
| 540 | |
| 541 | |
| 542 | let _guard2 = mutex2.lock(); |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | #[should_panic(expected = "poisoned LoroMutex")] |
| 547 | fn test_poisoned_lock_panics_after_unwind() { |
| 548 | let group = LoroLockGroup::new(); |
| 549 | let mutex = group.new_lock(42, LockKind::Txn); |
| 550 | |
| 551 | let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 552 | let _guard = mutex.lock(); |
| 553 | panic!("poison the lock"); |
| 554 | })); |
| 555 | |
| 556 | let _ = mutex.lock(); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | #[cfg(all(test, not(loom)))] |
| 561 | mod txn_gate_tests { |
| 562 | use super::*; |
| 563 | use std::sync::mpsc; |
| 564 | use std::time::Duration; |
| 565 | |
| 566 | #[test] |
| 567 | fn owner_thread_nests_and_writes_without_blocking() { |
| 568 | let group = LoroLockGroup::new(); |
| 569 | let txn = group.new_lock(0, LockKind::Txn); |
| 570 | let outer = txn.lock_exclusive(); |
| 571 | { |
| 572 | let _inner = txn.lock_exclusive(); |
| 573 | *txn.lock() += 1; |
| 574 | } |
| 575 | |
| 576 | assert!(txn.txn_gate.active.load(Ordering::SeqCst)); |
| 577 | *txn.lock() += 1; |
| 578 | drop(outer); |
| 579 | assert!(!txn.txn_gate.active.load(Ordering::SeqCst)); |
| 580 | assert_eq!(*txn.lock(), 2); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn other_writers_wait_for_the_compound_operation() { |
| 585 | let group = LoroLockGroup::new(); |
| 586 | let txn = Arc::new(group.new_lock(Vec::new(), LockKind::Txn)); |
| 587 | let exclusive = txn.lock_exclusive(); |
| 588 | txn.lock().push("owner-1"); |
| 589 | let (done, finished) = mpsc::channel(); |
| 590 | let writer = { |
| 591 | let txn = txn.clone(); |
| 592 | std::thread::spawn(move || { |
| 593 | txn.lock().push("writer"); |
| 594 | done.send(()).unwrap(); |
| 595 | }) |
| 596 | }; |
| 597 | |
| 598 | assert!(finished.recv_timeout(Duration::from_millis(100)).is_err()); |
| 599 | txn.lock().push("owner-2"); |
| 600 | drop(exclusive); |
| 601 | finished.recv_timeout(Duration::from_secs(10)).unwrap(); |
| 602 | writer.join().unwrap(); |
| 603 | assert_eq!(*txn.lock(), vec!["owner-1", "owner-2", "writer"]); |
| 604 | } |
| 605 | |
| 606 | #[test] |
| 607 | fn a_panic_inside_the_compound_operation_does_not_block_later_writers() { |
| 608 | let group = LoroLockGroup::new(); |
| 609 | let txn = Arc::new(group.new_lock(0, LockKind::Txn)); |
| 610 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 611 | let _exclusive = txn.lock_exclusive(); |
| 612 | panic!("undo failed"); |
| 613 | })); |
| 614 | assert!(result.is_err()); |
| 615 | assert!(!txn.txn_gate.active.load(Ordering::SeqCst)); |
| 616 | let other = { |
| 617 | let txn = txn.clone(); |
| 618 | std::thread::spawn(move || { |
| 619 | *txn.lock() += 1; |
| 620 | drop(txn.lock_exclusive()); |
| 621 | }) |
| 622 | }; |
| 623 | other.join().unwrap(); |
| 624 | drop(txn.lock_exclusive()); |
| 625 | assert_eq!(*txn.lock(), 1); |
| 626 | } |
| 627 | } |