mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
// Failures are `DatabaseError`s, returned through `Result` and handled by
// `handle_error`. `put_region_resource(s)` handle their errors themselves.
//
// Statements come from rusqlite's per-connection statement cache
// (`prepare_cached`), so they are dropped with the connection.
//
// A cache hit queues its row's `accessed` timestamp instead of writing it in
// a transaction of its own.
// The owner flushes the queue (`flush_accessed`, see `set_accessed_callback`);
// closing the database, changing its path, reopening it read-only, resizing
// the cache, deleting a region and a full queue flush it too, and `put`'s
// eviction writes it in its own transaction.

mod regions;
mod resources;
mod schema;

use std::collections::BTreeMap;

use mln_style::error::{Error, ErrorKind};
use rusqlite::types::FromSqlError;
use rusqlite::{Connection, Row, ffi};

use crate::log_target;
use crate::storage::constants::DEFAULT_MAX_CACHE_SIZE;
use crate::storage::resource::{Kind, Resource, TileData};

/// The most rows whose `accessed` timestamp waits to be written. Reads of
/// other rows while the queue is full don't update their timestamps.
pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;

/// Why a database operation failed.
#[derive(Clone, Debug, thiserror::Error)]
pub enum DatabaseError {
    /// SQLite failed with the extended result `code`.
    #[error("{message}")]
    Sqlite { code: i32, message: String },
    /// A file operation failed with the OS error `code`.
    #[error("{message}")]
    Io { code: i32, message: String },
    /// The operation failed, such as on a malformed region definition in the
    /// database.
    #[error("{0}")]
    Failed(String),
    /// An argument was invalid, such as a region definition's zoom range.
    #[error("{0}")]
    InvalidArgument(String),
    /// The database has no offline region with this ID.
    #[error("no offline region has ID {0}")]
    RegionNotFound(i64),
}

impl From<rusqlite::Error> for DatabaseError {
    fn from(e: rusqlite::Error) -> Self {
        let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
        DatabaseError::Sqlite { code, message: e.to_string() }
    }
}

impl From<FromSqlError> for DatabaseError {
    /// A column of an unexpected type, as rusqlite reports it.
    fn from(e: FromSqlError) -> Self {
        DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
    }
}

impl From<Error> for DatabaseError {
    fn from(e: Error) -> Self {
        match e.kind {
            ErrorKind::InvalidArgument => DatabaseError::InvalidArgument(e.message),
            _ => DatabaseError::Failed(e.message),
        }
    }
}

impl From<DatabaseError> for Error {
    /// An invalid argument for [`DatabaseError::InvalidArgument`], not found for
    /// [`DatabaseError::RegionNotFound`], and [`ErrorKind::Failed`] otherwise.
    fn from(error: DatabaseError) -> Self {
        let kind = match error {
            DatabaseError::InvalidArgument(_) => ErrorKind::InvalidArgument,
            DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
            _ => ErrorKind::Failed,
        };
        Error::new(kind, error.to_string())
    }
}

type DbResult<T> = Result<T, DatabaseError>;

fn delete_file(filename: &str) -> DbResult<()> {
    match std::fs::remove_file(filename) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => {
            let code = e.raw_os_error().unwrap_or(0);
            let what = e.to_string();
            let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
            Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
        }
    }
}

pub struct OfflineDatabase {
    path: String,
    db: Option<Connection>,

    maximum_ambient_cache_size: u64,
    current_ambient_cache_size: Option<u64>,

    autopack: bool,
    read_only: bool,

    /// `accessed` timestamps (seconds) of cache hits not yet written, by
    /// row id.
    pending_resource_accessed: BTreeMap<i64, i64>,
    pending_tile_accessed: BTreeMap<i64, i64>,
    /// Set when `put`'s eviction wrote the pending timestamps in its
    /// transaction, so they are dropped once it commits.
    pending_applied_for_eviction: bool,
    /// The last flush failed: a full queue waits for the next scheduled
    /// flush instead of retrying on every read.
    accessed_flush_failed: bool,
    accessed_callback: Option<Box<dyn FnMut() + Send>>,
}

impl Drop for OfflineDatabase {
    fn drop(&mut self) {
        self.cleanup();
    }
}

