autumn-plugin-turso 0.3.0

TursoDB plugin for Autumn: an embedded, SQLite-compatible database handle with config, migrations, health and metrics
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
//! `TursoPlugin`: connects the database to an Autumn app.

use std::borrow::Cow;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use autumn_web::app::AppBuilder;
use autumn_web::plugin::Plugin;
use autumn_web::plugin_contract::PluginContract;
use autumn_web::{AppState, AutumnError};

use crate::config::{ConfigSources, SyncConfig, TursoConfig};
use crate::error::TursoError;
use crate::handle::Turso;
use crate::health::TursoHealthIndicator;
use crate::metrics::TursoMetricsSource;
use crate::migrate::Migration;
use crate::slot::{Slot, SlotState};

/// The name of the config section, health indicator and metrics source.
const NAME: &str = "turso";

/// Installs a Turso database in an Autumn app.
///
/// At startup the plugin reads `[turso]`, opens the database, applies
/// migrations and puts a [`Turso`] handle in `AppState`. At shutdown it
/// pushes (with sync) and closes the handle.
///
/// ```no_run
/// use autumn_plugin_turso::{Migration, TursoPlugin};
///
/// const NOTES: Migration = Migration::new("0001_notes", "CREATE TABLE notes (body TEXT);");
///
/// # async fn run() {
/// autumn_web::app()
///     .plugin(TursoPlugin::new().migration(NOTES))
///     .run()
///     .await;
/// # }
/// ```
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct TursoPlugin {
    base: TursoConfig,
    migrations: Vec<Migration>,
    sources: Option<ConfigSources>,
}

impl TursoPlugin {
    /// Make a plugin with the default config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set `enabled`. The config files and environment can change it.
    pub const fn enabled(mut self, enabled: bool) -> Self {
        self.base.enabled = enabled;
        self
    }

    /// Set the database path. The config files and environment can change it.
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.base.path = path.into();
        self
    }

    /// Set `read_only`.
    pub const fn read_only(mut self, read_only: bool) -> Self {
        self.base.read_only = read_only;
        self
    }

    /// Set the lock wait time.
    pub fn busy_timeout(mut self, timeout: Duration) -> Self {
        self.base.busy_timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
        self
    }

    /// Set `migrate_on_start`. When `false`, the plugin only logs pending
    /// migrations.
    pub const fn migrate_on_start(mut self, migrate: bool) -> Self {
        self.base.migrate_on_start = migrate;
        self
    }

    /// Set the sync config. It needs the `sync` feature.
    pub fn sync(mut self, sync: SyncConfig) -> Self {
        self.base.sync = Some(sync);
        self
    }

    /// Add one migration. Migrations run in the order you add them.
    pub fn migration(mut self, migration: Migration) -> Self {
        self.migrations.push(migration);
        self
    }

    /// Add migrations.
    pub fn migrations(mut self, migrations: impl IntoIterator<Item = Migration>) -> Self {
        self.migrations.extend(migrations);
        self
    }

    /// Read config from `sources` instead of the process. Use it in tests.
    pub fn config_sources(mut self, sources: ConfigSources) -> Self {
        self.sources = Some(sources);
        self
    }
}

impl Plugin for TursoPlugin {
    /// One database per app. A second `TursoPlugin` is skipped with a warning.
    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed(env!("CARGO_PKG_NAME"))
    }

    fn contract(&self) -> Option<PluginContract> {
        Some(
            PluginContract::new(env!("CARGO_PKG_NAME"))
                .plugin_version(env!("CARGO_PKG_VERSION"))
                .autumn_web("0.10"),
        )
    }

    fn build(self, app: AppBuilder) -> AppBuilder {
        let slot = Slot::default();
        let running = Running::default();
        let start = Arc::new(Start {
            base: self.base,
            migrations: self.migrations,
            sources: self.sources,
            slot: slot.clone(),
            running: running.clone(),
        });
        app.config_section(NAME)
            .health_indicator(
                NAME,
                Arc::new(TursoHealthIndicator::from_slot(slot.clone())),
            )
            .metrics_source(NAME, Arc::new(TursoMetricsSource::from_slot(slot)))
            .on_startup(move |state| {
                let start = Arc::clone(&start);
                async move {
                    start
                        .run(&state)
                        .await
                        .map_err(AutumnError::internal_server_error)
                }
            })
            .on_shutdown(move || {
                let running = running.clone();
                async move { running.stop().await }
            })
    }
}

struct Start {
    base: TursoConfig,
    migrations: Vec<Migration>,
    sources: Option<ConfigSources>,
    slot: Slot,
    running: Running,
}

