libsql-wal 0.1.0-alpha.1

wal implementation for libsql
Documentation
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
use std::future::Future;
use std::sync::Arc;

use hashbrown::HashSet;
use libsql_sys::name::NamespaceName;
use tokio::sync::mpsc;
use tokio::task::JoinSet;

use crate::io::Io;
use crate::registry::WalRegistry;

pub(crate) type NotifyCheckpointer = mpsc::Sender<NamespaceName>;

pub enum CheckpointMessage {
    /// notify that a namespace may be checkpointable
    Namespace(NamespaceName),
    /// shutdown initiated
    Shutdown,
}

impl From<NamespaceName> for CheckpointMessage {
    fn from(value: NamespaceName) -> Self {
        Self::Namespace(value)
    }
}

pub type LibsqlCheckpointer<IO, S> = Checkpointer<WalRegistry<IO, S>>;

impl<IO, S> LibsqlCheckpointer<IO, S>
where
    IO: Io,
    S: Sync + Send + 'static,
{
    pub fn new(
        registry: Arc<WalRegistry<IO, S>>,
        notifier: mpsc::Receiver<CheckpointMessage>,
        max_checkpointing_conccurency: usize,
    ) -> Self {
        Self::new_with_performer(registry, notifier, max_checkpointing_conccurency)
    }
}

trait PerformCheckpoint {
    fn checkpoint(
        &self,
        namespace: &NamespaceName,
    ) -> impl Future<Output = crate::error::Result<()>> + Send;
}

impl<IO, S> PerformCheckpoint for WalRegistry<IO, S>
where
    IO: Io,
    S: Sync + Send + 'static,
{
    #[tracing::instrument(skip(self))]
    fn checkpoint(
        &self,
        namespace: &NamespaceName,
    ) -> impl Future<Output = crate::error::Result<()>> + Send {
        let namespace = namespace.clone();
        async move {
            if let Some(registry) = self.get_async(&namespace).await {
                registry.checkpoint().await?;
            }
            Ok(())
        }
    }
}

const CHECKPOINTER_ERROR_THRES: usize = 16;

/// The checkpointer checkpoint wal segments in the main db file, and deletes checkpointed
/// segments.
/// For simplicity of implementation, we only delete segments when they are checkpointed, and only checkpoint when
/// they are reported as durable.
#[derive(Debug)]
pub struct Checkpointer<P> {
    perform_checkpoint: Arc<P>,
    /// Namespaces scheduled for checkpointing, but not currently checkpointing
    scheduled: HashSet<NamespaceName>,
    /// currently checkpointing databases
    checkpointing: HashSet<NamespaceName>,
    /// the checkpointer is notifier whenever there is a change to a namespage that could trigger a
    /// checkpoint
    recv: mpsc::Receiver<CheckpointMessage>,
    max_checkpointing_conccurency: usize,
    shutting_down: bool,
    join_set: JoinSet<(NamespaceName, crate::error::Result<()>)>,
    processing: Vec<NamespaceName>,
    errors: usize,
    /// previous iteration of the loop resulted in no work being enqueued
    no_work: bool,
}

