-
Notifications
You must be signed in to change notification settings - Fork 486
Expand file tree
/
Copy pathconnection_manager.rs
More file actions
558 lines (515 loc) · 21.8 KB
/
connection_manager.rs
File metadata and controls
558 lines (515 loc) · 21.8 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
use std::ops::Deref;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crossbeam::deque::Steal;
use crossbeam::sync::{Parker, Unparker};
use hashbrown::HashMap;
use libsql_sys::wal::wrapper::{WrapWal, WrappedWal};
use libsql_sys::wal::{CheckpointMode, Sqlite3Wal, Sqlite3WalManager, Wal};
use metrics::atomics::AtomicU64;
use parking_lot::{Mutex, MutexGuard};
use rusqlite::ErrorCode;
use super::connection_core::CoreConnection;
use super::TXN_TIMEOUT;
pub type ConnId = u64;
pub type InnerWalManager = Sqlite3WalManager;
pub type InnerWal = Sqlite3Wal;
pub type ManagedConnectionWal = WrappedWal<ManagedConnectionWalWrapper, InnerWal>;
#[derive(Copy, Clone, Debug)]
struct Slot {
id: ConnId,
started_at: Instant,
state: SlotState,
}
#[derive(Clone)]
struct Abort(Arc<dyn Fn() + Send + Sync + 'static>);
impl Abort {
fn from_conn<T: Wal + Send + 'static>(conn: &Arc<Mutex<CoreConnection<T>>>) -> Self {
let conn = Arc::downgrade(conn);
Self(Arc::new(move || {
conn.upgrade()
.expect("connection still owns the slot, so it must exist")
.lock()
.force_rollback();
}))
}
fn abort(&self) {
(self.0)()
}
}
#[derive(Clone)]
pub struct ConnectionManager {
inner: Arc<ConnectionManagerInner>,
}
impl ConnectionManager {
pub(super) fn register_connection<T: Wal + Send + Send + 'static>(
&self,
conn: &Arc<Mutex<CoreConnection<T>>>,
id: ConnId,
) {
let abort = Abort::from_conn(conn);
self.inner.abort_handle.lock().insert(id, abort);
}
}
impl Deref for ConnectionManager {
type Target = ConnectionManagerInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ConnectionManager {
pub fn new(txn_timeout_duration: Duration) -> ConnectionManager {
Self {
inner: Arc::new(ConnectionManagerInner {
txn_timeout_duration,
..Default::default()
}),
}
}
}
pub struct ConnectionManagerInner {
/// When a slot becomes available, the connection allowed to make progress is put here
/// the connection currently holding the lock
/// bool: acquired
current: Mutex<Option<Slot>>,
/// map of registered connections
abort_handle: Mutex<HashMap<ConnId, Abort>>,
/// threads waiting to acquire the lock
/// todo: limit how many can be push
write_queue: crossbeam::deque::Injector<(ConnId, Unparker)>,
txn_timeout_duration: Duration,
/// the time we are given to acquire a transaction after we were given a slot
acquire_timeout_duration: Duration,
next_conn_id: AtomicU64,
sync_token: AtomicU64,
}
impl Default for ConnectionManagerInner {
fn default() -> Self {
Self {
current: Default::default(),
abort_handle: Default::default(),
write_queue: Default::default(),
txn_timeout_duration: TXN_TIMEOUT,
acquire_timeout_duration: Duration::from_millis(15),
next_conn_id: Default::default(),
sync_token: AtomicU64::new(0),
}
}
}
#[derive(Clone)]
pub struct ManagedConnectionWalWrapper {
id: ConnId,
manager: ConnectionManager,
}
impl ManagedConnectionWalWrapper {
pub(crate) fn new(manager: ConnectionManager) -> Self {
let id = manager.inner.next_conn_id.fetch_add(1, Ordering::SeqCst);
Self { id, manager }
}
pub fn id(&self) -> ConnId {
self.id
}
fn acquire(&self) -> libsql_sys::wal::Result<()> {
let parker = Parker::new();
let mut enqueued = false;
let enqueued_at = Instant::now();
let sync_token = self.manager.sync_token.load(Ordering::SeqCst);
loop {
let mut current = self.manager.current.lock();
// if current is not currently us, and we havent enqueued yet, then enqueue
// current can be us in two cases:
// - in previous iteration, the queue was empty, and we popped ourselves
// - we tried to acquire the lock during the previous iteration, but the underlying
// method returned an error and we had to retry immediately, by re-entering this
// function.
if self.manager.sync_token.load(Ordering::SeqCst) != sync_token {
return Err(rusqlite::ffi::Error {
code: ErrorCode::DatabaseBusy,
extended_code: 517, // stale read
});
}
// If other connection is about to checkpoint - we better to immediately return.
//
// The reason is that write transaction are upgraded from read transactions in SQLite.
// Due to this, every write transaction need to hold SHARED-WAL lock and if we will
// block write transaction here - we will prevent checkpoint process from restarting the WAL
// (because it needs to acquire EXCLUSIVE-WAL lock)
//
// So, the scenario is following:
// T0: we have a bunch of SELECT queries which will execute till time T2
// T1: CHECKPOINT process is starting: it holds CKPT and WRITE lock and attempt to acquire
// EXCLUSIVE-WAL locks one by one in order to check the position of readers. CHECKPOINT will
// use busy handler and can potentially acquire lock not from the first attempt.
// T2: CHECKPOINT process were able to check all WAL reader positions (by acquiring lock or atomically check reader position)
// and started to transfer WAL to the DB file
// T3: INSERT query starts executing: it started as a read transaction and holded SHARED-WAL lock but then it needs to
// upgrade to write transaction through begin_write_txn call
// T4: CHECKPOINT transferred all pages from WAL to DB file and need to check if it can restart the WAL. In order to
// do that it needs to hold all EXCLUSIVE-WAL locks to make sure that all readers use only DB file
//
// In the scenario above, if we will park INSERT at the time T3 - CHECKPOINT will be unable to hold EXCLUSIVE-WAL
// locks and so WAL will not be truncated.
// In case when DB has continious load with overlapping reads and writes - this problem became very noticeable
// as it can defer WAL truncation a lot.
//
// Also, such implementation is more aligned with LibSQL/SQLite behaviour where sqlite3WalBeginWriteTransaction
// immediately abort with SQLITE_BUSY error if it can't acquire WRITE lock (which CHECKPOINT also take before start of the work)
// and busy handler (e.g. retries) for writes are invoked by SQLite at upper layer of request processing.
match *current {
Some(Slot {
id,
state: SlotState::Acquired(SlotType::Checkpoint),
..
}) if id != self.id => {
return Err(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_BUSY));
}
_ => {}
}
// note, that it's important that we return SQLITE_BUSY error for CHECKPOINT starvation problem before that condition
// because after we will add something to the write_queue - we can't easily abort execution of acquire() method
if current.as_mut().map_or(true, |slot| slot.id != self.id) && !enqueued {
self.manager
.write_queue
.push((self.id, parker.unparker().clone()));
enqueued = true;
tracing::debug!("enqueued");
}
match *current {
Some(ref mut slot) => {
tracing::debug!("current slot: {slot:?}");
// this is us, the previous connection put us here when it closed the
// transaction
if slot.id == self.id {
assert!(
slot.state.is_notified() || slot.state.is_failure(),
"{slot:?}"
);
slot.state = SlotState::Acquiring;
tracing::debug!(
line = line!(),
"got lock after: {:?}",
enqueued_at.elapsed()
);
break;
} else {
// not us, maybe we need to steal the lock?
let since_started = slot.started_at.elapsed();
let deadline = slot.started_at + self.manager.txn_timeout_duration;
match slot.state {
SlotState::Acquired(..) => {
if since_started >= self.manager.txn_timeout_duration {
let id = slot.id;
drop(current);
let handle = {
self.manager
.inner
.abort_handle
.lock()
.get(&id)
.unwrap()
.clone()
};
// the guard must be dropped before rolling back, or end write txn will
// deadlock
tracing::debug!("forcing rollback of {id}");
handle.abort();
tracing::debug!(line = line!(), "parking");
parker.park();
tracing::debug!(line = line!(), "unparked");
} else {
// otherwise we wait for the txn to timeout, or to be unparked by it
let deadline =
slot.started_at + self.manager.inner.txn_timeout_duration;
drop(current);
tracing::debug!(line = line!(), "parking");
parker.park_deadline(deadline);
tracing::debug!(
line = line!(),
"before_deadline?: {:?}",
Instant::now() < deadline
);
}
}
// we may want to limit how long a lock takes to go from notified
// to acquiring
SlotState::Acquiring | SlotState::Notified => {
drop(current);
tracing::debug!(line = line!(), "parking");
parker.park_deadline(deadline);
tracing::debug!(
line = line!(),
"unparked after before_deadline?: {:?}",
Instant::now() < deadline
);
}
SlotState::Failure => {
if since_started >= self.manager.inner.acquire_timeout_duration {
// the connection failed to acquire a transaction during the grace
// period. schedule the next transaction
match self.schedule_next(&mut current) {
Some(id) if id == self.id => {
current.as_mut().unwrap().state = SlotState::Acquiring;
break;
}
Some(_) => {
drop(current);
tracing::debug!(line = line!(), "parking");
parker.park();
tracing::debug!(line = line!(), "unparked");
}
None => {
*current = Some(Slot {
id: self.id,
started_at: Instant::now(),
state: SlotState::Acquiring,
});
break;
}
}
} else {
tracing::trace!("noticed failure from id={}, parking until end of grace period", slot.id);
let deadline = slot.started_at
+ self.manager.inner.acquire_timeout_duration;
drop(current);
tracing::debug!(line = line!(), "parking");
parker.park_deadline(deadline);
tracing::debug!(
line = line!(),
"unparked after before_deadline?: {:?}",
Instant::now() < deadline
);
}
}
}
}
}
None => match self.schedule_next(&mut current) {
Some(id) if id == self.id => {
current.as_mut().unwrap().state = SlotState::Acquiring;
break;
}
Some(_) => {
drop(current);
tracing::debug!(line = line!(), "parking");
parker.park();
tracing::debug!(line = line!(), "unparked");
}
None => {
*current = Some(Slot {
id: self.id,
started_at: Instant::now(),
state: SlotState::Acquiring,
})
}
},
}
}
Ok(())
}
#[tracing::instrument(skip(self, current))]
#[track_caller]
fn schedule_next(&self, current: &mut MutexGuard<Option<Slot>>) -> Option<ConnId> {
let next = loop {
match self.manager.write_queue.steal() {
Steal::Empty => break None,
Steal::Success(item) => break Some(item),
Steal::Retry => (),
}
};
match next {
Some((id, unpaker)) => {
tracing::debug!(line = line!(), "unparking id={id}");
**current = Some(Slot {
id,
started_at: Instant::now(),
state: SlotState::Notified,
});
unpaker.unpark();
Some(id)
}
None => None,
}
}
#[tracing::instrument(skip(self))]
#[track_caller]
fn release(&self) {
let mut current = self.manager.current.lock();
let Some(slot) = current.take() else {
unreachable!("no lock to release")
};
assert_eq!(slot.id, self.id);
tracing::debug!("transaction finished after {:?}", slot.started_at.elapsed());
match self.schedule_next(&mut current) {
Some(_) => (),
None => {
*current = None;
}
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
enum SlotType {
WriteTxn,
Checkpoint,
}
#[derive(Copy, Clone, Debug)]
enum SlotState {
Notified,
Acquiring,
Acquired(SlotType),
Failure,
}
impl SlotState {
/// Returns `true` if the slot state is [`Notified`].
///
/// [`Notified`]: SlotState::Notified
#[must_use]
fn is_notified(&self) -> bool {
matches!(self, Self::Notified)
}
/// Returns `true` if the slot state is [`Failure`].
///
/// [`Failure`]: SlotState::Failure
#[must_use]
fn is_failure(&self) -> bool {
matches!(self, Self::Failure)
}
}
impl WrapWal<InnerWal> for ManagedConnectionWalWrapper {
#[tracing::instrument(skip_all, fields(id = self.id))]
fn begin_write_txn(&mut self, wrapped: &mut InnerWal) -> libsql_sys::wal::Result<()> {
tracing::debug!("begin write");
self.acquire()?;
match wrapped.begin_write_txn() {
Ok(_) => {
tracing::debug!("transaction acquired");
let mut lock = self.manager.current.lock();
lock.as_mut().unwrap().state = SlotState::Acquired(SlotType::WriteTxn);
Ok(())
}
Err(e) => {
if !matches!(e.code, ErrorCode::DatabaseBusy) {
// this is not a retriable error
tracing::debug!("error acquiring lock, releasing: {e}");
self.release();
} else {
let mut lock = self.manager.current.lock();
lock.as_mut().unwrap().state = SlotState::Failure;
tracing::debug!("error acquiring lock: {e}");
}
Err(e)
}
}
}
#[tracing::instrument(skip_all, fields(id = self.id))]
fn checkpoint(
&mut self,
wrapped: &mut InnerWal,
db: &mut libsql_sys::wal::Sqlite3Db,
mode: libsql_sys::wal::CheckpointMode,
busy_handler: Option<&mut dyn libsql_sys::wal::BusyHandler>,
sync_flags: u32,
// temporary scratch buffer
buf: &mut [u8],
checkpoint_cb: Option<&mut dyn libsql_sys::wal::CheckpointCallback>,
in_wal: Option<&mut i32>,
backfilled: Option<&mut i32>,
) -> libsql_sys::wal::Result<()> {
let before = Instant::now();
self.acquire()?;
self.manager.current.lock().as_mut().unwrap().state =
SlotState::Acquired(SlotType::Checkpoint);
let mode = if rand::random::<f32>() < 0.1 {
CheckpointMode::Truncate
} else {
mode
};
if mode as i32 >= CheckpointMode::Restart as i32 {
tracing::debug!("forcing queue sync");
self.manager.sync_token.fetch_add(1, Ordering::SeqCst);
let queue_len = self.manager.write_queue.len();
for _ in 0..queue_len {
let (id, unparker) = self.manager.write_queue.steal().success().unwrap();
tracing::debug!("forcing queue sync for id={id}");
unparker.unpark();
}
}
tracing::debug!("attempted checkpoint mode: {mode:?}");
let ret = wrapped.checkpoint(
db,
mode,
busy_handler,
sync_flags,
buf,
checkpoint_cb,
in_wal,
backfilled,
);
self.release();
tracing::debug!("checkpoint called: {:?}", before.elapsed());
ret
}
#[tracing::instrument(skip_all, fields(id = self.id))]
fn begin_read_txn(&mut self, wrapped: &mut InnerWal) -> libsql_sys::wal::Result<bool> {
tracing::debug!("begin read txn");
wrapped.begin_read_txn()
}
#[tracing::instrument(skip_all, fields(id = self.id))]
fn end_read_txn(&mut self, wrapped: &mut InnerWal) {
wrapped.end_read_txn();
{
let current = self.manager.current.lock();
// end read will only close the write txn if we actually acquired one, so only release
// if the slot acquire the transaction lock
if let Some(Slot {
id,
state: SlotState::Acquired(..),
..
}) = *current
{
// releasing read transaction releases the write lock (see wal.c)
if id == self.id {
drop(current);
self.release();
}
}
}
tracing::debug!("end read txn");
}
#[tracing::instrument(skip_all, fields(id = self.id))]
fn end_write_txn(&mut self, wrapped: &mut InnerWal) -> libsql_sys::wal::Result<()> {
wrapped.end_write_txn()?;
tracing::debug!("end write txn");
self.release();
Ok(())
}
#[tracing::instrument(skip_all, fields(id = self.id))]
fn close<M: libsql_sys::wal::WalManager<Wal = InnerWal>>(
&mut self,
manager: &M,
wrapped: &mut InnerWal,
db: &mut libsql_sys::wal::Sqlite3Db,
sync_flags: std::ffi::c_int,
_scratch: Option<&mut [u8]>,
) -> libsql_sys::wal::Result<()> {
let before = Instant::now();
let ret = manager.close(wrapped, db, sync_flags, None);
{
let current = self.manager.current.lock();
if let Some(slot @ Slot { id, .. }) = *current {
if id == self.id {
tracing::debug!(
id = self.id,
"connection closed without releasing lock: {slot:?}"
);
drop(current);
self.release()
}
}
}
self.manager.inner.abort_handle.lock().remove(&self.id);
tracing::debug!(id = self.id, "closed in {:?}", before.elapsed());
ret
}
}