Skip to main content

mln_engine/storage/offline_database/
mod.rs

1// Failures are `DatabaseError`s, returned through `Result` and handled by
2// `handle_error`. `put_region_resource(s)` handle their errors themselves.
3//
4// Statements come from rusqlite's per-connection statement cache
5// (`prepare_cached`), so they are dropped with the connection.
6//
7// A cache hit queues its row's `accessed` timestamp instead of writing it in
8// a transaction of its own.
9// The owner flushes the queue (`flush_accessed`, see `set_accessed_callback`);
10// closing the database, changing its path, reopening it read-only, resizing
11// the cache, deleting a region and a full queue flush it too, and `put`'s
12// eviction writes it in its own transaction.
13
14mod regions;
15mod resources;
16mod schema;
17
18use std::collections::BTreeMap;
19
20use mln_style::error::{Error, ErrorKind};
21use rusqlite::types::FromSqlError;
22use rusqlite::{Connection, Row, ffi};
23
24use crate::log_target;
25use crate::storage::constants::DEFAULT_MAX_CACHE_SIZE;
26use crate::storage::resource::{Kind, Resource, TileData};
27
28/// The most rows whose `accessed` timestamp waits to be written. Reads of
29/// other rows while the queue is full don't update their timestamps.
30pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;
31
32/// Why a database operation failed.
33#[derive(Clone, Debug, thiserror::Error)]
34pub enum DatabaseError {
35    /// SQLite failed with the extended result `code`.
36    #[error("{message}")]
37    Sqlite { code: i32, message: String },
38    /// A file operation failed with the OS error `code`.
39    #[error("{message}")]
40    Io { code: i32, message: String },
41    /// The operation failed, such as on a malformed region definition in the
42    /// database.
43    #[error("{0}")]
44    Failed(String),
45    /// An argument was invalid, such as a region definition's zoom range.
46    #[error("{0}")]
47    InvalidArgument(String),
48    /// The database has no offline region with this ID.
49    #[error("no offline region has ID {0}")]
50    RegionNotFound(i64),
51}
52
53impl From<rusqlite::Error> for DatabaseError {
54    fn from(e: rusqlite::Error) -> Self {
55        let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
56        DatabaseError::Sqlite { code, message: e.to_string() }
57    }
58}
59
60impl From<FromSqlError> for DatabaseError {
61    /// A column of an unexpected type, as rusqlite reports it.
62    fn from(e: FromSqlError) -> Self {
63        DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
64    }
65}
66
67impl From<Error> for DatabaseError {
68    fn from(e: Error) -> Self {
69        match e.kind {
70            ErrorKind::InvalidArgument => DatabaseError::InvalidArgument(e.message),
71            _ => DatabaseError::Failed(e.message),
72        }
73    }
74}
75
76impl From<DatabaseError> for Error {
77    /// An invalid argument for [`DatabaseError::InvalidArgument`], not found for
78    /// [`DatabaseError::RegionNotFound`], and [`ErrorKind::Failed`] otherwise.
79    fn from(error: DatabaseError) -> Self {
80        let kind = match error {
81            DatabaseError::InvalidArgument(_) => ErrorKind::InvalidArgument,
82            DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
83            _ => ErrorKind::Failed,
84        };
85        Error::new(kind, error.to_string())
86    }
87}
88
89type DbResult<T> = Result<T, DatabaseError>;
90
91fn delete_file(filename: &str) -> DbResult<()> {
92    match std::fs::remove_file(filename) {
93        Ok(()) => Ok(()),
94        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
95        Err(e) => {
96            let code = e.raw_os_error().unwrap_or(0);
97            let what = e.to_string();
98            let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
99            Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
100        }
101    }
102}
103
104pub struct OfflineDatabase {
105    path: String,
106    db: Option<Connection>,
107
108    maximum_ambient_cache_size: u64,
109    current_ambient_cache_size: Option<u64>,
110
111    autopack: bool,
112    read_only: bool,
113
114    /// `accessed` timestamps (seconds) of cache hits not yet written, by
115    /// row id.
116    pending_resource_accessed: BTreeMap<i64, i64>,
117    pending_tile_accessed: BTreeMap<i64, i64>,
118    /// Set when `put`'s eviction wrote the pending timestamps in its
119    /// transaction, so they are dropped once it commits.
120    pending_applied_for_eviction: bool,
121    /// The last flush failed: a full queue waits for the next scheduled
122    /// flush instead of retrying on every read.
123    accessed_flush_failed: bool,
124    accessed_callback: Option<Box<dyn FnMut() + Send>>,
125}
126
127impl Drop for OfflineDatabase {
128    fn drop(&mut self) {
129        self.cleanup();
130    }
131}
132
133impl OfflineDatabase {
134    /// The database at `path`, which it creates or migrates to the current
135    /// schema. A database it can't open, it opens again at its next use.
136    pub fn new(path: impl Into<String>) -> Self {
137        let mut db = OfflineDatabase {
138            path: path.into(),
139            db: None,
140            maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
141            current_ambient_cache_size: None,
142            autopack: true,
143            read_only: false,
144            pending_resource_accessed: BTreeMap::new(),
145            pending_tile_accessed: BTreeMap::new(),
146            pending_applied_for_eviction: false,
147            accessed_flush_failed: false,
148            accessed_callback: None,
149        };
150        // Assume that we can't open the database right now and work with an
151        // empty database object.
152        if let Err(e) = db.initialize() {
153            db.handle_error(&e, "open database");
154        }
155        db
156    }
157
158    #[cfg(test)]
159    pub(crate) fn change_path(&mut self, path: &str) {
160        tracing::info!(target: log_target::DATABASE, "Changing the database path.");
161        self.cleanup();
162        self.path = path.to_owned();
163        if let Err(e) = self.initialize() {
164            self.handle_error(&e, "open database");
165        }
166    }
167
168    fn cleanup(&mut self) {
169        self.flush_accessed();
170        self.discard_pending_accessed();
171        self.db = None;
172    }
173
174    fn disabled(&mut self) -> bool {
175        if self.maximum_ambient_cache_size != 0 {
176            return false;
177        }
178
179        let regions = self.list_regions();
180        regions.map_or(true, |regions| regions.is_empty())
181    }
182
183    fn handle_error(&mut self, error: &DatabaseError, action: &str) {
184        match error {
185            DatabaseError::Sqlite { code, message } => {
186                let primary_code = code & 0xff;
187                if primary_code == ffi::SQLITE_NOTADB
188                    || primary_code == ffi::SQLITE_CORRUPT
189                    || *code == ffi::SQLITE_READONLY_DBMOVED
190                {
191                    // The database was corruped, moved away, or deleted.
192                    // We're going to start fresh with a clean slate for the
193                    // next operation.
194                    tracing::error!(
195                        target: log_target::DATABASE,
196                        code = i64::from(primary_code),
197                        action,
198                        error = %message,
199                        "Offline database operation failed"
200                    );
201                    if let Err(io_ex) = self.remove_existing() {
202                        self.handle_error(&io_ex, action);
203                    }
204                } else {
205                    // We treat the error as temporary, and pretend we have an
206                    // inaccessible DB.
207                    tracing::warn!(
208                        target: log_target::DATABASE,
209                        code = i64::from(primary_code),
210                        action,
211                        error = %message,
212                        "Offline database operation failed"
213                    );
214                }
215            }
216            DatabaseError::Io { code, message } => {
217                // We failed to delete the database file.
218                tracing::error!(
219                    target: log_target::DATABASE,
220                    code = i64::from(*code),
221                    action,
222                    error = %message,
223                    "Offline database operation failed"
224                );
225            }
226            DatabaseError::Failed(message) => {
227                tracing::error!(target: log_target::DATABASE, action, error = %message, "Offline database operation failed");
228            }
229            DatabaseError::InvalidArgument(_) => {
230                tracing::error!(target: log_target::DATABASE, action, "Offline database operation failed");
231            }
232            // `RegionNotFound` is the caller's to report.
233            DatabaseError::RegionNotFound(_) => {}
234        }
235    }
236
237    /// Handles `result`'s error, if any (see `handle_error`), and passes
238    /// the result on.
239    fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
240        if let Err(e) = &result {
241            self.handle_error(e, action);
242        }
243        result
244    }
245
246    fn remove_existing(&mut self) -> DbResult<()> {
247        tracing::warn!(target: log_target::DATABASE, "Removing existing incompatible offline database");
248
249        self.discard_pending_accessed();
250        let filename = match &self.db {
251            Some(db) => db.path().unwrap_or("").to_owned(),
252            None => self.path.clone(),
253        };
254        self.db = None;
255
256        if !filename.is_empty() {
257            delete_file(&filename)?;
258        }
259        Ok(())
260    }
261
262    fn check_flags(&self) -> DbResult<()> {
263        if self.read_only {
264            return Err(DatabaseError::Failed("Cannot modify database in read-only mode".to_owned()));
265        }
266        Ok(())
267    }
268
269    /// The connection, which opens the database if it isn't open.
270    fn db(&mut self) -> DbResult<&Connection> {
271        if self.db.is_none() {
272            self.initialize()?;
273        }
274        self.db.as_ref().ok_or_else(|| DatabaseError::Failed("Database not initialized".to_owned()))
275    }
276
277    /// Runs `sql`, a statement that returns no rows, with `params` bound;
278    /// returns the number of rows changed.
279    fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
280        let conn = self.db()?;
281        let mut stmt = conn.prepare_cached(sql)?;
282        Ok(stmt.execute(params)? as u64)
283    }
284
285    /// Runs `sql` with `params` bound and steps once: `f` reads the row,
286    /// `None` when there is none.
287    fn query_row<T>(
288        &mut self,
289        sql: &str,
290        params: impl rusqlite::Params,
291        f: impl FnOnce(&Row<'_>) -> DbResult<T>,
292    ) -> DbResult<Option<T>> {
293        let conn = self.db()?;
294        let mut stmt = conn.prepare_cached(sql)?;
295        let mut rows = stmt.query(params)?;
296        match rows.next()? {
297            None => Ok(None),
298            Some(row) => f(row).map(Some),
299        }
300    }
301
302    /// The row id of the last statement's insert.
303    fn last_insert_row_id(&mut self) -> DbResult<i64> {
304        let conn = self.db()?;
305        Ok(conn.last_insert_rowid())
306    }
307
308    /// Runs `f` in a transaction that commits after `f` succeeds and rolls
309    /// back when `f` fails.
310    fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
311        exec(self.db()?, begin.sql())?;
312        match f(self) {
313            Ok(value) => {
314                exec(self.db()?, "COMMIT TRANSACTION")?;
315                Ok(value)
316            }
317            Err(e) => {
318                // `f`'s error is the one to report, not a failed rollback's.
319                if let Some(db) = &self.db {
320                    let _ = exec(db, "ROLLBACK TRANSACTION");
321                }
322                Err(e)
323            }
324        }
325    }
326
327    fn pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
328        Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
329    }
330
331    pub(crate) fn pack(&mut self) -> DbResult<()> {
332        let result = (|| -> DbResult<()> {
333            if self.db.is_none() {
334                self.initialize()?;
335            }
336            self.vacuum()
337        })();
338        self.report(result, "pack storage")
339    }
340
341    #[cfg(test)]
342    pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
343        self.autopack = autopack;
344    }
345
346    pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
347        if self.read_only == read_only {
348            return;
349        }
350        self.cleanup();
351        self.read_only = read_only;
352        if let Err(e) = self.initialize() {
353            self.handle_error(&e, "reopen database read-only");
354        }
355    }
356
357    /// Deletes the database file and starts an empty one. Returns the error,
358    /// if any.
359    pub(crate) fn reset_database(&mut self) -> DbResult<()> {
360        let result = self.remove_existing().and_then(|()| self.initialize());
361        self.report(result, "reset database")
362    }
363}
364
365/// How a transaction takes its locks.
366#[derive(Clone, Copy)]
367enum Begin {
368    Deferred,
369    Immediate,
370}
371
372impl Begin {
373    fn sql(self) -> &'static str {
374        match self {
375            Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
376            Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
377        }
378    }
379}
380
381/// Runs every statement of `sql` to completion, as `sqlite3_exec` does.
382/// rusqlite's `execute_batch` steps each statement only once, which leaves
383/// e.g. `PRAGMA incremental_vacuum` after freeing one page.
384fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
385    use rusqlite::fallible_iterator::FallibleIterator as _;
386
387    let mut batch = rusqlite::Batch::new(conn, sql);
388    while let Some(mut stmt) = batch.next()? {
389        let mut rows = stmt.raw_query();
390        while rows.next()?.is_some() {}
391    }
392    Ok(())
393}
394
395/// The tile data of a tile resource. A tile resource without it is stored
396/// and found by its URL, as other resources are.
397fn tile_data(resource: &Resource) -> Option<&TileData> {
398    resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
399}
400
401/// A table of copies.
402#[derive(Clone, Copy)]
403enum Table {
404    Tiles,
405    Resources,
406}
407
408impl Table {
409    fn name(self) -> &'static str {
410        match self {
411            Table::Tiles => "tiles",
412            Table::Resources => "resources",
413        }
414    }
415
416    /// The table that links the copies to the regions that hold them, and
417    /// its column for a copy's id.
418    fn regions(self) -> (&'static str, &'static str) {
419        match self {
420            Table::Tiles => ("region_tiles", "tile_id"),
421            Table::Resources => ("region_resources", "resource_id"),
422        }
423    }
424}
425
426/// Where the database stores a resource's copy: a tile by its tileset and
427/// coordinates in `tiles`, another resource by its cache key in `resources`.
428enum Stored<'a> {
429    Tile(&'a TileData),
430    Resource { url: String, kind: i32 },
431}
432
433impl<'a> Stored<'a> {
434    fn of(resource: &'a Resource) -> Self {
435        match tile_data(resource) {
436            Some(tile) => Stored::Tile(tile),
437            None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
438        }
439    }
440
441    fn is_tile(&self) -> bool {
442        matches!(self, Stored::Tile(_))
443    }
444}