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