Skip to main content

mln_engine/storage/
offline_database.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
14use std::collections::BTreeMap;
15use std::sync::Arc;
16use std::time::Duration;
17
18use mln_style::error::{Error, ErrorKind};
19use rusqlite::types::FromSqlError;
20use rusqlite::{Connection, OpenFlags, Row, ToSql, ffi, params};
21
22use crate::log_target;
23use crate::storage::chrono::{Timestamp, now};
24use crate::storage::compression::{compress, decompress};
25use crate::storage::constants::DEFAULT_MAX_CACHE_SIZE;
26use crate::storage::merge_sideloaded::MERGE_SIDELOADED_DATABASE_SQL;
27use crate::storage::offline::{
28    OfflineRegion, OfflineRegionDefinition, OfflineRegionExpiry, OfflineRegionMetadata, OfflineRegionStatus,
29    OfflineRegions, decode_offline_region_definition, encode_offline_region_definition,
30};
31use crate::storage::offline_schema::OFFLINE_DATABASE_SCHEMA;
32use crate::storage::resource::{Kind, Resource, TileData};
33use crate::storage::response::{Caching, Response};
34
35/// The most rows whose `accessed` timestamp waits to be written. Reads of
36/// other rows while the queue is full don't update their timestamps.
37pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;
38
39/// Why a database operation failed.
40#[derive(Clone, Debug, thiserror::Error)]
41pub enum DatabaseError {
42    /// SQLite failed with the extended result `code`.
43    #[error("{message}")]
44    Sqlite { code: i32, message: String },
45    /// A file operation failed with the OS error `code`.
46    #[error("{message}")]
47    Io { code: i32, message: String },
48    /// The operation failed, such as on a malformed region definition in the
49    /// database.
50    #[error("{0}")]
51    Runtime(String),
52    /// An argument was invalid, such as a region definition's zoom range.
53    #[error("{0}")]
54    Logic(String),
55    /// The database has no offline region with this ID.
56    #[error("no offline region has ID {0}")]
57    RegionNotFound(i64),
58}
59
60impl From<rusqlite::Error> for DatabaseError {
61    fn from(e: rusqlite::Error) -> Self {
62        let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
63        DatabaseError::Sqlite { code, message: e.to_string() }
64    }
65}
66
67impl From<FromSqlError> for DatabaseError {
68    /// A column of an unexpected type, as rusqlite reports it.
69    fn from(e: FromSqlError) -> Self {
70        DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
71    }
72}
73
74impl From<Error> for DatabaseError {
75    fn from(e: Error) -> Self {
76        match e.kind {
77            ErrorKind::InvalidArgument => DatabaseError::Logic(e.message),
78            _ => DatabaseError::Runtime(e.message),
79        }
80    }
81}
82
83impl From<DatabaseError> for Error {
84    /// An invalid argument for [`DatabaseError::Logic`], not found for
85    /// [`DatabaseError::RegionNotFound`], and a native error otherwise.
86    fn from(error: DatabaseError) -> Self {
87        let kind = match error {
88            DatabaseError::Logic(_) => ErrorKind::InvalidArgument,
89            DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
90            _ => ErrorKind::Native,
91        };
92        Error::new(kind, error.to_string())
93    }
94}
95
96type DbResult<T> = Result<T, DatabaseError>;
97
98/// The tile data of a tile resource. A tile resource without it is stored
99/// and found by its URL, as other resources are.
100fn tile_data(resource: &Resource) -> Option<&TileData> {
101    resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
102}
103
104fn delete_file(filename: &str) -> DbResult<()> {
105    match std::fs::remove_file(filename) {
106        Ok(()) => Ok(()),
107        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
108        Err(e) => {
109            let code = e.raw_os_error().unwrap_or(0);
110            let what = std::io::Error::from_raw_os_error(code).to_string();
111            let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
112            Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
113        }
114    }
115}
116
117/// The database size (pages in use) when it was created. The database is
118/// passed to the methods that query it.
119struct DatabaseSizeChangeStats {
120    page_size: u64,
121    page_count: u64,
122    initial_size: u64,
123}
124
125impl DatabaseSizeChangeStats {
126    fn new(db: &mut OfflineDatabase) -> DbResult<Self> {
127        let page_size = db.get_pragma_i64("PRAGMA page_size")? as u64;
128        let page_count = db.get_pragma_i64("PRAGMA page_count")? as u64;
129        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
130        let initial_size = page_size.wrapping_mul(page_count.wrapping_sub(freelist_count as u64));
131        Ok(DatabaseSizeChangeStats { page_size, page_count, initial_size })
132    }
133
134    /// Returns difference between current database size and database size at
135    /// the time of creation of this object.
136    fn diff(&self, db: &mut OfflineDatabase) -> DbResult<i64> {
137        let page_count = db.get_pragma_i64("PRAGMA page_count")?;
138        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
139        let current_size = (self.page_size as i64).wrapping_mul(page_count.wrapping_sub(freelist_count));
140        Ok(current_size.wrapping_sub(self.initial_size as i64))
141    }
142
143    /// Returns how many bytes were released comparing to a database size at
144    /// the time of creation of this object.
145    fn bytes_released(&self, db: &mut OfflineDatabase) -> DbResult<u64> {
146        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
147        let current_size = self.page_size.wrapping_mul(self.page_count.wrapping_sub(freelist_count as u64));
148        Ok((self.initial_size.wrapping_sub(current_size) as i64).max(0) as u64)
149    }
150
151    /// Returns page size for the database.
152    fn page_size(&self) -> u64 {
153        self.page_size
154    }
155}
156
157pub struct OfflineDatabase {
158    path: String,
159    db: Option<Connection>,
160
161    maximum_ambient_cache_size: u64,
162    current_ambient_cache_size: Option<u64>,
163
164    autopack: bool,
165    read_only: bool,
166
167    /// `accessed` timestamps (seconds) of cache hits not yet written, by
168    /// row id.
169    pending_resource_accessed: BTreeMap<i64, i64>,
170    pending_tile_accessed: BTreeMap<i64, i64>,
171    /// Set when `put`'s eviction wrote the pending timestamps in its
172    /// transaction, so they are dropped once it commits.
173    pending_applied_for_eviction: bool,
174    /// The last flush failed: a full queue waits for the next scheduled
175    /// flush instead of retrying on every read.
176    accessed_flush_failed: bool,
177    accessed_callback: Option<Box<dyn FnMut() + Send>>,
178}
179
180impl Drop for OfflineDatabase {
181    fn drop(&mut self) {
182        self.cleanup();
183    }
184}
185
186impl OfflineDatabase {
187    /// Single-point transformer for offline storage keys. For sources where
188    /// the URL is not enough to guarantee uniqueness (eg. PMTiles where all
189    /// requests resolve to the same URL), this function creates a synthetic
190    /// key based on the requested data range.
191    #[must_use]
192    pub(crate) fn cache_key(resource: &Resource) -> String {
193        let Some((first, second)) = resource.data_range else {
194            return resource.url.clone();
195        };
196        let sep = if resource.url.contains('?') { '&' } else { '?' };
197        format!("{}{}_mlnRange={}-{}", resource.url, sep, first, second)
198    }
199
200    /// The database at `path`, which it creates or migrates to the current
201    /// schema. A database it can't open, it opens again at its next use.
202    pub fn new(path: impl Into<String>) -> Self {
203        let mut db = OfflineDatabase {
204            path: path.into(),
205            db: None,
206            maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
207            current_ambient_cache_size: None,
208            autopack: true,
209            read_only: false,
210            pending_resource_accessed: BTreeMap::new(),
211            pending_tile_accessed: BTreeMap::new(),
212            pending_applied_for_eviction: false,
213            accessed_flush_failed: false,
214            accessed_callback: None,
215        };
216        // Assume that we can't open the database right now and work with an
217        // empty database object.
218        if let Err(e) = db.initialize() {
219            db.handle_error(&e, "open database");
220        }
221        db
222    }
223
224    fn initialize(&mut self) -> DbResult<()> {
225        assert!(self.db.is_none());
226
227        let flags = if self.read_only {
228            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI
229        } else {
230            OpenFlags::default()
231        };
232        let db = self.db.insert(Connection::open_with_flags(&self.path, flags)?);
233        db.busy_timeout(Duration::from_millis(i32::MAX as u64))?;
234        exec(db, "PRAGMA foreign_keys = ON")?;
235        if self.read_only {
236            return Ok(());
237        }
238
239        let user_version = self.get_pragma_i64("PRAGMA user_version")?;
240        match user_version {
241            0 | 1 => {
242                // Newly created database, or old cache-only database; remove
243                // old table if it exists.
244                self.remove_old_cache_table()?;
245                self.create_schema()?;
246                Ok(())
247            }
248            2..=6 => {
249                if user_version == 2 {
250                    self.migrate_to_version3()?;
251                }
252                // 3: Removed migration, see below.
253                if user_version <= 4 {
254                    self.migrate_to_version5()?;
255                }
256                if user_version <= 5 {
257                    self.migrate_to_version6()?;
258                }
259                // 6: Happy path; we're done
260                Ok(())
261            }
262            _ => {
263                // Downgrade: delete the database and try to reinitialize.
264                self.remove_existing()?;
265                self.initialize()
266            }
267        }
268    }
269
270    #[cfg(test)]
271    pub(crate) fn change_path(&mut self, path: &str) {
272        log::info!(target: log_target::DATABASE, "Changing the database path.");
273        self.cleanup();
274        self.path = path.to_owned();
275        if let Err(e) = self.initialize() {
276            self.handle_error(&e, "open database");
277        }
278    }
279
280    fn cleanup(&mut self) {
281        self.flush_accessed();
282        self.discard_pending_accessed();
283        self.db = None;
284    }
285
286    /// Sets the callback that runs after a cache hit leaves `accessed`
287    /// timestamps waiting to be written; the owner then calls
288    /// [`flush_accessed`](Self::flush_accessed) later. It runs inside `get`
289    /// and `get_region_resource`, so it must not use this database.
290    pub(crate) fn set_accessed_callback(&mut self, callback: Box<dyn FnMut() + Send>) {
291        self.accessed_callback = Some(callback);
292    }
293
294    /// The number of rows whose `accessed` timestamp waits to be written.
295    #[must_use]
296    pub(crate) fn pending_accessed_count(&self) -> usize {
297        self.pending_resource_accessed.len() + self.pending_tile_accessed.len()
298    }
299
300    /// Writes the waiting `accessed` timestamps in one transaction, never
301    /// moving a row's timestamp back. Returns false and keeps them waiting
302    /// when that fails or the database is read-only or closed.
303    pub(crate) fn flush_accessed(&mut self) -> bool {
304        if self.pending_accessed_count() == 0 {
305            return true;
306        }
307        if self.read_only || self.db.is_none() {
308            return false;
309        }
310        match self.with_transaction(Begin::Immediate, Self::apply_pending_accessed) {
311            Ok(()) => {
312                self.discard_pending_accessed();
313                true
314            }
315            Err(e) => {
316                self.accessed_flush_failed = true;
317                self.handle_error(&e, "flush accessed timestamps");
318                false
319            }
320        }
321    }
322
323    fn discard_pending_accessed(&mut self) {
324        self.pending_resource_accessed.clear();
325        self.pending_tile_accessed.clear();
326        self.accessed_flush_failed = false;
327    }
328
329    /// Runs the `accessed` updates in the open transaction.
330    fn apply_pending_accessed(&mut self) -> DbResult<()> {
331        self.get_db()?;
332        let Some(conn) = &self.db else {
333            return Ok(());
334        };
335        for (sql, pending) in [
336            ("UPDATE resources SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_resource_accessed),
337            ("UPDATE tiles SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_tile_accessed),
338        ] {
339            if pending.is_empty() {
340                continue;
341            }
342            let mut stmt = conn.prepare_cached(sql)?;
343            for (id, accessed) in pending {
344                stmt.execute(params![accessed, id])?;
345            }
346        }
347        Ok(())
348    }
349
350    /// Queues the `accessed` timestamp of a cache hit, used for LRU
351    /// eviction.
352    fn queue_accessed(&mut self, tile: bool, id: i64) {
353        if self.read_only {
354            return;
355        }
356        let accessed = now().secs_since_epoch();
357        let full = self.pending_accessed_count() >= MAX_PENDING_ACCESSED;
358        let pending = if tile { &mut self.pending_tile_accessed } else { &mut self.pending_resource_accessed };
359        if let Some(existing) = pending.get_mut(&id) {
360            *existing = (*existing).max(accessed);
361        } else if !full {
362            pending.insert(id, accessed);
363        }
364    }
365
366    fn disabled(&mut self) -> bool {
367        if self.maximum_ambient_cache_size != 0 {
368            return false;
369        }
370
371        let regions = self.list_regions();
372        regions.map_or(true, |regions| regions.is_empty())
373    }
374
375    fn handle_error(&mut self, error: &DatabaseError, action: &str) {
376        match error {
377            DatabaseError::Sqlite { code, message } => {
378                let primary_code = code & 0xff;
379                if primary_code == ffi::SQLITE_NOTADB
380                    || primary_code == ffi::SQLITE_CORRUPT
381                    || *code == ffi::SQLITE_READONLY_DBMOVED
382                {
383                    // The database was corruped, moved away, or deleted.
384                    // We're going to start fresh with a clean slate for the
385                    // next operation.
386                    log::error!(
387                        target: log_target::DATABASE,
388                        code = i64::from(primary_code);
389                        "Can't {action}: {message}"
390                    );
391                    if let Err(io_ex) = self.remove_existing() {
392                        self.handle_error(&io_ex, action);
393                    }
394                } else {
395                    // We treat the error as temporary, and pretend we have an
396                    // inaccessible DB.
397                    log::warn!(
398                        target: log_target::DATABASE,
399                        code = i64::from(primary_code);
400                        "Can't {action}: {message}"
401                    );
402                }
403            }
404            DatabaseError::Io { code, message } => {
405                // We failed to delete the database file.
406                log::error!(target: log_target::DATABASE, code = i64::from(*code); "Can't {action}: {message}");
407            }
408            DatabaseError::Runtime(message) => {
409                log::error!(target: log_target::DATABASE, "Can't {action}: {message}");
410            }
411            DatabaseError::Logic(_) => {
412                log::error!(target: log_target::DATABASE, "Can't {action}");
413            }
414            // `RegionNotFound` is the caller's to report.
415            DatabaseError::RegionNotFound(_) => {}
416        }
417    }
418
419    fn remove_existing(&mut self) -> DbResult<()> {
420        log::warn!(target: log_target::DATABASE, "Removing existing incompatible offline database");
421
422        self.discard_pending_accessed();
423        let filename = match &self.db {
424            Some(db) => db.path().unwrap_or("").to_owned(),
425            None => self.path.clone(),
426        };
427        self.db = None;
428
429        if !filename.is_empty() {
430            delete_file(&filename)?;
431        }
432        Ok(())
433    }
434
435    fn remove_old_cache_table(&mut self) -> DbResult<()> {
436        self.check_flags()?;
437        exec(self.get_db()?, "DROP TABLE IF EXISTS http_cache")?;
438        if self.autopack {
439            self.vacuum()?;
440        }
441        Ok(())
442    }
443
444    fn create_schema(&mut self) -> DbResult<()> {
445        self.check_flags()?;
446
447        self.vacuum()?;
448        let db = self.get_db()?;
449        exec(db, "PRAGMA journal_mode = DELETE")?;
450        exec(db, "PRAGMA synchronous = FULL")?;
451        self.with_transaction(Begin::Deferred, |this| {
452            let db = this.get_db()?;
453            exec(db, OFFLINE_DATABASE_SCHEMA)?;
454            exec(db, "PRAGMA user_version = 6")?;
455            Ok(())
456        })
457    }
458
459    fn migrate_to_version3(&mut self) -> DbResult<()> {
460        self.check_flags()?;
461        self.vacuum()?;
462        exec(self.get_db()?, "PRAGMA user_version = 3")?;
463        Ok(())
464    }
465
466    // Schema version 4 was WAL journal + NORMAL sync. It was reverted during
467    // pre-release development and the migration was removed entirely to
468    // avoid potential conflicts from quickly (and needlessly) switching
469    // journal and sync modes.
470    //
471    // See: https://github.com/mapbox/mapbox-gl-native/pull/6320
472
473    fn migrate_to_version5(&mut self) -> DbResult<()> {
474        self.check_flags()?;
475        let db = self.get_db()?;
476        exec(db, "PRAGMA journal_mode = DELETE")?;
477        exec(db, "PRAGMA synchronous = FULL")?;
478        exec(db, "PRAGMA user_version = 5")?;
479        Ok(())
480    }
481
482    fn migrate_to_version6(&mut self) -> DbResult<()> {
483        self.check_flags()?;
484        self.with_transaction(Begin::Deferred, |this| {
485            let db = this.get_db()?;
486            exec(db, "ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
487            exec(db, "ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
488            exec(db, "PRAGMA user_version = 6")?;
489            Ok(())
490        })
491    }
492
493    fn vacuum(&mut self) -> DbResult<()> {
494        self.check_flags()?;
495        if self.get_pragma_i64("PRAGMA auto_vacuum")? == 2 {
496            exec(self.get_db()?, "PRAGMA incremental_vacuum")?;
497        } else {
498            // A database without pages, such as a new one in memory, takes
499            // the setting with its first table, and has nothing to vacuum.
500            let empty = self.get_pragma_i64("PRAGMA page_count")? == 0;
501            let db = self.get_db()?;
502            exec(db, "PRAGMA auto_vacuum = INCREMENTAL")?;
503            if !empty {
504                exec(db, "VACUUM")?;
505            }
506        }
507        Ok(())
508    }
509
510    fn check_flags(&self) -> DbResult<()> {
511        if self.read_only {
512            return Err(DatabaseError::Runtime("Cannot modify database in read-only mode".to_owned()));
513        }
514        Ok(())
515    }
516
517    /// The connection, which opens the database if it isn't open.
518    fn get_db(&mut self) -> DbResult<&Connection> {
519        if self.db.is_none() {
520            self.initialize()?;
521        }
522        Ok(self.db.as_ref().expect("initialized database"))
523    }
524
525    /// Runs `sql`, a statement that returns no rows, with `params` bound;
526    /// returns the number of rows changed.
527    fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
528        let conn = self.get_db()?;
529        let mut stmt = conn.prepare_cached(sql)?;
530        Ok(stmt.execute(params)? as u64)
531    }
532
533    /// Runs `sql` with `params` bound and steps once: `f` reads the row,
534    /// `None` when there is none.
535    fn query_row<T>(
536        &mut self,
537        sql: &str,
538        params: impl rusqlite::Params,
539        f: impl FnOnce(&Row<'_>) -> DbResult<T>,
540    ) -> DbResult<Option<T>> {
541        let conn = self.get_db()?;
542        let mut stmt = conn.prepare_cached(sql)?;
543        let mut rows = stmt.query(params)?;
544        match rows.next()? {
545            None => Ok(None),
546            Some(row) => f(row).map(Some),
547        }
548    }
549
550    /// The row id of the last statement's insert.
551    fn last_insert_row_id(&mut self) -> DbResult<i64> {
552        let conn = self.get_db()?;
553        Ok(conn.last_insert_rowid())
554    }
555
556    /// Runs `f` in a transaction that commits after `f` succeeds and rolls
557    /// back when `f` fails.
558    fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
559        exec(self.get_db()?, begin.sql())?;
560        match f(self) {
561            Ok(value) => {
562                exec(self.get_db()?, "COMMIT TRANSACTION")?;
563                Ok(value)
564            }
565            Err(e) => {
566                // `f`'s error is the one to report, not a failed rollback's.
567                if let Some(db) = &self.db {
568                    let _ = exec(db, "ROLLBACK TRANSACTION");
569                }
570                Err(e)
571            }
572        }
573    }
574
575    fn get_pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
576        Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
577    }
578
579    /// The stored copy of `resource`, if any.
580    pub fn get(&mut self, resource: &Resource) -> Option<Response> {
581        let result = if self.disabled() { Ok(None) } else { self.get_internal(resource) };
582        self.report(result, "read resource").ok().flatten().map(|(response, _size)| response)
583    }
584
585    fn get_internal(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
586        let stored = Stored::of(resource);
587        let sql = format!(
588            "SELECT etag, modified, data, compressed, id, {} FROM {} WHERE {}",
589            CACHING_COLUMNS,
590            stored.table().name(),
591            stored.condition()
592        );
593        let Some((response, size, id)) = self.query_row(&sql, &*stored.params(), read_response)? else {
594            return Ok(None);
595        };
596        self.queue_accessed(stored.is_tile(), id);
597        if self.pending_accessed_count() >= MAX_PENDING_ACCESSED && !self.accessed_flush_failed {
598            self.flush_accessed();
599        }
600        if self.pending_accessed_count() > 0
601            && let Some(callback) = &mut self.accessed_callback
602        {
603            callback();
604        }
605        Ok(Some((response, size)))
606    }
607
608    /// The stored size and caching rules of the copy of `resource`; `None`
609    /// without one, or for a copy without data.
610    fn has_internal(&mut self, resource: &Resource) -> DbResult<Option<(u64, Caching)>> {
611        let stored = Stored::of(resource);
612        let sql = format!(
613            "SELECT length(data), {} FROM {} WHERE {}",
614            CACHING_COLUMNS,
615            stored.table().name(),
616            stored.condition()
617        );
618        let row = self.query_row(&sql, &*stored.params(), |row| {
619            let size: Option<i64> = row.get(0)?;
620            size.map(|size| Ok((size as u64, read_caching(row, 1)?))).transpose()
621        })?;
622        Ok(row.flatten())
623    }
624
625    /// `put(const Resource&, const Response&)`: (inserted, stored size). The ambient cache doesn't
626    /// keep a tile the tileset doesn't have (`Response::tile_not_found`), since it would read back as
627    /// an empty tile.
628    pub fn put(&mut self, resource: &Resource, response: &Response) -> (bool, u64) {
629        if self.read_only || response.tile_not_found {
630            return (false, 0);
631        }
632
633        let result = (|| -> DbResult<(bool, u64)> {
634            if self.disabled() {
635                return Ok((false, 0));
636            }
637
638            self.pending_applied_for_eviction = false;
639            let result = self.with_transaction(Begin::Immediate, |this| this.put_internal(resource, response, true))?;
640            if self.pending_applied_for_eviction {
641                self.discard_pending_accessed();
642            }
643            Ok(result)
644        })();
645        self.report(result, "write resource").unwrap_or((false, 0))
646    }
647
648    /// Stores `response` for `resource`, first making room in the ambient
649    /// cache when `evict` is set.
650    fn put_internal(&mut self, resource: &Resource, response: &Response, evict: bool) -> DbResult<(bool, u64)> {
651        self.check_flags()?;
652
653        // An error isn't stored, nor what the server forbids storing.
654        if response.error.is_some() || response.no_store {
655            return Ok((false, 0));
656        }
657
658        // An ambient cache with no room can't store anything, so skip compressing.
659        if evict && self.maximum_ambient_cache_size == 0 {
660            return Ok((false, 0));
661        }
662
663        // A copy the database has, as for a 304, only renews its caching
664        // rules.
665        let renews = renews(response);
666        let compressed = match &response.data {
667            Some(data) if !renews => {
668                Some(compress(data).map_err(DatabaseError::Runtime)?).filter(|c| c.len() < data.len())
669            }
670            _ => None,
671        };
672        let data = if renews {
673            &[]
674        } else {
675            compressed.as_deref().or(response.data.as_deref().map(Vec::as_slice)).unwrap_or_default()
676        };
677        let size = data.len() as u64;
678
679        let stats = if evict {
680            let stats = DatabaseSizeChangeStats::new(self)?;
681            if !self.evict(size, &stats, true)? {
682                log::info!(target: log_target::DATABASE, "Unable to make space for entry");
683                return Ok((false, 0));
684            }
685            Some(stats)
686        } else {
687            None
688        };
689
690        let inserted = self.write(&Stored::of(resource), response, data, compressed.is_some())?;
691
692        if let Some(stats) = stats {
693            self.update_ambient_cache_size(&stats)?;
694        }
695
696        Ok((inserted, size))
697    }
698
699    /// Writes `response`, with `data` as its stored bytes, to the row of
700    /// `stored`, and gives whether it added the row. A copy the database has
701    /// (`renews`) updates only its caching rules.
702    fn write(&mut self, stored: &Stored<'_>, response: &Response, data: &[u8], compressed: bool) -> DbResult<bool> {
703        let secs = |time: Option<Timestamp>| time.map(Timestamp::secs_since_epoch);
704        let (expires, modified) = (secs(response.caching.expires), secs(response.modified));
705        let accessed = now().secs_since_epoch();
706        // An empty body is an empty blob, and no content is NULL.
707        let data = (!response.no_content).then_some(data);
708        let compressed = compressed && data.is_some();
709
710        let mut columns: Vec<(&str, &dyn ToSql)> = vec![
711            ("accessed", &accessed),
712            ("expires", &expires),
713            ("must_revalidate", &response.caching.must_revalidate),
714        ];
715        let renews = renews(response);
716        if !renews {
717            columns.extend::<[(&str, &dyn ToSql); 4]>([
718                ("etag", &response.etag),
719                ("modified", &modified),
720                ("data", &data),
721                ("compressed", &compressed),
722            ]);
723            columns.extend(stored.content());
724        }
725        let key = stored.key();
726        let params: Vec<&dyn ToSql> = columns.iter().chain(&key).map(|(_, value)| *value).collect();
727
728        // Not REPLACE, which would change the row's id.
729        let assignments: Vec<String> = columns.iter().map(|(column, _)| format!("{column} = ?")).collect();
730        let table = stored.table().name();
731        let sql = format!("UPDATE {table} SET {} WHERE {}", assignments.join(", "), stored.condition());
732        if self.execute(&sql, &*params)? != 0 || renews {
733            return Ok(false);
734        }
735
736        let names: Vec<&str> = columns.iter().chain(&key).map(|(column, _)| *column).collect();
737        let sql = format!("INSERT INTO {table} ({}) VALUES ({})", names.join(", "), vec!["?"; names.len()].join(", "));
738        self.execute(&sql, &*params)?;
739        Ok(true)
740    }
741
742    /// Makes the ambient cache's copies stale, so maps revalidate them when
743    /// they next use them. See `invalidate`.
744    pub(crate) fn invalidate_ambient_cache(&mut self) -> DbResult<()> {
745        let result = self.invalidate(
746            "id NOT IN (SELECT tile_id FROM region_tiles)",
747            "id NOT IN (SELECT resource_id FROM region_resources)",
748            [],
749        );
750        self.report(result, "invalidate ambient cache")
751    }
752
753    /// Makes the region's copies stale, so maps revalidate them when they
754    /// next use them and its next download refreshes them. See `invalidate`.
755    pub fn invalidate_region(&mut self, region_id: i64) -> DbResult<()> {
756        let result = self.invalidate(
757            "id IN (SELECT tile_id FROM region_tiles WHERE region_id = ?1)",
758            "id IN (SELECT resource_id FROM region_resources WHERE region_id = ?1)",
759            params![region_id],
760        );
761        self.report(result, "invalidate region")
762    }
763
764    /// Makes the tiles and resources whose ids match the conditions stale
765    /// now. A copy that must revalidate then can't be used until it has.
766    fn invalidate(&mut self, tiles: &str, resources: &str, params: impl rusqlite::Params + Copy) -> DbResult<()> {
767        self.check_flags()?;
768        let now = now().secs_since_epoch();
769        for (table, ids) in [("tiles", tiles), ("resources", resources)] {
770            self.execute(
771                &format!("UPDATE {table} SET expires = MIN(IFNULL(expires, {now}), {now}) WHERE {ids}"),
772                params,
773            )?;
774        }
775        Ok(())
776    }
777
778    /// Clears the ambient cache, freeing space.
779    pub(crate) fn clear_ambient_cache(&mut self) -> DbResult<()> {
780        let result = (|| -> DbResult<()> {
781            self.check_flags()?;
782            // The deleted rows' ids may be reused.
783            self.discard_pending_accessed();
784
785            self.execute(
786                "DELETE FROM tiles \
787                 WHERE id NOT IN (\
788                     SELECT tile_id FROM region_tiles\
789                 )",
790                [],
791            )?;
792
793            self.execute(
794                "DELETE FROM resources \
795                 WHERE id NOT IN (\
796                     SELECT resource_id FROM region_resources\
797                 )",
798                [],
799            )?;
800
801            if self.autopack {
802                self.vacuum()?;
803            }
804            Ok(())
805        })();
806        self.report(result, "clear ambient cache")
807    }
808
809    /// Handles `result`'s error, if any (see `handle_error`), and passes
810    /// the result on.
811    fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
812        if let Err(e) = &result {
813            self.handle_error(e, action);
814        }
815        result
816    }
817
818    /// The regions that `sql` selects: their id, definition and description. A region whose
819    /// definition is malformed fails, or, with `skip_malformed`, is left out.
820    fn read_regions(
821        &mut self,
822        sql: &str,
823        params: impl rusqlite::Params,
824        skip_malformed: bool,
825    ) -> DbResult<OfflineRegions> {
826        let rows = {
827            let mut stmt = self.get_db()?.prepare_cached(sql)?;
828            let mut rows = stmt.query(params)?;
829            let mut result = Vec::new();
830            while let Some(row) = rows.next()? {
831                result.push((row.get(0)?, text_or_blob(row, 1)?, text_or_blob(row, 2)?));
832            }
833            result
834        };
835        let mut regions = OfflineRegions::new();
836        for (id, definition, metadata) in rows {
837            let definition = match decode_offline_region_definition(&definition) {
838                Ok(definition) => definition,
839                Err(e) if skip_malformed => {
840                    log::error!(target: log_target::GENERAL, "{}", e.message);
841                    continue;
842                }
843                Err(e) => return Err(e.into()),
844            };
845            regions.push(OfflineRegion { id, definition, metadata });
846        }
847        Ok(regions)
848    }
849
850    /// Every region whose definition can be read.
851    pub fn list_regions(&mut self) -> DbResult<OfflineRegions> {
852        let result = self.read_regions("SELECT id, definition, description FROM regions", [], true);
853        self.report(result, "list regions")
854    }
855
856    /// The region `region_id`, or `None` when the database has none.
857    pub fn get_region(&mut self, region_id: i64) -> DbResult<Option<OfflineRegion>> {
858        let sql = "SELECT id, definition, description FROM regions WHERE id = ?1";
859        let result = self.read_regions(sql, params![region_id], false).map(|regions| regions.into_iter().next());
860        self.report(result, "get region")
861    }
862
863    /// Creates a region without resources.
864    pub fn create_region(
865        &mut self,
866        definition: &OfflineRegionDefinition,
867        metadata: &OfflineRegionMetadata,
868    ) -> DbResult<OfflineRegion> {
869        let result = (|| -> DbResult<OfflineRegion> {
870            self.check_flags()?;
871            self.execute(
872                "INSERT INTO regions (definition, description) VALUES (?1, ?2)",
873                params![encode_offline_region_definition(definition), metadata_blob(metadata)],
874            )?;
875            Ok(OfflineRegion {
876                id: self.last_insert_row_id()?,
877                definition: definition.clone(),
878                metadata: metadata.clone(),
879            })
880        })();
881        self.report(result, "create region")
882    }
883
884    /// How long the region's stored resources stay usable.
885    pub fn get_region_expiry(&mut self, region_id: i64) -> DbResult<OfflineRegionExpiry> {
886        let result = (|| -> DbResult<OfflineRegionExpiry> {
887            let mut sql = Vec::new();
888            for table in [Table::Tiles, Table::Resources] {
889                let (name, (regions, id)) = (table.name(), table.regions());
890                sql.push(format!(
891                    "SELECT {CACHING_COLUMNS} FROM {regions} AS held JOIN {name} ON {name}.id = held.{id} \
892                     WHERE held.region_id = ?1"
893                ));
894            }
895            let now = now();
896            let mut expiry = OfflineRegionExpiry::default();
897            let mut stmt = self.get_db()?.prepare_cached(&sql.join(" UNION ALL "))?;
898            let mut rows = stmt.query(params![region_id])?;
899            while let Some(row) = rows.next()? {
900                let caching = read_caching(row, 0)?;
901                let earliest = |a: Option<Timestamp>, b: Option<Timestamp>| a.into_iter().chain(b).min();
902                expiry.stale_after = earliest(expiry.stale_after, caching.expires);
903                expiry.usable_offline_until = earliest(expiry.usable_offline_until, caching.usable_until());
904                expiry.stale_resource_count += u64::from(!caching.is_fresh(now));
905                expiry.unusable_resource_count += u64::from(!caching.is_usable(now));
906            }
907            Ok(expiry)
908        })();
909        self.report(result, "get region expiry")
910    }
911
912    pub fn merge_database(&mut self, side_database_path: &str) -> Result<OfflineRegions, DatabaseError> {
913        self.check_flags()?;
914
915        match self.execute("ATTACH DATABASE ?1 AS side", params![side_database_path]) {
916            Ok(_) => {}
917            Err(e @ DatabaseError::Sqlite { code, .. }) => {
918                log::error!(
919                    target: log_target::DATABASE,
920                    code = i64::from(code & 0xff);
921                    "Can't attach database ({side_database_path}) for merge: {e}"
922                );
923                return Err(e);
924            }
925            Err(e) => return Err(e),
926        }
927
928        let result = (|| -> DbResult<OfflineRegions> {
929            // A sideloaded database has the main database's version, 6.
930            let side_user_version = self.get_pragma_i64("PRAGMA side.user_version")?;
931            let main_user_version = self.get_pragma_i64("PRAGMA user_version")?;
932            if side_user_version != main_user_version {
933                return Err(DatabaseError::Runtime("Merge database has incorrect user_version".to_owned()));
934            }
935
936            self.with_transaction(Begin::Deferred, |this| {
937                exec(this.get_db()?, MERGE_SIDELOADED_DATABASE_SQL)?;
938                Ok(())
939            })?;
940
941            let sql = "SELECT DISTINCT r.id, r.definition, r.description FROM side.regions sr \
942                       JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description \
943                       ORDER BY r.id";
944            let result = self.read_regions(sql, [], false)?;
945            exec(self.get_db()?, "DETACH DATABASE side")?;
946            Ok(result)
947        })();
948
949        match result {
950            // `catch (const std::runtime_error& ex)`: everything but the
951            // logic errors, which propagate (side stays attached).
952            Err(e) if !matches!(e, DatabaseError::Logic(_)) => {
953                exec(self.get_db()?, "DETACH DATABASE side")?;
954                log::error!(target: log_target::DATABASE, "{e}");
955                Err(e)
956            }
957            result => result,
958        }
959    }
960
961    pub fn update_metadata(
962        &mut self,
963        region_id: i64,
964        metadata: &OfflineRegionMetadata,
965    ) -> Result<OfflineRegionMetadata, DatabaseError> {
966        let result = (|| -> DbResult<OfflineRegionMetadata> {
967            self.check_flags()?;
968
969            self.execute(
970                "UPDATE regions SET description = ?1 \
971                 WHERE id = ?2",
972                params![metadata_blob(metadata), region_id],
973            )?;
974
975            Ok(metadata.clone())
976        })();
977        self.report(result, "update region metadata")
978    }
979
980    pub fn delete_region(&mut self, region: &OfflineRegion) -> DbResult<()> {
981        let result = (|| -> DbResult<()> {
982            self.check_flags()?;
983            // Eviction uses the stored timestamps if this fails.
984            self.flush_accessed();
985
986            self.execute("DELETE FROM regions WHERE id = ?", params![region.id])?;
987
988            let stats = DatabaseSizeChangeStats::new(self)?;
989            self.evict(0, &stats, false)?;
990            if self.autopack {
991                self.vacuum()?;
992            }
993            self.update_ambient_cache_size(&stats)?;
994            Ok(())
995        })();
996        self.report(result, "delete region")
997    }
998
999    /// The stored copy of `resource`, with its stored size, whether or not
1000    /// the ambient cache is enabled.
1001    pub fn get_region_resource(&mut self, resource: &Resource) -> Option<(Response, u64)> {
1002        let result = self.get_internal(resource);
1003        self.report(result, "read region resource").ok().flatten()
1004    }
1005
1006    /// The stored size and caching rules of the copy of `resource`; `None`
1007    /// without one, or for a copy without data.
1008    pub fn check_region_resource(&mut self, resource: &Resource) -> Option<(u64, Caching)> {
1009        let result = self.has_internal(resource);
1010        self.report(result, "query region resource").ok().flatten()
1011    }
1012
1013    pub fn put_region_resource(&mut self, region_id: i64, resource: &Resource, response: &Response) -> u64 {
1014        let result = (|| -> DbResult<u64> {
1015            self.check_flags()?;
1016
1017            if self.db.is_none() {
1018                self.initialize()?;
1019            }
1020            self.with_transaction(Begin::Deferred, |this| {
1021                this.put_region_resource_internal(region_id, resource, response)
1022            })
1023        })();
1024        result.unwrap_or_else(|e| {
1025            self.handle_error(&e, "write region resource");
1026            0
1027        })
1028    }
1029
1030    pub fn put_region_resources(
1031        &mut self,
1032        region_id: i64,
1033        resources: &[(Resource, Response)],
1034        status: &mut OfflineRegionStatus,
1035    ) {
1036        let result = (|| -> DbResult<()> {
1037            self.check_flags()?;
1038
1039            if self.db.is_none() {
1040                self.initialize()?;
1041            }
1042            // Accumulate all statistics locally first before adding them to
1043            // the OfflineRegionStatus object to ensure correctness when the
1044            // transaction fails.
1045            let mut completed_resource_count = 0u64;
1046            let mut completed_resource_size = 0u64;
1047            let mut completed_tile_count = 0u64;
1048            let mut completed_tile_size = 0u64;
1049
1050            self.with_transaction(Begin::Deferred, |this| {
1051                for (resource, response) in resources {
1052                    let resource_size = this.put_region_resource_internal(region_id, resource, response)?;
1053                    completed_resource_count += 1;
1054                    completed_resource_size += resource_size;
1055                    if resource.kind == Kind::Tile {
1056                        completed_tile_count += 1;
1057                        completed_tile_size += resource_size;
1058                    }
1059                }
1060                Ok(())
1061            })?;
1062
1063            status.completed_resource_count += completed_resource_count;
1064            status.completed_resource_size += completed_resource_size;
1065            status.completed_tile_count += completed_tile_count;
1066            status.completed_tile_size += completed_tile_size;
1067            Ok(())
1068        })();
1069        if let Err(e) = result {
1070            self.handle_error(&e, "write region resources");
1071        }
1072    }
1073
1074    fn put_region_resource_internal(
1075        &mut self,
1076        region_id: i64,
1077        resource: &Resource,
1078        response: &Response,
1079    ) -> DbResult<u64> {
1080        self.check_flags()?;
1081
1082        let mut size = self.put_internal(resource, response, false)?.1;
1083        if response.not_modified {
1084            // A 304 keeps the stored data, so report the size it takes up.
1085            size = self.has_internal(resource)?.map_or(0, |(stored, _)| stored);
1086        }
1087        self.mark_used(region_id, resource)?;
1088        Ok(size)
1089    }
1090
1091    /// Adds `resource`, which the database holds, to the region.
1092    fn mark_used(&mut self, region_id: i64, resource: &Resource) -> DbResult<()> {
1093        self.check_flags()?;
1094        let stored = Stored::of(resource);
1095        let table = stored.table();
1096        let (name, (regions, id)) = (table.name(), table.regions());
1097        let mut params: Vec<&dyn ToSql> = vec![&region_id];
1098        params.extend(stored.params());
1099        self.execute(
1100            &format!(
1101                "INSERT OR IGNORE INTO {regions} (region_id, {id}) SELECT ?, id FROM {name} WHERE {}",
1102                stored.condition()
1103            ),
1104            &*params,
1105        )?;
1106        Ok(())
1107    }
1108
1109    #[cfg(test)]
1110    pub(crate) fn get_region_definition(&mut self, region_id: i64) -> Result<OfflineRegionDefinition, DatabaseError> {
1111        let result = (|| -> DbResult<OfflineRegionDefinition> {
1112            // A missing region reads as an empty, malformed definition.
1113            let definition = self
1114                .query_row("SELECT definition FROM regions WHERE id = ?1", params![region_id], |row| {
1115                    text_or_blob(row, 0)
1116                })?
1117                .unwrap_or_default();
1118
1119            Ok(decode_offline_region_definition(&definition)?)
1120        })();
1121        self.report(result, "load region")
1122    }
1123
1124    /// The number and size of the resources that the region holds, tiles
1125    /// included, and of its tiles.
1126    pub fn get_region_completed_status(&mut self, region_id: i64) -> DbResult<OfflineRegionStatus> {
1127        let result = (|| -> DbResult<OfflineRegionStatus> {
1128            let mut status = OfflineRegionStatus::default();
1129            for table in [Table::Tiles, Table::Resources] {
1130                let (name, (regions, id)) = (table.name(), table.regions());
1131                let (count, size) = self
1132                    .query_row(
1133                        &format!(
1134                            "SELECT COUNT(*), IFNULL(SUM(LENGTH(data)), 0) FROM {regions} \
1135                             JOIN {name} ON {name}.id = {regions}.{id} WHERE region_id = ?1"
1136                        ),
1137                        params![region_id],
1138                        |row| Ok((row.get::<_, i64>(0)? as u64, row.get::<_, i64>(1)? as u64)),
1139                    )?
1140                    .unwrap_or_default();
1141                status.completed_resource_count += count;
1142                status.completed_resource_size += size;
1143                if let Table::Tiles = table {
1144                    status.completed_tile_count = count;
1145                    status.completed_tile_size = size;
1146                }
1147            }
1148            Ok(status)
1149        })();
1150        self.report(result, "get region status")
1151    }
1152
1153    // Remove least-recently used resources and tiles until the used database
1154    // size, as calculated by multiplying the number of in-use pages by the
1155    // page size, is less than the maximum cache size. Returns false if this
1156    // condition cannot be satisfied.
1157    //
1158    // SQLite database never shrinks in size unless we call VACUUM. We here
1159    // are monitoring the soft limit (i.e. number of free pages in the file)
1160    // and as it approaches to the hard limit (i.e. the actual file size) we
1161    // delete an arbitrary number of old cache entries. The free pages
1162    // approach saves us from calling VACUUM or keeping a running total,
1163    // which can be costly.
1164    //
1165    // `apply_accessed` (put only) writes the pending `accessed` timestamps in
1166    // the caller's transaction before choosing what to evict.
1167    fn evict(
1168        &mut self,
1169        needed_free_size: u64,
1170        stats: &DatabaseSizeChangeStats,
1171        apply_accessed: bool,
1172    ) -> DbResult<bool> {
1173        self.check_flags()?;
1174        let mut new_ambient_cache_size =
1175            self.ambient_cache_size()?.wrapping_add(needed_free_size).wrapping_add(stats.page_size());
1176
1177        if apply_accessed
1178            && new_ambient_cache_size > self.maximum_ambient_cache_size
1179            && self.pending_accessed_count() > 0
1180        {
1181            self.apply_pending_accessed()?;
1182            self.pending_applied_for_eviction = true;
1183        }
1184        while new_ambient_cache_size > self.maximum_ambient_cache_size {
1185            let accessed = self.query_row(
1186                "SELECT max(accessed) \
1187                 FROM ( \
1188                     SELECT accessed \
1189                     FROM resources \
1190                     LEFT JOIN region_resources \
1191                     ON resource_id = resources.id \
1192                     WHERE resource_id IS NULL \
1193                   UNION ALL \
1194                     SELECT accessed \
1195                     FROM tiles \
1196                     LEFT JOIN region_tiles \
1197                     ON tile_id = tiles.id \
1198                     WHERE tile_id IS NULL \
1199                   ORDER BY accessed ASC LIMIT ?1 \
1200                 ) ",
1201                params![50],
1202                |row| Ok(row.get::<_, Option<i64>>(0)?),
1203            )?;
1204            let Some(accessed) = accessed.flatten() else {
1205                return Ok(false);
1206            };
1207
1208            let resource_changes = self.execute(
1209                "DELETE FROM resources \
1210                 WHERE id IN ( \
1211                   SELECT id FROM resources \
1212                   LEFT JOIN region_resources \
1213                   ON resource_id = resources.id \
1214                   WHERE resource_id IS NULL \
1215                   AND accessed <= ?1 \
1216                 ) ",
1217                params![accessed],
1218            )?;
1219
1220            let tile_changes = self.execute(
1221                "DELETE FROM tiles \
1222                 WHERE id IN ( \
1223                   SELECT id FROM tiles \
1224                   LEFT JOIN region_tiles \
1225                   ON tile_id = tiles.id \
1226                   WHERE tile_id IS NULL \
1227                   AND accessed <= ?1 \
1228                 ) ",
1229                params![accessed],
1230            )?;
1231
1232            // Update current ambient cache size, based on how many bytes were
1233            // released.
1234            let released = stats.bytes_released(self)?;
1235            new_ambient_cache_size = (new_ambient_cache_size as i64).wrapping_sub(released as i64).max(0) as u64;
1236
1237            if resource_changes == 0 && tile_changes == 0 {
1238                return Ok(false);
1239            }
1240        }
1241
1242        Ok(true)
1243    }
1244
1245    /// The size of the ambient cache's rows, which it reads once and then
1246    /// keeps up to date.
1247    fn ambient_cache_size(&mut self) -> DbResult<u64> {
1248        if let Some(size) = self.current_ambient_cache_size {
1249            return Ok(size);
1250        }
1251        let size = self.query_row(
1252            "SELECT SUM(data) \
1253                 FROM ( \
1254                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1255                                + IFNULL(LENGTH(id), 0) \
1256                                + IFNULL(LENGTH(url_template), 0) \
1257                                + IFNULL(LENGTH(pixel_ratio), 0) \
1258                                + IFNULL(LENGTH(x), 0) \
1259                                + IFNULL(LENGTH(y), 0) \
1260                                + IFNULL(LENGTH(z), 0) \
1261                                + IFNULL(LENGTH(expires), 0) \
1262                                + IFNULL(LENGTH(modified), 0) \
1263                                + IFNULL(LENGTH(etag), 0) \
1264                                + IFNULL(LENGTH(compressed), 0) \
1265                                + IFNULL(LENGTH(accessed), 0) \
1266                                + IFNULL(LENGTH(must_revalidate), 0) \
1267                                ) as data \
1268                     FROM tiles \
1269                     LEFT JOIN region_tiles \
1270                     ON tile_id = tiles.id \
1271                     WHERE tile_id IS NULL \
1272                   UNION ALL \
1273                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1274                                + IFNULL(LENGTH(id), 0) \
1275                                + IFNULL(LENGTH(url), 0) \
1276                                + IFNULL(LENGTH(kind), 0) \
1277                                + IFNULL(LENGTH(expires), 0) \
1278                                + IFNULL(LENGTH(modified), 0) \
1279                                + IFNULL(LENGTH(etag), 0) \
1280                                + IFNULL(LENGTH(compressed), 0) \
1281                                + IFNULL(LENGTH(accessed), 0) \
1282                                + IFNULL(LENGTH(must_revalidate), 0) \
1283                                ) as data \
1284                     FROM resources \
1285                     LEFT JOIN region_resources \
1286                     ON resource_id = resources.id \
1287                     WHERE resource_id IS NULL \
1288                 ) ",
1289            [],
1290            |row| Ok(row.get::<_, Option<i64>>(0)?),
1291        )?;
1292        let size = size.flatten().unwrap_or(0) as u64;
1293        self.current_ambient_cache_size = Some(size);
1294        Ok(size)
1295    }
1296
1297    pub(crate) fn set_maximum_ambient_cache_size(&mut self, size: u64) -> DbResult<()> {
1298        // Eviction uses the stored timestamps if this fails.
1299        self.flush_accessed();
1300        let previous_maximum_ambient_cache_size = self.maximum_ambient_cache_size;
1301
1302        let result = (|| -> DbResult<()> {
1303            let current = self.ambient_cache_size()?;
1304            self.maximum_ambient_cache_size = size;
1305            if current > size {
1306                let stats = DatabaseSizeChangeStats::new(self)?;
1307                self.evict(0, &stats, false)?;
1308                if self.autopack {
1309                    self.vacuum()?;
1310                }
1311                self.update_ambient_cache_size(&stats)?;
1312            }
1313            Ok(())
1314        })();
1315        if result.is_err() {
1316            self.maximum_ambient_cache_size = previous_maximum_ambient_cache_size;
1317        }
1318        self.report(result, "set maximum ambient cache size")
1319    }
1320
1321    pub fn mark_used_resources(&mut self, region_id: i64, resources: &[Resource]) {
1322        let result = (|| -> DbResult<()> {
1323            if self.db.is_none() {
1324                self.initialize()?;
1325            }
1326            self.with_transaction(Begin::Deferred, |this| {
1327                for resource in resources {
1328                    this.mark_used(region_id, resource)?;
1329                }
1330                Ok(())
1331            })
1332        })();
1333        if let Err(e) = result {
1334            self.handle_error(&e, "mark resources as used");
1335        }
1336    }
1337
1338    pub(crate) fn pack(&mut self) -> DbResult<()> {
1339        let result = (|| -> DbResult<()> {
1340            if self.db.is_none() {
1341                self.initialize()?;
1342            }
1343            self.vacuum()
1344        })();
1345        self.report(result, "pack storage")
1346    }
1347
1348    #[cfg(test)]
1349    pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
1350        self.autopack = autopack;
1351    }
1352
1353    pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
1354        if self.read_only == read_only {
1355            return;
1356        }
1357        self.cleanup();
1358        self.read_only = read_only;
1359        if let Err(e) = self.initialize() {
1360            self.handle_error(&e, "reopen database read-only");
1361        }
1362    }
1363
1364    /// Deletes the database file and starts an empty one. Returns the error,
1365    /// if any.
1366    pub(crate) fn reset_database(&mut self) -> DbResult<()> {
1367        let result = self.remove_existing().and_then(|()| self.initialize());
1368        self.report(result, "reset database")
1369    }
1370
1371    fn update_ambient_cache_size(&mut self, stats: &DatabaseSizeChangeStats) -> DbResult<()> {
1372        debug_assert!(self.current_ambient_cache_size.is_some());
1373        if let Some(current) = self.current_ambient_cache_size {
1374            let diff = stats.diff(self)?;
1375            self.current_ambient_cache_size = Some((current as i64).wrapping_add(diff).max(0) as u64);
1376        }
1377        Ok(())
1378    }
1379}
1380
1381/// How a transaction takes its locks.
1382#[derive(Clone, Copy)]
1383enum Begin {
1384    Deferred,
1385    Immediate,
1386}
1387
1388impl Begin {
1389    fn sql(self) -> &'static str {
1390        match self {
1391            Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
1392            Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
1393        }
1394    }
1395}
1396
1397/// Runs every statement of `sql` to completion, as `sqlite3_exec` does.
1398/// rusqlite's `execute_batch` steps each statement only once, which leaves
1399/// e.g. `PRAGMA incremental_vacuum` after freeing one page.
1400fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
1401    use rusqlite::fallible_iterator::FallibleIterator as _;
1402
1403    let mut batch = rusqlite::Batch::new(conn, sql);
1404    while let Some(mut stmt) = batch.next()? {
1405        let mut rows = stmt.raw_query();
1406        while rows.next()?.is_some() {}
1407    }
1408    Ok(())
1409}
1410
1411/// The bytes of a TEXT or BLOB column, such as a region's definition and
1412/// metadata; empty for NULL.
1413fn text_or_blob(row: &Row<'_>, index: usize) -> DbResult<Vec<u8>> {
1414    Ok(row.get_ref(index)?.as_bytes_or_null()?.unwrap_or_default().to_vec())
1415}
1416
1417/// The metadata as a blob to bind. Empty metadata is stored as NULL.
1418fn metadata_blob(metadata: &OfflineRegionMetadata) -> Option<&[u8]> {
1419    if metadata.is_empty() { None } else { Some(metadata.as_slice()) }
1420}
1421
1422/// A table of copies.
1423#[derive(Clone, Copy)]
1424enum Table {
1425    Tiles,
1426    Resources,
1427}
1428
1429impl Table {
1430    fn name(self) -> &'static str {
1431        match self {
1432            Table::Tiles => "tiles",
1433            Table::Resources => "resources",
1434        }
1435    }
1436
1437    /// The table that links the copies to the regions that hold them, and
1438    /// its column for a copy's id.
1439    fn regions(self) -> (&'static str, &'static str) {
1440        match self {
1441            Table::Tiles => ("region_tiles", "tile_id"),
1442            Table::Resources => ("region_resources", "resource_id"),
1443        }
1444    }
1445}
1446
1447/// Where the database stores a resource's copy: a tile by its tileset and
1448/// coordinates in `tiles`, another resource by its cache key in `resources`.
1449enum Stored<'a> {
1450    Tile(&'a TileData),
1451    Resource { url: String, kind: i32 },
1452}
1453
1454impl<'a> Stored<'a> {
1455    fn of(resource: &'a Resource) -> Self {
1456        match tile_data(resource) {
1457            Some(tile) => Stored::Tile(tile),
1458            None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
1459        }
1460    }
1461
1462    fn is_tile(&self) -> bool {
1463        matches!(self, Stored::Tile(_))
1464    }
1465
1466    fn table(&self) -> Table {
1467        if self.is_tile() { Table::Tiles } else { Table::Resources }
1468    }
1469
1470    /// The columns that identify the row, with their values, in the order of
1471    /// `condition`'s parameters.
1472    fn key(&self) -> Vec<(&'static str, &dyn ToSql)> {
1473        match self {
1474            Stored::Tile(tile) => vec![
1475                ("url_template", &tile.url_template),
1476                ("pixel_ratio", &tile.pixel_ratio),
1477                ("x", &tile.x),
1478                ("y", &tile.y),
1479                ("z", &tile.z),
1480            ],
1481            Stored::Resource { url, .. } => vec![("url", url)],
1482        }
1483    }
1484
1485    /// The condition that selects the row, over `params`.
1486    fn condition(&self) -> &'static str {
1487        if self.is_tile() { "url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?" } else { "url = ?" }
1488    }
1489
1490    fn params(&self) -> Vec<&dyn ToSql> {
1491        self.key().into_iter().map(|(_, value)| value).collect()
1492    }
1493
1494    /// The columns besides the response's that a write of new content sets.
1495    fn content(&self) -> Vec<(&'static str, &dyn ToSql)> {
1496        match self {
1497            Stored::Tile(_) => Vec::new(),
1498            Stored::Resource { kind, .. } => vec![("kind", kind)],
1499        }
1500    }
1501}
1502
1503/// Whether `response` brings a copy the database has: a 304, or the copy
1504/// the request carried, which a 304 delivered.
1505fn renews(response: &Response) -> bool {
1506    response.not_modified || response.prior
1507}
1508
1509/// Reads `etag, modified, data, compressed, id`, then the caching columns:
1510/// the response, its stored size, and its row id.
1511fn read_response(row: &Row<'_>) -> DbResult<(Response, u64, i64)> {
1512    let mut response = Response::new();
1513    let mut size = 0u64;
1514    response.etag = row.get(0)?;
1515    response.modified = row.get::<_, Option<i64>>(1)?.map(Timestamp::from_secs);
1516    match row.get_ref(2)?.as_bytes_or_null()? {
1517        None => response.no_content = true,
1518        Some(data) => {
1519            size = data.len() as u64;
1520            let data = if row.get(3)? { decompress(data).map_err(DatabaseError::Runtime)? } else { data.to_vec() };
1521            response.data = Some(Arc::new(data));
1522        }
1523    }
1524    response.caching = read_caching(row, 5)?;
1525    Ok((response, size, row.get(4)?))
1526}
1527
1528/// The columns that `read_caching` reads.
1529const CACHING_COLUMNS: &str = "expires, must_revalidate";
1530
1531/// Reads `CACHING_COLUMNS` from column `start` on.
1532fn read_caching(row: &Row<'_>, start: usize) -> DbResult<Caching> {
1533    Ok(Caching {
1534        expires: row.get::<_, Option<i64>>(start)?.map(Timestamp::from_secs),
1535        must_revalidate: row.get(start + 1)?,
1536    })
1537}
1538// The cached value of offlineTileCount does not need to be
1539// updated here because only non-offline tiles can be removed by
1540// eviction.