#[allow(private_bounds)]
impl<P> Checkpointer<P>
where
    P: PerformCheckpoint + Send + Sync + 'static,
{
    fn new_with_performer(
        perform_checkpoint: Arc<P>,
        notifier: mpsc::Receiver<CheckpointMessage>,
        max_checkpointing_conccurency: usize,
    ) -> Self {
        Self {
            perform_checkpoint,
            scheduled: Default::default(),
            checkpointing: Default::default(),
            recv: notifier,
            max_checkpointing_conccurency,
            shutting_down: false,
            join_set: JoinSet::new(),
            processing: Vec::new(),
            errors: 0,
            no_work: false,
        }
    }

    #[tracing::instrument(skip(self))]
    pub async fn run(mut self) {
        loop {
            if self.should_exit() {
                tracing::info!("checkpointer exited cleanly.");
                return;
            }

            if self.errors > CHECKPOINTER_ERROR_THRES {
                todo!("handle too many consecutive errors");
            }

            self.step().await;
        }
    }

    fn should_exit(&self) -> bool {
        self.shutting_down
            && self.recv.is_empty()
            && self.scheduled.is_empty()
            && self.checkpointing.is_empty()
            && self.join_set.is_empty()
    }

    async fn step(&mut self) {
        tokio::select! {
            biased;
            result = self.join_set.join_next(), if !self.join_set.is_empty() => {
                match result {
                    Some(Ok((namespace, result))) => {
                        self.checkpointing.remove(&namespace);
                        if let Err(e) = result {
                            self.errors += 1;
                            tracing::error!("error checkpointing ns {namespace}: {e}, rescheduling");
                            // reschedule
                            self.scheduled.insert(namespace);
                        } else {
                            self.errors = 0;
                        }
                    }
                    Some(Err(e)) => panic!("checkpoint task panicked: {e}"),
                    None => unreachable!("got None, but join set is not empty")
                }
            }
            notified = self.recv.recv(), if !self.shutting_down => {
                match notified {
                    Some(CheckpointMessage::Namespace(namespace)) => {
                        tracing::info!(namespace = namespace.as_str(), "notified for checkpoint");
                        self.scheduled.insert(namespace);
                    }
                    None | Some(CheckpointMessage::Shutdown) => {
                        tracing::info!("checkpointed is shutting down. {} namespaces to checkpoint", self.checkpointing.len());
                        self.shutting_down = true;
                    }
                }
            }
            // don't wait if there is stuff to enqueue
            _ = std::future::ready(()), if !self.scheduled.is_empty()
                && self.join_set.len() < self.max_checkpointing_conccurency && !self.no_work => (),
        }

        let n_available = self.max_checkpointing_conccurency - self.join_set.len();
        if n_available > 0 {
            self.no_work = true;
            for namespace in self
                .scheduled
                .difference(&self.checkpointing)
                .take(n_available)
                .cloned()
            {
                self.no_work = false;
                self.processing.push(namespace.clone());
                let perform_checkpoint = self.perform_checkpoint.clone();
                self.join_set.spawn(async move {
                    let ret = perform_checkpoint.checkpoint(&namespace).await;
                    (namespace, ret)
                });
            }

            for namespace in self.processing.drain(..) {
                self.scheduled.remove(&namespace);
                self.checkpointing.insert(namespace);
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::sync::atomic::{AtomicBool, Ordering::Relaxed};

    use tokio::time::Duration;

    use super::*;

    #[tokio::test]
    async fn process_checkpoint() {
        static CALLED: AtomicBool = AtomicBool::new(false);

        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                CALLED.store(true, Relaxed);
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);
        let ns = NamespaceName::from("test");

        sender.send(ns.clone().into()).await.unwrap();

        checkpointer.step().await;

        assert!(checkpointer.checkpointing.contains(&ns));

        checkpointer.step().await;

        assert!(checkpointer.checkpointing.is_empty());
        assert!(checkpointer.scheduled.is_empty());
        assert!(CALLED.load(std::sync::atomic::Ordering::Relaxed));
    }

    #[tokio::test]
    async fn checkpoint_error() {
        static CALLED: AtomicBool = AtomicBool::new(false);

        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                CALLED.store(true, Relaxed);
                // random error
                Err(crate::error::Error::BusySnapshot)
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);
        let ns = NamespaceName::from("test");

        sender.send(ns.clone().into()).await.unwrap();

        checkpointer.step().await;
        assert_eq!(checkpointer.errors, 0);

        assert!(checkpointer.checkpointing.contains(&ns));

        checkpointer.step().await;

        // job is re-enqueued
        assert!(CALLED.load(std::sync::atomic::Ordering::Relaxed));
        assert!(checkpointer.checkpointing.contains(&ns));
        assert!(checkpointer.scheduled.is_empty());
        assert_eq!(checkpointer.errors, 1);
    }

    #[tokio::test]
    async fn checkpointer_shutdown() {
        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);

        drop(sender);

        assert!(!checkpointer.should_exit());

        checkpointer.step().await;

        assert!(checkpointer.should_exit());

        // should return immediately.
        checkpointer.run().await;
    }

    #[tokio::test]
    async fn cant_exit_until_all_processed() {
        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);

        drop(sender);

        checkpointer.step().await;

        let ns: NamespaceName = "test".into();
        checkpointer.scheduled.insert(ns.clone());
        assert!(!checkpointer.should_exit());
        checkpointer.scheduled.remove(&ns);

        checkpointer.checkpointing.insert(ns.clone());
        assert!(!checkpointer.should_exit());
        checkpointer.checkpointing.remove(&ns);

        assert!(checkpointer.should_exit());
        // should return immediately.
        checkpointer.run().await;
    }

    #[tokio::test]
    async fn dont_schedule_already_scheduled() {
        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                tokio::time::sleep(Duration::from_secs(1000)).await;
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);

        let ns: NamespaceName = "test".into();

        sender.send(ns.clone().into()).await.unwrap();
        sender.send(ns.clone().into()).await.unwrap();

        checkpointer.step().await;

        assert!(checkpointer.scheduled.is_empty());
        assert!(checkpointer.checkpointing.contains(&ns));

        checkpointer.step().await;

        assert!(checkpointer.scheduled.contains(&ns));
        assert!(checkpointer.checkpointing.contains(&ns));
        assert_eq!(checkpointer.join_set.len(), 1);
    }

    #[tokio::test]
    async fn schedule_conccurently_for_different_namespaces() {
        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                tokio::time::sleep(Duration::from_secs(1000)).await;
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 5);

        let ns1: NamespaceName = "test1".into();
        let ns2: NamespaceName = "test2".into();

        sender.send(ns1.clone().into()).await.unwrap();
        sender.send(ns2.clone().into()).await.unwrap();

        checkpointer.step().await;

        assert!(checkpointer.scheduled.is_empty());
        assert!(checkpointer.checkpointing.contains(&ns1));
        assert_eq!(checkpointer.checkpointing.len(), 1);

        checkpointer.step().await;

        assert!(checkpointer.scheduled.is_empty());
        assert!(checkpointer.checkpointing.contains(&ns2));
        assert_eq!(checkpointer.checkpointing.len(), 2);
        assert_eq!(checkpointer.join_set.len(), 2);
    }

    #[tokio::test]
    async fn checkpointer_limited_conccurency() {
        #[derive(Debug)]
        struct TestPerformCheckoint;

        impl PerformCheckpoint for TestPerformCheckoint {
            async fn checkpoint(&self, _namespace: &NamespaceName) -> crate::error::Result<()> {
                tokio::time::sleep(Duration::from_secs(1000)).await;
                Ok(())
            }
        }

        let (sender, receiver) = mpsc::channel(8);
        let mut checkpointer =
            Checkpointer::new_with_performer(TestPerformCheckoint.into(), receiver, 2);

        let ns1: NamespaceName = "test1".into();
        let ns2: NamespaceName = "test2".into();
        let ns3: NamespaceName = "test3".into();

        sender.send(ns1.clone().into()).await.unwrap();
        sender.send(ns2.clone().into()).await.unwrap();
        sender.send(ns3.clone().into()).await.unwrap();

        checkpointer.step().await;
        checkpointer.step().await;
        checkpointer.step().await;

        assert_eq!(checkpointer.scheduled.len(), 1);
        assert!(checkpointer.scheduled.contains(&ns3));

        assert!(checkpointer.checkpointing.contains(&ns1));
        assert!(checkpointer.checkpointing.contains(&ns2));
        assert_eq!(checkpointer.checkpointing.len(), 2);
        assert_eq!(checkpointer.join_set.len(), 2);

        tokio::time::pause();
        tokio::time::advance(Duration::from_secs(2000)).await;

        checkpointer.step().await;
        checkpointer.step().await;

        assert!(checkpointer.scheduled.is_empty());
        assert!(checkpointer.checkpointing.contains(&ns3));
        assert_eq!(checkpointer.checkpointing.len(), 1);
    }
}