impl OfflineDatabase {
    /// The database at `path`, which it creates or migrates to the current
    /// schema. A database it can't open, it opens again at its next use.
    pub fn new(path: impl Into<String>) -> Self {
        let mut db = OfflineDatabase {
            path: path.into(),
            db: None,
            maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
            current_ambient_cache_size: None,
            autopack: true,
            read_only: false,
            pending_resource_accessed: BTreeMap::new(),
            pending_tile_accessed: BTreeMap::new(),
            pending_applied_for_eviction: false,
            accessed_flush_failed: false,
            accessed_callback: None,
        };
        // Assume that we can't open the database right now and work with an
        // empty database object.
        if let Err(e) = db.initialize() {
            db.handle_error(&e, "open database");
        }
        db
    }

    #[cfg(test)]
    pub(crate) fn change_path(&mut self, path: &str) {
        tracing::info!(target: log_target::DATABASE, "Changing the database path.");
        self.cleanup();
        self.path = path.to_owned();
        if let Err(e) = self.initialize() {
            self.handle_error(&e, "open database");
        }
    }

    fn cleanup(&mut self) {
        self.flush_accessed();
        self.discard_pending_accessed();
        self.db = None;
    }

    fn disabled(&mut self) -> bool {
        if self.maximum_ambient_cache_size != 0 {
            return false;
        }

        let regions = self.list_regions();
        regions.map_or(true, |regions| regions.is_empty())
    }

    fn handle_error(&mut self, error: &DatabaseError, action: &str) {
        match error {
            DatabaseError::Sqlite { code, message } => {
                let primary_code = code & 0xff;
                if primary_code == ffi::SQLITE_NOTADB
                    || primary_code == ffi::SQLITE_CORRUPT
                    || *code == ffi::SQLITE_READONLY_DBMOVED
                {
                    // The database was corruped, moved away, or deleted.
                    // We're going to start fresh with a clean slate for the
                    // next operation.
                    tracing::error!(
                        target: log_target::DATABASE,
                        code = i64::from(primary_code),
                        action,
                        error = %message,
                        "Offline database operation failed"
                    );
                    if let Err(io_ex) = self.remove_existing() {
                        self.handle_error(&io_ex, action);
                    }
                } else {
                    // We treat the error as temporary, and pretend we have an
                    // inaccessible DB.
                    tracing::warn!(
                        target: log_target::DATABASE,
                        code = i64::from(primary_code),
                        action,
                        error = %message,
                        "Offline database operation failed"
                    );
                }
            }
            DatabaseError::Io { code, message } => {
                // We failed to delete the database file.
                tracing::error!(
                    target: log_target::DATABASE,
                    code = i64::from(*code),
                    action,
                    error = %message,
                    "Offline database operation failed"
                );
            }
            DatabaseError::Failed(message) => {
                tracing::error!(target: log_target::DATABASE, action, error = %message, "Offline database operation failed");
            }
            DatabaseError::InvalidArgument(_) => {
                tracing::error!(target: log_target::DATABASE, action, "Offline database operation failed");
            }
            // `RegionNotFound` is the caller's to report.
            DatabaseError::RegionNotFound(_) => {}
        }
    }

