Skip to main content

mln_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_util::chrono::{Timestamp, now};
19use mln_util::compression::{compress, decompress};
20use mln_util::constants::DEFAULT_MAX_CACHE_SIZE;
21use mln_util::error::{Error, ErrorKind};
22use mln_util::logging::{Event, EventSeverity, Log};
23use rusqlite::types::FromSqlError;
24use rusqlite::{Connection, OpenFlags, Row, ToSql, ffi, params};
25
26use crate::merge_sideloaded::MERGE_SIDELOADED_DATABASE_SQL;
27use crate::offline::{
28    OfflineRegion, OfflineRegionDefinition, OfflineRegionExpiry, OfflineRegionMetadata, OfflineRegionStatus,
29    OfflineRegions, decode_offline_region_definition, encode_offline_region_definition,
30};
31use crate::offline_schema::OFFLINE_DATABASE_SCHEMA;
32use crate::resource::{Kind, Resource, TileData};
33use crate::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(Event::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::record(
387                        EventSeverity::Error,
388                        Event::Database,
389                        i64::from(primary_code),
390                        &format!("Can't {action}: {message}"),
391                    );
392                    if let Err(io_ex) = self.remove_existing() {
393                        self.handle_error(&io_ex, action);
394                    }
395                } else {
396                    // We treat the error as temporary, and pretend we have an
397                    // inaccessible DB.
398                    Log::record(
399                        EventSeverity::Warning,
400                        Event::Database,
401                        i64::from(primary_code),
402                        &format!("Can't {action}: {message}"),
403                    );
404                }
405            }
406            DatabaseError::Io { code, message } => {
407                // We failed to delete the database file.
408                Log::record(
409                    EventSeverity::Error,
410                    Event::Database,
411                    i64::from(*code),
412                    &format!("Can't {action}: {message}"),
413                );
414            }
415            DatabaseError::Runtime(message) => {
416                Log::error(Event::Database, format!("Can't {action}: {message}"));
417            }
418            DatabaseError::Logic(_) => {
419                Log::error(Event::Database, format!("Can't {action}"));
420            }
421            // `RegionNotFound` is the caller's to report.
422            DatabaseError::RegionNotFound(_) => {}
423        }
424    }
425
426    fn remove_existing(&mut self) -> DbResult<()> {
427        Log::warning(Event::Database, "Removing existing incompatible offline database");
428
429        self.discard_pending_accessed();
430        let filename = match &self.db {
431            Some(db) => db.path().unwrap_or("").to_owned(),
432            None => self.path.clone(),
433        };
434        self.db = None;
435
436        if !filename.is_empty() {
437            delete_file(&filename)?;
438        }
439        Ok(())
440    }
441
442    fn remove_old_cache_table(&mut self) -> DbResult<()> {
443        self.check_flags()?;
444        exec(self.get_db()?, "DROP TABLE IF EXISTS http_cache")?;
445        if self.autopack {
446            self.vacuum()?;
447        }
448        Ok(())
449    }
450
451    fn create_schema(&mut self) -> DbResult<()> {
452        self.check_flags()?;
453
454        self.vacuum()?;
455        let db = self.get_db()?;
456        exec(db, "PRAGMA journal_mode = DELETE")?;
457        exec(db, "PRAGMA synchronous = FULL")?;
458        self.with_transaction(Begin::Deferred, |this| {
459            let db = this.get_db()?;
460            exec(db, OFFLINE_DATABASE_SCHEMA)?;
461            exec(db, "PRAGMA user_version = 6")?;
462            Ok(())
463        })
464    }
465
466    fn migrate_to_version3(&mut self) -> DbResult<()> {
467        self.check_flags()?;
468        self.vacuum()?;
469        exec(self.get_db()?, "PRAGMA user_version = 3")?;
470        Ok(())
471    }
472
473    // Schema version 4 was WAL journal + NORMAL sync. It was reverted during
474    // pre-release development and the migration was removed entirely to
475    // avoid potential conflicts from quickly (and needlessly) switching
476    // journal and sync modes.
477    //
478    // See: https://github.com/mapbox/mapbox-gl-native/pull/6320
479
480    fn migrate_to_version5(&mut self) -> DbResult<()> {
481        self.check_flags()?;
482        let db = self.get_db()?;
483        exec(db, "PRAGMA journal_mode = DELETE")?;
484        exec(db, "PRAGMA synchronous = FULL")?;
485        exec(db, "PRAGMA user_version = 5")?;
486        Ok(())
487    }
488
489    fn migrate_to_version6(&mut self) -> DbResult<()> {
490        self.check_flags()?;
491        self.with_transaction(Begin::Deferred, |this| {
492            let db = this.get_db()?;
493            exec(db, "ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
494            exec(db, "ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
495            exec(db, "PRAGMA user_version = 6")?;
496            Ok(())
497        })
498    }
499
500    fn vacuum(&mut self) -> DbResult<()> {
501        self.check_flags()?;
502        if self.get_pragma_i64("PRAGMA auto_vacuum")? == 2 {
503            exec(self.get_db()?, "PRAGMA incremental_vacuum")?;
504        } else {
505            // A database without pages, such as a new one in memory, takes
506            // the setting with its first table, and has nothing to vacuum.
507            let empty = self.get_pragma_i64("PRAGMA page_count")? == 0;
508            let db = self.get_db()?;
509            exec(db, "PRAGMA auto_vacuum = INCREMENTAL")?;
510            if !empty {
511                exec(db, "VACUUM")?;
512            }
513        }
514        Ok(())
515    }
516
517    fn check_flags(&self) -> DbResult<()> {
518        if self.read_only {
519            return Err(DatabaseError::Runtime("Cannot modify database in read-only mode".to_owned()));
520        }
521        Ok(())
522    }
523
524    /// The connection, which opens the database if it isn't open.
525    fn get_db(&mut self) -> DbResult<&Connection> {
526        if self.db.is_none() {
527            self.initialize()?;
528        }
529        Ok(self.db.as_ref().expect("initialized database"))
530    }
531
532    /// Runs `sql`, a statement that returns no rows, with `params` bound;
533    /// returns the number of rows changed.
534    fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
535        let conn = self.get_db()?;
536        let mut stmt = conn.prepare_cached(sql)?;
537        Ok(stmt.execute(params)? as u64)
538    }
539
540    /// Runs `sql` with `params` bound and steps once: `f` reads the row,
541    /// `None` when there is none.
542    fn query_row<T>(
543        &mut self,
544        sql: &str,
545        params: impl rusqlite::Params,
546        f: impl FnOnce(&Row<'_>) -> DbResult<T>,
547    ) -> DbResult<Option<T>> {
548        let conn = self.get_db()?;
549        let mut stmt = conn.prepare_cached(sql)?;
550        let mut rows = stmt.query(params)?;
551        match rows.next()? {
552            None => Ok(None),
553            Some(row) => f(row).map(Some),
554        }
555    }
556
557    /// The row id of the last statement's insert.
558    fn last_insert_row_id(&mut self) -> DbResult<i64> {
559        let conn = self.get_db()?;
560        Ok(conn.last_insert_rowid())
561    }
562
563    /// Runs `f` in a transaction that commits after `f` succeeds and rolls
564    /// back when `f` fails.
565    fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
566        exec(self.get_db()?, begin.sql())?;
567        match f(self) {
568            Ok(value) => {
569                exec(self.get_db()?, "COMMIT TRANSACTION")?;
570                Ok(value)
571            }
572            Err(e) => {
573                // `f`'s error is the one to report, not a failed rollback's.
574                if let Some(db) = &self.db {
575                    let _ = exec(db, "ROLLBACK TRANSACTION");
576                }
577                Err(e)
578            }
579        }
580    }
581
582    fn get_pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
583        Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
584    }
585
586    /// The stored copy of `resource`, if any.
587    pub fn get(&mut self, resource: &Resource) -> Option<Response> {
588        let result = if self.disabled() { Ok(None) } else { self.get_internal(resource) };
589        self.report(result, "read resource").ok().flatten().map(|(response, _size)| response)
590    }
591
592    fn get_internal(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
593        let stored = Stored::of(resource);
594        let sql = format!(
595            "SELECT etag, modified, data, compressed, id, {} FROM {} WHERE {}",
596            CACHING_COLUMNS,
597            stored.table().name(),
598            stored.condition()
599        );
600        let Some((response, size, id)) = self.query_row(&sql, &*stored.params(), read_response)? else {
601            return Ok(None);
602        };
603        self.queue_accessed(stored.is_tile(), id);
604        if self.pending_accessed_count() >= MAX_PENDING_ACCESSED && !self.accessed_flush_failed {
605            self.flush_accessed();
606        }
607        if self.pending_accessed_count() > 0
608            && let Some(callback) = &mut self.accessed_callback
609        {
610            callback();
611        }
612        Ok(Some((response, size)))
613    }
614
615    /// The stored size and caching rules of the copy of `resource`; `None`
616    /// without one, or for a copy without data.
617    fn has_internal(&mut self, resource: &Resource) -> DbResult<Option<(u64, Caching)>> {
618        let stored = Stored::of(resource);
619        let sql = format!(
620            "SELECT length(data), {} FROM {} WHERE {}",
621            CACHING_COLUMNS,
622            stored.table().name(),
623            stored.condition()
624        );
625        let row = self.query_row(&sql, &*stored.params(), |row| {
626            let size: Option<i64> = row.get(0)?;
627            size.map(|size| Ok((size as u64, read_caching(row, 1)?))).transpose()
628        })?;
629        Ok(row.flatten())
630    }
631
632    /// `put(const Resource&, const Response&)`: (inserted, stored size). The ambient cache doesn't
633    /// keep a tile the tileset doesn't have (`Response::tile_not_found`), since it would read back as
634    /// an empty tile.
635    pub fn put(&mut self, resource: &Resource, response: &Response) -> (bool, u64) {
636        if self.read_only || response.tile_not_found {
637            return (false, 0);
638        }
639
640        let result = (|| -> DbResult<(bool, u64)> {
641            if self.disabled() {
642                return Ok((false, 0));
643            }
644
645            self.pending_applied_for_eviction = false;
646            let result = self.with_transaction(Begin::Immediate, |this| this.put_internal(resource, response, true))?;
647            if self.pending_applied_for_eviction {
648                self.discard_pending_accessed();
649            }
650            Ok(result)
651        })();
652        self.report(result, "write resource").unwrap_or((false, 0))
653    }
654
655    /// Stores `response` for `resource`, first making room in the ambient
656    /// cache when `evict` is set.
657    fn put_internal(&mut self, resource: &Resource, response: &Response, evict: bool) -> DbResult<(bool, u64)> {
658        self.check_flags()?;
659
660        // An error isn't stored, nor what the server forbids storing.
661        if response.error.is_some() || response.no_store {
662            return Ok((false, 0));
663        }
664
665        // An ambient cache with no room can't store anything, so skip compressing.
666        if evict && self.maximum_ambient_cache_size == 0 {
667            return Ok((false, 0));
668        }
669
670        // A copy the database has, as for a 304, only renews its caching
671        // rules.
672        let renews = renews(response);
673        let compressed = match &response.data {
674            Some(data) if !renews => {
675                Some(compress(data).map_err(DatabaseError::Runtime)?).filter(|c| c.len() < data.len())
676            }
677            _ => None,
678        };
679        let data = if renews {
680            &[]
681        } else {
682            compressed.as_deref().or(response.data.as_deref().map(Vec::as_slice)).unwrap_or_default()
683        };
684        let size = data.len() as u64;
685
686        let stats = if evict {
687            let stats = DatabaseSizeChangeStats::new(self)?;
688            if !self.evict(size, &stats, true)? {
689                Log::info(Event::Database, "Unable to make space for entry");
690                return Ok((false, 0));
691            }
692            Some(stats)
693        } else {
694            None
695        };
696
697        let inserted = self.write(&Stored::of(resource), response, data, compressed.is_some())?;
698
699        if let Some(stats) = stats {
700            self.update_ambient_cache_size(&stats)?;
701        }
702
703        Ok((inserted, size))
704    }
705
706    /// Writes `response`, with `data` as its stored bytes, to the row of
707    /// `stored`, and gives whether it added the row. A copy the database has
708    /// (`renews`) updates only its caching rules.
709    fn write(&mut self, stored: &Stored<'_>, response: &Response, data: &[u8], compressed: bool) -> DbResult<bool> {
710        let secs = |time: Option<Timestamp>| time.map(Timestamp::secs_since_epoch);
711        let (expires, modified) = (secs(response.caching.expires), secs(response.modified));
712        let accessed = now().secs_since_epoch();
713        // An empty body is an empty blob, and no content is NULL.
714        let data = (!response.no_content).then_some(data);
715        let compressed = compressed && data.is_some();
716
717        let mut columns: Vec<(&str, &dyn ToSql)> = vec![
718            ("accessed", &accessed),
719            ("expires", &expires),
720            ("must_revalidate", &response.caching.must_revalidate),
721        ];
722        let renews = renews(response);
723        if !renews {
724            columns.extend::<[(&str, &dyn ToSql); 4]>([
725                ("etag", &response.etag),
726                ("modified", &modified),
727                ("data", &data),
728                ("compressed", &compressed),
729            ]);
730            columns.extend(stored.content());
731        }
732        let key = stored.key();
733        let params: Vec<&dyn ToSql> = columns.iter().chain(&key).map(|(_, value)| *value).collect();
734
735        // Not REPLACE, which would change the row's id.
736        let assignments: Vec<String> = columns.iter().map(|(column, _)| format!("{column} = ?")).collect();
737        let table = stored.table().name();
738        let sql = format!("UPDATE {table} SET {} WHERE {}", assignments.join(", "), stored.condition());
739        if self.execute(&sql, &*params)? != 0 || renews {
740            return Ok(false);
741        }
742
743        let names: Vec<&str> = columns.iter().chain(&key).map(|(column, _)| *column).collect();
744        let sql = format!("INSERT INTO {table} ({}) VALUES ({})", names.join(", "), vec!["?"; names.len()].join(", "));
745        self.execute(&sql, &*params)?;
746        Ok(true)
747    }
748
749    /// Makes the ambient cache's copies stale, so maps revalidate them when
750    /// they next use them. See `invalidate`.
751    pub(crate) fn invalidate_ambient_cache(&mut self) -> DbResult<()> {
752        let result = self.invalidate(
753            "id NOT IN (SELECT tile_id FROM region_tiles)",
754            "id NOT IN (SELECT resource_id FROM region_resources)",
755            [],
756        );
757        self.report(result, "invalidate ambient cache")
758    }
759
760    /// Makes the region's copies stale, so maps revalidate them when they
761    /// next use them and its next download refreshes them. See `invalidate`.
762    pub fn invalidate_region(&mut self, region_id: i64) -> DbResult<()> {
763        let result = self.invalidate(
764            "id IN (SELECT tile_id FROM region_tiles WHERE region_id = ?1)",
765            "id IN (SELECT resource_id FROM region_resources WHERE region_id = ?1)",
766            params![region_id],
767        );
768        self.report(result, "invalidate region")
769    }
770
771    /// Makes the tiles and resources whose ids match the conditions stale
772    /// now. A copy that must revalidate then can't be used until it has.
773    fn invalidate(&mut self, tiles: &str, resources: &str, params: impl rusqlite::Params + Copy) -> DbResult<()> {
774        self.check_flags()?;
775        let now = now().secs_since_epoch();
776        for (table, ids) in [("tiles", tiles), ("resources", resources)] {
777            self.execute(
778                &format!("UPDATE {table} SET expires = MIN(IFNULL(expires, {now}), {now}) WHERE {ids}"),
779                params,
780            )?;
781        }
782        Ok(())
783    }
784
785    /// Clears the ambient cache, freeing space.
786    pub(crate) fn clear_ambient_cache(&mut self) -> DbResult<()> {
787        let result = (|| -> DbResult<()> {
788            self.check_flags()?;
789            // The deleted rows' ids may be reused.
790            self.discard_pending_accessed();
791
792            self.execute(
793                "DELETE FROM tiles \
794                 WHERE id NOT IN (\
795                     SELECT tile_id FROM region_tiles\
796                 )",
797                [],
798            )?;
799
800            self.execute(
801                "DELETE FROM resources \
802                 WHERE id NOT IN (\
803                     SELECT resource_id FROM region_resources\
804                 )",
805                [],
806            )?;
807
808            if self.autopack {
809                self.vacuum()?;
810            }
811            Ok(())
812        })();
813        self.report(result, "clear ambient cache")
814    }
815
816    /// Handles `result`'s error, if any (see `handle_error`), and passes
817    /// the result on.
818    fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
819        if let Err(e) = &result {
820            self.handle_error(e, action);
821        }
822        result
823    }
824
825    /// The regions that `sql` selects: their id, definition and description. A region whose
826    /// definition is malformed fails, or, with `skip_malformed`, is left out.
827    fn read_regions(
828        &mut self,
829        sql: &str,
830        params: impl rusqlite::Params,
831        skip_malformed: bool,
832    ) -> DbResult<OfflineRegions> {
833        let rows = {
834            let mut stmt = self.get_db()?.prepare_cached(sql)?;
835            let mut rows = stmt.query(params)?;
836            let mut result = Vec::new();
837            while let Some(row) = rows.next()? {
838                result.push((row.get(0)?, text_or_blob(row, 1)?, text_or_blob(row, 2)?));
839            }
840            result
841        };
842        let mut regions = OfflineRegions::new();
843        for (id, definition, metadata) in rows {
844            let definition = match decode_offline_region_definition(&definition) {
845                Ok(definition) => definition,
846                Err(e) if skip_malformed => {
847                    Log::error(Event::General, &e.message);
848                    continue;
849                }
850                Err(e) => return Err(e.into()),
851            };
852            regions.push(OfflineRegion { id, definition, metadata });
853        }
854        Ok(regions)
855    }
856
857    /// Every region whose definition can be read.
858    pub fn list_regions(&mut self) -> DbResult<OfflineRegions> {
859        let result = self.read_regions("SELECT id, definition, description FROM regions", [], true);
860        self.report(result, "list regions")
861    }
862
863    /// The region `region_id`, or `None` when the database has none.
864    pub fn get_region(&mut self, region_id: i64) -> DbResult<Option<OfflineRegion>> {
865        let sql = "SELECT id, definition, description FROM regions WHERE id = ?1";
866        let result = self.read_regions(sql, params![region_id], false).map(|regions| regions.into_iter().next());
867        self.report(result, "get region")
868    }
869
870    /// Creates a region without resources.
871    pub fn create_region(
872        &mut self,
873        definition: &OfflineRegionDefinition,
874        metadata: &OfflineRegionMetadata,
875    ) -> DbResult<OfflineRegion> {
876        let result = (|| -> DbResult<OfflineRegion> {
877            self.check_flags()?;
878            self.execute(
879                "INSERT INTO regions (definition, description) VALUES (?1, ?2)",
880                params![encode_offline_region_definition(definition), metadata_blob(metadata)],
881            )?;
882            Ok(OfflineRegion {
883                id: self.last_insert_row_id()?,
884                definition: definition.clone(),
885                metadata: metadata.clone(),
886            })
887        })();
888        self.report(result, "create region")
889    }
890
891    /// How long the region's stored resources stay usable.
892    pub fn get_region_expiry(&mut self, region_id: i64) -> DbResult<OfflineRegionExpiry> {
893        let result = (|| -> DbResult<OfflineRegionExpiry> {
894            let mut sql = Vec::new();
895            for table in [Table::Tiles, Table::Resources] {
896                let (name, (regions, id)) = (table.name(), table.regions());
897                sql.push(format!(
898                    "SELECT {CACHING_COLUMNS} FROM {regions} AS held JOIN {name} ON {name}.id = held.{id} \
899                     WHERE held.region_id = ?1"
900                ));
901            }
902            let now = now();
903            let mut expiry = OfflineRegionExpiry::default();
904            let mut stmt = self.get_db()?.prepare_cached(&sql.join(" UNION ALL "))?;
905            let mut rows = stmt.query(params![region_id])?;
906            while let Some(row) = rows.next()? {
907                let caching = read_caching(row, 0)?;
908                let earliest = |a: Option<Timestamp>, b: Option<Timestamp>| a.into_iter().chain(b).min();
909                expiry.stale_after = earliest(expiry.stale_after, caching.expires);
910                expiry.usable_offline_until = earliest(expiry.usable_offline_until, caching.usable_until());
911                expiry.stale_resource_count += u64::from(!caching.is_fresh(now));
912                expiry.unusable_resource_count += u64::from(!caching.is_usable(now));
913            }
914            Ok(expiry)
915        })();
916        self.report(result, "get region expiry")
917    }
918
919    pub fn merge_database(&mut self, side_database_path: &str) -> Result<OfflineRegions, DatabaseError> {
920        self.check_flags()?;
921
922        match self.execute("ATTACH DATABASE ?1 AS side", params![side_database_path]) {
923            Ok(_) => {}
924            Err(e @ DatabaseError::Sqlite { code, .. }) => {
925                Log::record(
926                    EventSeverity::Error,
927                    Event::Database,
928                    i64::from(code & 0xff),
929                    &format!("Can't attach database ({side_database_path}) for merge: {e}"),
930                );
931                return Err(e);
932            }
933            Err(e) => return Err(e),
934        }
935
936        let result = (|| -> DbResult<OfflineRegions> {
937            // A sideloaded database has the main database's version, 6.
938            let side_user_version = self.get_pragma_i64("PRAGMA side.user_version")?;
939            let main_user_version = self.get_pragma_i64("PRAGMA user_version")?;
940            if side_user_version != main_user_version {
941                return Err(DatabaseError::Runtime("Merge database has incorrect user_version".to_owned()));
942            }
943
944            self.with_transaction(Begin::Deferred, |this| {
945                exec(this.get_db()?, MERGE_SIDELOADED_DATABASE_SQL)?;
946                Ok(())
947            })?;
948
949            let sql = "SELECT DISTINCT r.id, r.definition, r.description FROM side.regions sr \
950                       JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description \
951                       ORDER BY r.id";
952            let result = self.read_regions(sql, [], false)?;
953            exec(self.get_db()?, "DETACH DATABASE side")?;
954            Ok(result)
955        })();
956
957        match result {
958            // `catch (const std::runtime_error& ex)`: everything but the
959            // logic errors, which propagate (side stays attached).
960            Err(e) if !matches!(e, DatabaseError::Logic(_)) => {
961                exec(self.get_db()?, "DETACH DATABASE side")?;
962                Log::error(Event::Database, e.to_string());
963                Err(e)
964            }
965            result => result,
966        }
967    }
968
969    pub fn update_metadata(
970        &mut self,
971        region_id: i64,
972        metadata: &OfflineRegionMetadata,
973    ) -> Result<OfflineRegionMetadata, DatabaseError> {
974        let result = (|| -> DbResult<OfflineRegionMetadata> {
975            self.check_flags()?;
976
977            self.execute(
978                "UPDATE regions SET description = ?1 \
979                 WHERE id = ?2",
980                params![metadata_blob(metadata), region_id],
981            )?;
982
983            Ok(metadata.clone())
984        })();
985        self.report(result, "update region metadata")
986    }
987
988    pub fn delete_region(&mut self, region: &OfflineRegion) -> DbResult<()> {
989        let result = (|| -> DbResult<()> {
990            self.check_flags()?;
991            // Eviction uses the stored timestamps if this fails.
992            self.flush_accessed();
993
994            self.execute("DELETE FROM regions WHERE id = ?", params![region.id])?;
995
996            let stats = DatabaseSizeChangeStats::new(self)?;
997            self.evict(0, &stats, false)?;
998            if self.autopack {
999                self.vacuum()?;
1000            }
1001            self.update_ambient_cache_size(&stats)?;
1002            Ok(())
1003        })();
1004        self.report(result, "delete region")
1005    }
1006
1007    /// The stored copy of `resource`, with its stored size, whether or not
1008    /// the ambient cache is enabled.
1009    pub fn get_region_resource(&mut self, resource: &Resource) -> Option<(Response, u64)> {
1010        let result = self.get_internal(resource);
1011        self.report(result, "read region resource").ok().flatten()
1012    }
1013
1014    /// The stored size and caching rules of the copy of `resource`; `None`
1015    /// without one, or for a copy without data.
1016    pub fn check_region_resource(&mut self, resource: &Resource) -> Option<(u64, Caching)> {
1017        let result = self.has_internal(resource);
1018        self.report(result, "query region resource").ok().flatten()
1019    }
1020
1021    pub fn put_region_resource(&mut self, region_id: i64, resource: &Resource, response: &Response) -> u64 {
1022        let result = (|| -> DbResult<u64> {
1023            self.check_flags()?;
1024
1025            if self.db.is_none() {
1026                self.initialize()?;
1027            }
1028            self.with_transaction(Begin::Deferred, |this| {
1029                this.put_region_resource_internal(region_id, resource, response)
1030            })
1031        })();
1032        result.unwrap_or_else(|e| {
1033            self.handle_error(&e, "write region resource");
1034            0
1035        })
1036    }
1037
1038    pub fn put_region_resources(
1039        &mut self,
1040        region_id: i64,
1041        resources: &[(Resource, Response)],
1042        status: &mut OfflineRegionStatus,
1043    ) {
1044        let result = (|| -> DbResult<()> {
1045            self.check_flags()?;
1046
1047            if self.db.is_none() {
1048                self.initialize()?;
1049            }
1050            // Accumulate all statistics locally first before adding them to
1051            // the OfflineRegionStatus object to ensure correctness when the
1052            // transaction fails.
1053            let mut completed_resource_count = 0u64;
1054            let mut completed_resource_size = 0u64;
1055            let mut completed_tile_count = 0u64;
1056            let mut completed_tile_size = 0u64;
1057
1058            self.with_transaction(Begin::Deferred, |this| {
1059                for (resource, response) in resources {
1060                    let resource_size = this.put_region_resource_internal(region_id, resource, response)?;
1061                    completed_resource_count += 1;
1062                    completed_resource_size += resource_size;
1063                    if resource.kind == Kind::Tile {
1064                        completed_tile_count += 1;
1065                        completed_tile_size += resource_size;
1066                    }
1067                }
1068                Ok(())
1069            })?;
1070
1071            status.completed_resource_count += completed_resource_count;
1072            status.completed_resource_size += completed_resource_size;
1073            status.completed_tile_count += completed_tile_count;
1074            status.completed_tile_size += completed_tile_size;
1075            Ok(())
1076        })();
1077        if let Err(e) = result {
1078            self.handle_error(&e, "write region resources");
1079        }
1080    }
1081
1082    fn put_region_resource_internal(
1083        &mut self,
1084        region_id: i64,
1085        resource: &Resource,
1086        response: &Response,
1087    ) -> DbResult<u64> {
1088        self.check_flags()?;
1089
1090        let mut size = self.put_internal(resource, response, false)?.1;
1091        if response.not_modified {
1092            // A 304 keeps the stored data, so report the size it takes up.
1093            size = self.has_internal(resource)?.map_or(0, |(stored, _)| stored);
1094        }
1095        self.mark_used(region_id, resource)?;
1096        Ok(size)
1097    }
1098
1099    /// Adds `resource`, which the database holds, to the region.
1100    fn mark_used(&mut self, region_id: i64, resource: &Resource) -> DbResult<()> {
1101        self.check_flags()?;
1102        let stored = Stored::of(resource);
1103        let table = stored.table();
1104        let (name, (regions, id)) = (table.name(), table.regions());
1105        let mut params: Vec<&dyn ToSql> = vec![&region_id];
1106        params.extend(stored.params());
1107        self.execute(
1108            &format!(
1109                "INSERT OR IGNORE INTO {regions} (region_id, {id}) SELECT ?, id FROM {name} WHERE {}",
1110                stored.condition()
1111            ),
1112            &*params,
1113        )?;
1114        Ok(())
1115    }
1116
1117    #[cfg(test)]
1118    pub(crate) fn get_region_definition(&mut self, region_id: i64) -> Result<OfflineRegionDefinition, DatabaseError> {
1119        let result = (|| -> DbResult<OfflineRegionDefinition> {
1120            // A missing region reads as an empty, malformed definition.
1121            let definition = self
1122                .query_row("SELECT definition FROM regions WHERE id = ?1", params![region_id], |row| {
1123                    text_or_blob(row, 0)
1124                })?
1125                .unwrap_or_default();
1126
1127            Ok(decode_offline_region_definition(&definition)?)
1128        })();
1129        self.report(result, "load region")
1130    }
1131
1132    /// The number and size of the resources that the region holds, tiles
1133    /// included, and of its tiles.
1134    pub fn get_region_completed_status(&mut self, region_id: i64) -> DbResult<OfflineRegionStatus> {
1135        let result = (|| -> DbResult<OfflineRegionStatus> {
1136            let mut status = OfflineRegionStatus::default();
1137            for table in [Table::Tiles, Table::Resources] {
1138                let (name, (regions, id)) = (table.name(), table.regions());
1139                let (count, size) = self
1140                    .query_row(
1141                        &format!(
1142                            "SELECT COUNT(*), IFNULL(SUM(LENGTH(data)), 0) FROM {regions} \
1143                             JOIN {name} ON {name}.id = {regions}.{id} WHERE region_id = ?1"
1144                        ),
1145                        params![region_id],
1146                        |row| Ok((row.get::<_, i64>(0)? as u64, row.get::<_, i64>(1)? as u64)),
1147                    )?
1148                    .unwrap_or_default();
1149                status.completed_resource_count += count;
1150                status.completed_resource_size += size;
1151                if let Table::Tiles = table {
1152                    status.completed_tile_count = count;
1153                    status.completed_tile_size = size;
1154                }
1155            }
1156            Ok(status)
1157        })();
1158        self.report(result, "get region status")
1159    }
1160
1161    // Remove least-recently used resources and tiles until the used database
1162    // size, as calculated by multiplying the number of in-use pages by the
1163    // page size, is less than the maximum cache size. Returns false if this
1164    // condition cannot be satisfied.
1165    //
1166    // SQLite database never shrinks in size unless we call VACUUM. We here
1167    // are monitoring the soft limit (i.e. number of free pages in the file)
1168    // and as it approaches to the hard limit (i.e. the actual file size) we
1169    // delete an arbitrary number of old cache entries. The free pages
1170    // approach saves us from calling VACUUM or keeping a running total,
1171    // which can be costly.
1172    //
1173    // `apply_accessed` (put only) writes the pending `accessed` timestamps in
1174    // the caller's transaction before choosing what to evict.
1175    fn evict(
1176        &mut self,
1177        needed_free_size: u64,
1178        stats: &DatabaseSizeChangeStats,
1179        apply_accessed: bool,
1180    ) -> DbResult<bool> {
1181        self.check_flags()?;
1182        let mut new_ambient_cache_size =
1183            self.ambient_cache_size()?.wrapping_add(needed_free_size).wrapping_add(stats.page_size());
1184
1185        if apply_accessed
1186            && new_ambient_cache_size > self.maximum_ambient_cache_size
1187            && self.pending_accessed_count() > 0
1188        {
1189            self.apply_pending_accessed()?;
1190            self.pending_applied_for_eviction = true;
1191        }
1192        while new_ambient_cache_size > self.maximum_ambient_cache_size {
1193            let accessed = self.query_row(
1194                "SELECT max(accessed) \
1195                 FROM ( \
1196                     SELECT accessed \
1197                     FROM resources \
1198                     LEFT JOIN region_resources \
1199                     ON resource_id = resources.id \
1200                     WHERE resource_id IS NULL \
1201                   UNION ALL \
1202                     SELECT accessed \
1203                     FROM tiles \
1204                     LEFT JOIN region_tiles \
1205                     ON tile_id = tiles.id \
1206                     WHERE tile_id IS NULL \
1207                   ORDER BY accessed ASC LIMIT ?1 \
1208                 ) ",
1209                params![50],
1210                |row| Ok(row.get::<_, Option<i64>>(0)?),
1211            )?;
1212            let Some(accessed) = accessed.flatten() else {
1213                return Ok(false);
1214            };
1215
1216            let resource_changes = self.execute(
1217                "DELETE FROM resources \
1218                 WHERE id IN ( \
1219                   SELECT id FROM resources \
1220                   LEFT JOIN region_resources \
1221                   ON resource_id = resources.id \
1222                   WHERE resource_id IS NULL \
1223                   AND accessed <= ?1 \
1224                 ) ",
1225                params![accessed],
1226            )?;
1227
1228            let tile_changes = self.execute(
1229                "DELETE FROM tiles \
1230                 WHERE id IN ( \
1231                   SELECT id FROM tiles \
1232                   LEFT JOIN region_tiles \
1233                   ON tile_id = tiles.id \
1234                   WHERE tile_id IS NULL \
1235                   AND accessed <= ?1 \
1236                 ) ",
1237                params![accessed],
1238            )?;
1239
1240            // Update current ambient cache size, based on how many bytes were
1241            // released.
1242            let released = stats.bytes_released(self)?;
1243            new_ambient_cache_size = (new_ambient_cache_size as i64).wrapping_sub(released as i64).max(0) as u64;
1244
1245            if resource_changes == 0 && tile_changes == 0 {
1246                return Ok(false);
1247            }
1248        }
1249
1250        Ok(true)
1251    }
1252
1253    /// The size of the ambient cache's rows, which it reads once and then
1254    /// keeps up to date.
1255    fn ambient_cache_size(&mut self) -> DbResult<u64> {
1256        if let Some(size) = self.current_ambient_cache_size {
1257            return Ok(size);
1258        }
1259        let size = self.query_row(
1260            "SELECT SUM(data) \
1261                 FROM ( \
1262                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1263                                + IFNULL(LENGTH(id), 0) \
1264                                + IFNULL(LENGTH(url_template), 0) \
1265                                + IFNULL(LENGTH(pixel_ratio), 0) \
1266                                + IFNULL(LENGTH(x), 0) \
1267                                + IFNULL(LENGTH(y), 0) \
1268                                + IFNULL(LENGTH(z), 0) \
1269                                + IFNULL(LENGTH(expires), 0) \
1270                                + IFNULL(LENGTH(modified), 0) \
1271                                + IFNULL(LENGTH(etag), 0) \
1272                                + IFNULL(LENGTH(compressed), 0) \
1273                                + IFNULL(LENGTH(accessed), 0) \
1274                                + IFNULL(LENGTH(must_revalidate), 0) \
1275                                ) as data \
1276                     FROM tiles \
1277                     LEFT JOIN region_tiles \
1278                     ON tile_id = tiles.id \
1279                     WHERE tile_id IS NULL \
1280                   UNION ALL \
1281                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1282                                + IFNULL(LENGTH(id), 0) \
1283                                + IFNULL(LENGTH(url), 0) \
1284                                + IFNULL(LENGTH(kind), 0) \
1285                                + IFNULL(LENGTH(expires), 0) \
1286                                + IFNULL(LENGTH(modified), 0) \
1287                                + IFNULL(LENGTH(etag), 0) \
1288                                + IFNULL(LENGTH(compressed), 0) \
1289                                + IFNULL(LENGTH(accessed), 0) \
1290                                + IFNULL(LENGTH(must_revalidate), 0) \
1291                                ) as data \
1292                     FROM resources \
1293                     LEFT JOIN region_resources \
1294                     ON resource_id = resources.id \
1295                     WHERE resource_id IS NULL \
1296                 ) ",
1297            [],
1298            |row| Ok(row.get::<_, Option<i64>>(0)?),
1299        )?;
1300        let size = size.flatten().unwrap_or(0) as u64;
1301        self.current_ambient_cache_size = Some(size);
1302        Ok(size)
1303    }
1304
1305    pub(crate) fn set_maximum_ambient_cache_size(&mut self, size: u64) -> DbResult<()> {
1306        // Eviction uses the stored timestamps if this fails.
1307        self.flush_accessed();
1308        let previous_maximum_ambient_cache_size = self.maximum_ambient_cache_size;
1309
1310        let result = (|| -> DbResult<()> {
1311            let current = self.ambient_cache_size()?;
1312            self.maximum_ambient_cache_size = size;
1313            if current > size {
1314                let stats = DatabaseSizeChangeStats::new(self)?;
1315                self.evict(0, &stats, false)?;
1316                if self.autopack {
1317                    self.vacuum()?;
1318                }
1319                self.update_ambient_cache_size(&stats)?;
1320            }
1321            Ok(())
1322        })();
1323        if result.is_err() {
1324            self.maximum_ambient_cache_size = previous_maximum_ambient_cache_size;
1325        }
1326        self.report(result, "set maximum ambient cache size")
1327    }
1328
1329    pub fn mark_used_resources(&mut self, region_id: i64, resources: &[Resource]) {
1330        let result = (|| -> DbResult<()> {
1331            if self.db.is_none() {
1332                self.initialize()?;
1333            }
1334            self.with_transaction(Begin::Deferred, |this| {
1335                for resource in resources {
1336                    this.mark_used(region_id, resource)?;
1337                }
1338                Ok(())
1339            })
1340        })();
1341        if let Err(e) = result {
1342            self.handle_error(&e, "mark resources as used");
1343        }
1344    }
1345
1346    pub(crate) fn pack(&mut self) -> DbResult<()> {
1347        let result = (|| -> DbResult<()> {
1348            if self.db.is_none() {
1349                self.initialize()?;
1350            }
1351            self.vacuum()
1352        })();
1353        self.report(result, "pack storage")
1354    }
1355
1356    #[cfg(test)]
1357    pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
1358        self.autopack = autopack;
1359    }
1360
1361    pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
1362        if self.read_only == read_only {
1363            return;
1364        }
1365        self.cleanup();
1366        self.read_only = read_only;
1367        if let Err(e) = self.initialize() {
1368            self.handle_error(&e, "reopen database read-only");
1369        }
1370    }
1371
1372    /// Deletes the database file and starts an empty one. Returns the error,
1373    /// if any.
1374    pub(crate) fn reset_database(&mut self) -> DbResult<()> {
1375        let result = self.remove_existing().and_then(|()| self.initialize());
1376        self.report(result, "reset database")
1377    }
1378
1379    fn update_ambient_cache_size(&mut self, stats: &DatabaseSizeChangeStats) -> DbResult<()> {
1380        debug_assert!(self.current_ambient_cache_size.is_some());
1381        if let Some(current) = self.current_ambient_cache_size {
1382            let diff = stats.diff(self)?;
1383            self.current_ambient_cache_size = Some((current as i64).wrapping_add(diff).max(0) as u64);
1384        }
1385        Ok(())
1386    }
1387}
1388
1389/// How a transaction takes its locks.
1390#[derive(Clone, Copy)]
1391enum Begin {
1392    Deferred,
1393    Immediate,
1394}
1395
1396impl Begin {
1397    fn sql(self) -> &'static str {
1398        match self {
1399            Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
1400            Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
1401        }
1402    }
1403}
1404
1405/// Runs every statement of `sql` to completion, as `sqlite3_exec` does.
1406/// rusqlite's `execute_batch` steps each statement only once, which leaves
1407/// e.g. `PRAGMA incremental_vacuum` after freeing one page.
1408fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
1409    use rusqlite::fallible_iterator::FallibleIterator as _;
1410
1411    let mut batch = rusqlite::Batch::new(conn, sql);
1412    while let Some(mut stmt) = batch.next()? {
1413        let mut rows = stmt.raw_query();
1414        while rows.next()?.is_some() {}
1415    }
1416    Ok(())
1417}
1418
1419/// The bytes of a TEXT or BLOB column, such as a region's definition and
1420/// metadata; empty for NULL.
1421fn text_or_blob(row: &Row<'_>, index: usize) -> DbResult<Vec<u8>> {
1422    Ok(row.get_ref(index)?.as_bytes_or_null()?.unwrap_or_default().to_vec())
1423}
1424
1425/// The metadata as a blob to bind. Empty metadata is stored as NULL.
1426fn metadata_blob(metadata: &OfflineRegionMetadata) -> Option<&[u8]> {
1427    if metadata.is_empty() { None } else { Some(metadata.as_slice()) }
1428}
1429
1430/// A table of copies.
1431#[derive(Clone, Copy)]
1432enum Table {
1433    Tiles,
1434    Resources,
1435}
1436
1437impl Table {
1438    fn name(self) -> &'static str {
1439        match self {
1440            Table::Tiles => "tiles",
1441            Table::Resources => "resources",
1442        }
1443    }
1444
1445    /// The table that links the copies to the regions that hold them, and
1446    /// its column for a copy's id.
1447    fn regions(self) -> (&'static str, &'static str) {
1448        match self {
1449            Table::Tiles => ("region_tiles", "tile_id"),
1450            Table::Resources => ("region_resources", "resource_id"),
1451        }
1452    }
1453}
1454
1455/// Where the database stores a resource's copy: a tile by its tileset and
1456/// coordinates in `tiles`, another resource by its cache key in `resources`.
1457enum Stored<'a> {
1458    Tile(&'a TileData),
1459    Resource { url: String, kind: i32 },
1460}
1461
1462impl<'a> Stored<'a> {
1463    fn of(resource: &'a Resource) -> Self {
1464        match tile_data(resource) {
1465            Some(tile) => Stored::Tile(tile),
1466            None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
1467        }
1468    }
1469
1470    fn is_tile(&self) -> bool {
1471        matches!(self, Stored::Tile(_))
1472    }
1473
1474    fn table(&self) -> Table {
1475        if self.is_tile() { Table::Tiles } else { Table::Resources }
1476    }
1477
1478    /// The columns that identify the row, with their values, in the order of
1479    /// `condition`'s parameters.
1480    fn key(&self) -> Vec<(&'static str, &dyn ToSql)> {
1481        match self {
1482            Stored::Tile(tile) => vec![
1483                ("url_template", &tile.url_template),
1484                ("pixel_ratio", &tile.pixel_ratio),
1485                ("x", &tile.x),
1486                ("y", &tile.y),
1487                ("z", &tile.z),
1488            ],
1489            Stored::Resource { url, .. } => vec![("url", url)],
1490        }
1491    }
1492
1493    /// The condition that selects the row, over `params`.
1494    fn condition(&self) -> &'static str {
1495        if self.is_tile() { "url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?" } else { "url = ?" }
1496    }
1497
1498    fn params(&self) -> Vec<&dyn ToSql> {
1499        self.key().into_iter().map(|(_, value)| value).collect()
1500    }
1501
1502    /// The columns besides the response's that a write of new content sets.
1503    fn content(&self) -> Vec<(&'static str, &dyn ToSql)> {
1504        match self {
1505            Stored::Tile(_) => Vec::new(),
1506            Stored::Resource { kind, .. } => vec![("kind", kind)],
1507        }
1508    }
1509}
1510
1511/// Whether `response` brings a copy the database has: a 304, or the copy
1512/// the request carried, which a 304 delivered.
1513fn renews(response: &Response) -> bool {
1514    response.not_modified || response.prior
1515}
1516
1517/// Reads `etag, modified, data, compressed, id`, then the caching columns:
1518/// the response, its stored size, and its row id.
1519fn read_response(row: &Row<'_>) -> DbResult<(Response, u64, i64)> {
1520    let mut response = Response::new();
1521    let mut size = 0u64;
1522    response.etag = row.get(0)?;
1523    response.modified = row.get::<_, Option<i64>>(1)?.map(Timestamp::from_secs);
1524    match row.get_ref(2)?.as_bytes_or_null()? {
1525        None => response.no_content = true,
1526        Some(data) => {
1527            size = data.len() as u64;
1528            let data = if row.get(3)? { decompress(data).map_err(DatabaseError::Runtime)? } else { data.to_vec() };
1529            response.data = Some(Arc::new(data));
1530        }
1531    }
1532    response.caching = read_caching(row, 5)?;
1533    Ok((response, size, row.get(4)?))
1534}
1535
1536/// The columns that `read_caching` reads.
1537const CACHING_COLUMNS: &str = "expires, must_revalidate";
1538
1539/// Reads `CACHING_COLUMNS` from column `start` on.
1540fn read_caching(row: &Row<'_>, start: usize) -> DbResult<Caching> {
1541    Ok(Caching {
1542        expires: row.get::<_, Option<i64>>(start)?.map(Timestamp::from_secs),
1543        must_revalidate: row.get(start + 1)?,
1544    })
1545}
1546// The cached value of offlineTileCount does not need to be
1547// updated here because only non-offline tiles can be removed by
1548// eviction.