impl Start {
    async fn run(&self, state: &AppState) -> Result<(), TursoError> {
        let sources = self
            .sources
            .clone()
            .unwrap_or_else(|| ConfigSources::from_process(state.profile()));
        let config = TursoConfig::resolve(self.base.clone(), &sources)?;
        if !config.enabled {
            tracing::info!("turso plugin is disabled");
            self.slot.set(SlotState::Disabled);
            return Ok(());
        }
        if self.running.is_started() {
            return Err(TursoError::AlreadyStarted);
        }
        let handle = Turso::open(&config).await?;
        if config.migrate_on_start {
            handle.migrate(&self.migrations).await?;
        } else {
            let pending = handle.pending(&self.migrations).await?;
            if !pending.is_empty() {
                tracing::warn!(
                    ?pending,
                    "turso migrations are pending; migrate_on_start is off"
                );
            }
        }
        self.running.start(&handle, config.active_sync())?;
        state.insert_extension(handle.clone());
        self.slot.set(SlotState::Open(handle));
        tracing::info!(path = %config.path, "turso database open");
        Ok(())
    }
}

/// What shutdown must stop.
#[derive(Clone, Default)]
struct Running(Arc<Mutex<Option<RunningState>>>);

struct RunningState {
    handle: Turso,
    #[cfg(feature = "sync")]
    sync: Option<SyncTask>,
}

impl Running {
    fn is_started(&self) -> bool {
        self.0
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .is_some()
    }

    /// Record the open handle and start the sync loop. A second start is an
    /// error.
    #[cfg_attr(not(feature = "sync"), allow(unused_variables))]
    fn start(&self, handle: &Turso, sync: Option<&SyncConfig>) -> Result<(), TursoError> {
        let mut slot = self.0.lock().unwrap_or_else(PoisonError::into_inner);
        if slot.is_some() {
            return Err(TursoError::AlreadyStarted);
        }
        *slot = Some(RunningState {
            handle: handle.clone(),
            #[cfg(feature = "sync")]
            sync: sync.map(|sync| SyncTask::start(handle, sync)),
        });
        Ok(())
    }

    async fn stop(&self) {
        let state = self.0.lock().unwrap_or_else(PoisonError::into_inner).take();
        let Some(state) = state else {
            return;
        };
        #[cfg(feature = "sync")]
        if let Some(sync) = state.sync {
            sync.stop(&state.handle).await;
        }
        state.handle.close().await;
        tracing::info!("turso database closed");
    }
}

/// The sync loop and the shutdown push.
#[cfg(feature = "sync")]
struct SyncTask {
    push_on_shutdown: bool,
    stop: Option<tokio::sync::watch::Sender<bool>>,
    task: Option<tokio::task::JoinHandle<()>>,
}

#[cfg(feature = "sync")]
impl SyncTask {
    fn start(handle: &Turso, config: &SyncConfig) -> Self {
        let mut task = Self {
            push_on_shutdown: config.push_on_shutdown,
            stop: None,
            task: None,
        };
        if config.interval_secs > 0 {
            let (tx, rx) = tokio::sync::watch::channel(false);
            let every = Duration::from_secs(config.interval_secs);
            task.stop = Some(tx);
            task.task = Some(tokio::spawn(sync_loop(handle.clone(), every, rx)));
        }
        task
    }

    /// Stop the loop, then push once. Each step has a time limit, so the
    /// caller can always close the handle.
    async fn stop(self, handle: &Turso) {
        if let Some(stop) = self.stop {
            let _ = stop.send(true);
        }
        if let Some(mut task) = self.task
            && tokio::time::timeout(STOP_LOOP_TIMEOUT, &mut task)
                .await
                .is_err()
        {
            task.abort();
        }
        if !self.push_on_shutdown {
            return;
        }
        match tokio::time::timeout(SHUTDOWN_PUSH_TIMEOUT, handle.push()).await {
            Ok(Ok(())) => {}
            Ok(Err(err)) => tracing::error!(%err, "turso push at shutdown failed"),
            Err(_) => tracing::error!("turso push at shutdown took too long; local data is kept"),
        }
    }
}

/// How long shutdown waits for the sync loop to stop.
#[cfg(feature = "sync")]
const STOP_LOOP_TIMEOUT: Duration = Duration::from_secs(2);

/// How long shutdown waits for the final push.
#[cfg(feature = "sync")]
const SHUTDOWN_PUSH_TIMEOUT: Duration = Duration::from_secs(10);

/// Push and pull every `every`. Log errors and continue. A stop signal
/// also stops a push or pull in progress.
#[cfg(feature = "sync")]
async fn sync_loop(handle: Turso, every: Duration, mut stop: tokio::sync::watch::Receiver<bool>) {
    let mut ticker = tokio::time::interval(every);
    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    ticker.tick().await;
    loop {
        tokio::select! {
            _ = ticker.tick() => {}
            _ = stop.changed() => break,
        }
        let round = async {
            if let Err(err) = handle.push().await {
                tracing::warn!(%err, "turso sync push failed");
            }
            if let Err(err) = handle.pull().await {
                tracing::warn!(%err, "turso sync pull failed");
            }
        };
        tokio::select! {
            () = round => {}
            _ = stop.changed() => break,
        }
    }
}