    /// Handles `result`'s error, if any (see `handle_error`), and passes
    /// the result on.
    fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
        if let Err(e) = &result {
            self.handle_error(e, action);
        }
        result
    }

    fn remove_existing(&mut self) -> DbResult<()> {
        tracing::warn!(target: log_target::DATABASE, "Removing existing incompatible offline database");

        self.discard_pending_accessed();
        let filename = match &self.db {
            Some(db) => db.path().unwrap_or("").to_owned(),
            None => self.path.clone(),
        };
        self.db = None;

        if !filename.is_empty() {
            delete_file(&filename)?;
        }
        Ok(())
    }

    fn check_flags(&self) -> DbResult<()> {
        if self.read_only {
            return Err(DatabaseError::Failed("Cannot modify database in read-only mode".to_owned()));
        }
        Ok(())
    }

    /// The connection, which opens the database if it isn't open.
    fn db(&mut self) -> DbResult<&Connection> {
        if self.db.is_none() {
            self.initialize()?;
        }
        self.db.as_ref().ok_or_else(|| DatabaseError::Failed("Database not initialized".to_owned()))
    }

    /// Runs `sql`, a statement that returns no rows, with `params` bound;
    /// returns the number of rows changed.
    fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
        let conn = self.db()?;
        let mut stmt = conn.prepare_cached(sql)?;
        Ok(stmt.execute(params)? as u64)
    }

    /// Runs `sql` with `params` bound and steps once: `f` reads the row,
    /// `None` when there is none.
    fn query_row<T>(
        &mut self,
        sql: &str,
        params: impl rusqlite::Params,
        f: impl FnOnce(&Row<'_>) -> DbResult<T>,
    ) -> DbResult<Option<T>> {
        let conn = self.db()?;
        let mut stmt = conn.prepare_cached(sql)?;
        let mut rows = stmt.query(params)?;
        match rows.next()? {
            None => Ok(None),
            Some(row) => f(row).map(Some),
        }
    }

    /// The row id of the last statement's insert.
    fn last_insert_row_id(&mut self) -> DbResult<i64> {
        let conn = self.db()?;
        Ok(conn.last_insert_rowid())
    }

    /// Runs `f` in a transaction that commits after `f` succeeds and rolls
    /// back when `f` fails.
    fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
        exec(self.db()?, begin.sql())?;
        match f(self) {
            Ok(value) => {
                exec(self.db()?, "COMMIT TRANSACTION")?;
                Ok(value)
            }
            Err(e) => {
                // `f`'s error is the one to report, not a failed rollback's.
                if let Some(db) = &self.db {
                    let _ = exec(db, "ROLLBACK TRANSACTION");
                }
                Err(e)
            }
        }
    }

    fn pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
        Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
    }

    pub(crate) fn pack(&mut self) -> DbResult<()> {
        let result = (|| -> DbResult<()> {
            if self.db.is_none() {
                self.initialize()?;
            }
            self.vacuum()
        })();
        self.report(result, "pack storage")
    }

    #[cfg(test)]
    pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
        self.autopack = autopack;
    }

    pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
        if self.read_only == read_only {
            return;
        }
        self.cleanup();
        self.read_only = read_only;
        if let Err(e) = self.initialize() {
            self.handle_error(&e, "reopen database read-only");
        }
    }

    /// Deletes the database file and starts an empty one. Returns the error,
    /// if any.
    pub(crate) fn reset_database(&mut self) -> DbResult<()> {
        let result = self.remove_existing().and_then(|()| self.initialize());
        self.report(result, "reset database")
    }
}

/// How a transaction takes its locks.
#[derive(Clone, Copy)]
enum Begin {
    Deferred,
    Immediate,
}

impl Begin {
    fn sql(self) -> &'static str {
        match self {
            Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
            Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
        }
    }
}

/// Runs every statement of `sql` to completion, as `sqlite3_exec` does.
/// rusqlite's `execute_batch` steps each statement only once, which leaves
/// e.g. `PRAGMA incremental_vacuum` after freeing one page.
fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
    use rusqlite::fallible_iterator::FallibleIterator as _;

    let mut batch = rusqlite::Batch::new(conn, sql);
    while let Some(mut stmt) = batch.next()? {
        let mut rows = stmt.raw_query();
        while rows.next()?.is_some() {}
    }
    Ok(())
}

/// The tile data of a tile resource. A tile resource without it is stored
/// and found by its URL, as other resources are.
fn tile_data(resource: &Resource) -> Option<&TileData> {
    resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
}

/// A table of copies.
#[derive(Clone, Copy)]
enum Table {
    Tiles,
    Resources,
}

impl Table {
    fn name(self) -> &'static str {
        match self {
            Table::Tiles => "tiles",
            Table::Resources => "resources",
        }
    }

    /// The table that links the copies to the regions that hold them, and
    /// its column for a copy's id.
    fn regions(self) -> (&'static str, &'static str) {
        match self {
            Table::Tiles => ("region_tiles", "tile_id"),
            Table::Resources => ("region_resources", "resource_id"),
        }
    }
}

/// Where the database stores a resource's copy: a tile by its tileset and
/// coordinates in `tiles`, another resource by its cache key in `resources`.
enum Stored<'a> {
    Tile(&'a TileData),
    Resource { url: String, kind: i32 },
}

impl<'a> Stored<'a> {
    fn of(resource: &'a Resource) -> Self {
        match tile_data(resource) {
            Some(tile) => Stored::Tile(tile),
            None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
        }
    }

    fn is_tile(&self) -> bool {
        matches!(self, Stored::Tile(_))
    }
}