#[cfg(test)]
mod local_tests {
    use super::*;

    async fn memory() -> Turso {
        Turso::open(&TursoConfig::new(":memory:"))
            .await
            .expect("open")
    }

    #[tokio::test]
    async fn stop_closes_a_local_handle() {
        let handle = memory().await;
        let running = Running::default();
        running.start(&handle, None).expect("start");
        running.stop().await;
        assert!(handle.is_closed());
    }

    #[tokio::test]
    async fn second_start_is_refused() {
        let running = Running::default();
        running.start(&memory().await, None).expect("first");
        let err = running.start(&memory().await, None).expect_err("second");
        assert!(matches!(err, TursoError::AlreadyStarted), "{err:?}");
    }
}

#[cfg(all(test, feature = "sync"))]
mod tests {
    use super::*;

    use crate::sync_server;

    fn synced(dir: &tempfile::TempDir, url: &str, interval_secs: u64) -> TursoConfig {
        let mut sync = SyncConfig::new(url);
        sync.interval_secs = interval_secs;
        TursoConfig::new(dir.path().join("db").to_string_lossy()).sync(sync)
    }

    async fn count(db: &Turso) -> i64 {
        let rows = db
            .query("SELECT count(*) FROM notes", ())
            .await
            .expect("count");
        rows[0].get(0).expect("n")
    }

    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "requires tursodb (TURSODB_BIN)"]
    async fn shutdown_pushes_then_closes() {
        let server = sync_server::SyncServer::start();
        let dir = tempfile::tempdir().expect("dir");
        let config = synced(&dir, server.url(), 0);
        let handle = Turso::open(&config).await.expect("open");
        handle
            .execute_batch("CREATE TABLE notes (body TEXT); INSERT INTO notes VALUES ('x');")
            .await
            .expect("write");
        let running = Running::default();
        running.start(&handle, config.sync.as_ref()).expect("start");
        stop_in_time(&running).await;
        assert!(handle.is_closed());

        let other_dir = tempfile::tempdir().expect("dir");
        let other = Turso::open(&synced(&other_dir, server.url(), 0))
            .await
            .expect("other");
        assert_eq!(count(&other).await, 1, "shutdown must push");
    }

    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "requires tursodb (TURSODB_BIN)"]
    async fn interval_loop_pushes_and_pulls() {
        let server = sync_server::SyncServer::start();
        let dir = tempfile::tempdir().expect("dir");
        let config = synced(&dir, server.url(), 1);
        let handle = Turso::open(&config).await.expect("open");
        handle
            .execute_batch("CREATE TABLE notes (body TEXT); INSERT INTO notes VALUES ('x');")
            .await
            .expect("write");
        let running = Running::default();
        running.start(&handle, config.sync.as_ref()).expect("start");
        let deadline = std::time::Instant::now() + Duration::from_secs(20);
        while handle.stats().sync_pushes == 0 || handle.stats().sync_pulls < 2 {
            assert!(
                std::time::Instant::now() < deadline,
                "loop did not sync: {:?}",
                handle.stats()
            );
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        stop_in_time(&running).await;
        assert!(handle.is_closed());
    }

    async fn stop_in_time(running: &Running) {
        tokio::time::timeout(Duration::from_secs(15), running.stop())
            .await
            .expect("stop must finish in time");
    }

    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "requires tursodb (TURSODB_BIN)"]
    async fn no_push_when_push_on_shutdown_is_off() {
        let server = sync_server::SyncServer::start();
        let dir = tempfile::tempdir().expect("dir");
        let mut config = synced(&dir, server.url(), 0);
        if let Some(sync) = config.sync.as_mut() {
            sync.push_on_shutdown = false;
        }
        let handle = Turso::open(&config).await.expect("open");
        handle
            .execute_batch("CREATE TABLE notes (body TEXT); INSERT INTO notes VALUES ('x');")
            .await
            .expect("write");
        let running = Running::default();
        running.start(&handle, config.sync.as_ref()).expect("start");
        stop_in_time(&running).await;
        assert_eq!(handle.stats().sync_pushes, 0);
    }

    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "requires tursodb (TURSODB_BIN)"]
    async fn loop_counts_errors_and_continues_when_the_server_goes_away() {
        let server = sync_server::SyncServer::start();
        let dir = tempfile::tempdir().expect("dir");
        let config = synced(&dir, server.url(), 1);
        let handle = Turso::open(&config).await.expect("open");
        let running = Running::default();
        running.start(&handle, config.sync.as_ref()).expect("start");
        drop(server);
        let deadline = std::time::Instant::now() + Duration::from_secs(30);
        while handle.stats().sync_errors < 2 {
            assert!(
                std::time::Instant::now() < deadline,
                "no sync errors counted: {:?}",
                handle.stats()
            );
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        stop_in_time(&running).await;
        assert!(handle.is_closed());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn stop_without_start_is_a_no_op() {
        Running::default().stop().await;
    }
}