Skip to main content

mln_storage/
offline_database.rs

1// Ports platform/default/include/mln/storage/offline_database.hpp and
2// platform/default/src/mln/storage/offline_database.cpp.
3//
4// Failures are `DatabaseError`s, returned through `Result` and handled by
5// `handle_error`. `put_region_resource(s)` handle their errors themselves.
6//
7// Prepared statements are rusqlite's per-connection statement cache
8// (`prepare_cached`) instead of the `statements` map; both are dropped with
9// the connection.
10//
11// Port-only (maplibre/maplibre-native#4748): a cache hit queues its row's
12// `accessed` timestamp instead of writing it in a transaction of its own.
13// The owner flushes the queue (`flush_accessed`, see `set_accessed_callback`);
14// closing the database, changing its path, reopening it read-only, resizing
15// the cache, deleting a region and a full queue flush it too, and `put`'s
16// eviction writes it in its own transaction.
17
18use std::collections::BTreeMap;
19use std::sync::Arc;
20
21use mln_util::chrono::{Timestamp, now};
22use mln_util::compression::{compress, decompress};
23use mln_util::constants::DEFAULT_MAX_CACHE_SIZE;
24use mln_util::error::{Error, ErrorKind};
25use mln_util::logging::{Event, EventSeverity, Log};
26use rusqlite::params;
27
28use crate::merge_sideloaded::MERGE_SIDELOADED_DATABASE_SQL;
29use crate::offline::{
30    OfflineRegion, OfflineRegionDefinition, OfflineRegionMetadata, OfflineRegionStatus, OfflineRegions,
31    decode_offline_region_definition, encode_offline_region_definition,
32};
33use crate::offline_schema::OFFLINE_DATABASE_SCHEMA;
34use crate::resource::{Kind, Resource, TileData};
35use crate::response::Response;
36use crate::sqlite3::{
37    self, Database, OpenFlag, SqliteError, Transaction, TransactionMode, extended_result_code, get_bool, get_bytes,
38    get_i64, get_optional_bytes, get_optional_i64, get_optional_string, result_code,
39};
40
41/// The most rows whose `accessed` timestamp waits to be written. Reads of
42/// other rows while the queue is full don't update their timestamps.
43pub const MAX_PENDING_ACCESSED: usize = 4096;
44
45/// Why a database operation failed.
46#[derive(Clone, Debug, thiserror::Error)]
47pub enum DatabaseError {
48    #[error(transparent)]
49    Sqlite(#[from] SqliteError),
50    /// A file operation failed with the OS error `code`.
51    #[error("{message}")]
52    Io { code: i32, message: String },
53    /// The operation failed, such as on a malformed region definition in the
54    /// database.
55    #[error("{0}")]
56    Runtime(String),
57    /// An argument was invalid, such as a region definition's zoom range.
58    #[error("{0}")]
59    Logic(String),
60    /// The database has no offline region with this ID.
61    #[error("no offline region has ID {0}")]
62    RegionNotFound(i64),
63}
64
65impl From<rusqlite::Error> for DatabaseError {
66    fn from(e: rusqlite::Error) -> Self {
67        DatabaseError::Sqlite(e.into())
68    }
69}
70
71impl From<Error> for DatabaseError {
72    fn from(e: Error) -> Self {
73        match e.kind {
74            ErrorKind::InvalidArgument => DatabaseError::Logic(e.message),
75            _ => DatabaseError::Runtime(e.message),
76        }
77    }
78}
79
80impl From<DatabaseError> for Error {
81    /// An invalid argument for [`DatabaseError::Logic`], not found for
82    /// [`DatabaseError::RegionNotFound`], and a native error otherwise.
83    fn from(error: DatabaseError) -> Self {
84        let kind = match error {
85            DatabaseError::Logic(_) => ErrorKind::InvalidArgument,
86            DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
87            _ => ErrorKind::Native,
88        };
89        Error::new(kind, error.to_string())
90    }
91}
92
93type DbResult<T> = Result<T, DatabaseError>;
94
95/// The tile data of a tile resource. C++ dereferences `resource.tileData`
96/// unchecked; a tile resource without it (built by hand) is stored and found
97/// by its URL here, as other resources are.
98fn tile_data(resource: &Resource) -> Option<&TileData> {
99    resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
100}
101
102/// `util::deleteFile` (src/mln/util/io.cpp).
103fn delete_file(filename: &str) -> DbResult<()> {
104    match std::fs::remove_file(filename) {
105        Ok(()) => Ok(()),
106        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
107        Err(e) => {
108            let code = e.raw_os_error().unwrap_or(0);
109            // IOException(err, msg): msg + ": " + std::generic_category().message(err)
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/// `OfflineDatabase::DatabaseSizeChangeStats`: the database size (pages in
118/// use) when it was created. The C++ object keeps a pointer to the
119/// database; here the database is passed to the methods that query it.
120struct DatabaseSizeChangeStats {
121    page_size: u64,
122    page_count: u64,
123    initial_size: u64,
124}
125
126impl DatabaseSizeChangeStats {
127    fn new(db: &mut OfflineDatabase) -> DbResult<Self> {
128        let page_size = db.get_pragma_i64("PRAGMA page_size")? as u64;
129        let page_count = db.get_pragma_i64("PRAGMA page_count")? as u64;
130        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
131        let initial_size = page_size.wrapping_mul(page_count.wrapping_sub(freelist_count as u64));
132        Ok(DatabaseSizeChangeStats { page_size, page_count, initial_size })
133    }
134
135    /// Returns difference between current database size and database size at
136    /// the time of creation of this object.
137    fn diff(&self, db: &mut OfflineDatabase) -> DbResult<i64> {
138        let page_count = db.get_pragma_i64("PRAGMA page_count")?;
139        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
140        let current_size = (self.page_size as i64).wrapping_mul(page_count.wrapping_sub(freelist_count));
141        Ok(current_size.wrapping_sub(self.initial_size as i64))
142    }
143
144    /// Returns how many bytes were released comparing to a database size at
145    /// the time of creation of this object.
146    fn bytes_released(&self, db: &mut OfflineDatabase) -> DbResult<u64> {
147        let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
148        let current_size = self.page_size.wrapping_mul(self.page_count.wrapping_sub(freelist_count as u64));
149        Ok((self.initial_size.wrapping_sub(current_size) as i64).max(0) as u64)
150    }
151
152    /// Returns page size for the database.
153    fn page_size(&self) -> u64 {
154        self.page_size
155    }
156}
157
158/// `OfflineDatabase`.
159pub struct OfflineDatabase {
160    path: String,
161    db: Option<Database>,
162
163    maximum_ambient_cache_size: u64,
164    current_ambient_cache_size: Option<u64>,
165
166    autopack: bool,
167    read_only: bool,
168
169    /// `accessed` timestamps (seconds) of cache hits not yet written, by
170    /// row id.
171    pending_resource_accessed: BTreeMap<i64, i64>,
172    pending_tile_accessed: BTreeMap<i64, i64>,
173    /// Set when `put`'s eviction wrote the pending timestamps in its
174    /// transaction, so they are dropped once it commits.
175    pending_applied_for_eviction: bool,
176    /// The last flush failed: a full queue waits for the next scheduled
177    /// flush instead of retrying on every read.
178    accessed_flush_failed: bool,
179    accessed_callback: Option<Box<dyn FnMut() + Send>>,
180}
181
182impl Drop for OfflineDatabase {
183    fn drop(&mut self) {
184        self.cleanup();
185    }
186}
187
188impl OfflineDatabase {
189    /// Single-point transformer for offline storage keys. For sources where
190    /// the URL is not enough to guarantee uniqueness (eg. PMTiles where all
191    /// requests resolve to the same URL), this function creates a synthetic
192    /// key based on the requested data range.
193    #[must_use]
194    pub fn cache_key(resource: &Resource) -> String {
195        let Some((first, second)) = resource.data_range else {
196            return resource.url.clone();
197        };
198        let sep = if resource.url.contains('?') { '&' } else { '?' };
199        format!("{}{}_mlnRange={}-{}", resource.url, sep, first, second)
200    }
201
202    /// `OfflineDatabase(std::string path)`.
203    pub fn new(path: impl Into<String>) -> Self {
204        let mut db = OfflineDatabase {
205            path: path.into(),
206            db: None,
207            maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
208            current_ambient_cache_size: None,
209            autopack: true,
210            read_only: false,
211            pending_resource_accessed: BTreeMap::new(),
212            pending_tile_accessed: BTreeMap::new(),
213            pending_applied_for_eviction: false,
214            accessed_flush_failed: false,
215            accessed_callback: None,
216        };
217        if let Err(e) = db.initialize() {
218            db.handle_error(&e, "open database");
219        }
220        // Assume that we can't open the database right now and work with an
221        // empty database object.
222        db
223    }
224
225    fn initialize(&mut self) -> DbResult<()> {
226        assert!(self.db.is_none());
227
228        if self.read_only {
229            let db = Database::open(&self.path, OpenFlag::ReadOnly)?;
230            self.db = Some(db);
231            let db = self.db.as_ref().unwrap();
232            db.set_busy_timeout(i64::MAX)?;
233            db.exec("PRAGMA foreign_keys = ON")?;
234            return Ok(());
235        }
236
237        let db = Database::open(&self.path, OpenFlag::ReadWriteCreate)?;
238        self.db = Some(db);
239        {
240            let db = self.db.as_ref().unwrap();
241            db.set_busy_timeout(i64::MAX)?;
242            db.exec("PRAGMA foreign_keys = ON")?;
243        }
244
245        let user_version = self.get_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    /// `changePath`.
277    pub fn change_path(&mut self, path: &str) {
278        Log::info(Event::Database, "Changing the database path.");
279        self.cleanup();
280        self.path = path.to_owned();
281        if let Err(e) = self.initialize() {
282            // C++ lets this propagate to the caller (the database thread).
283            self.handle_error(&e, "open database");
284        }
285    }
286
287    fn cleanup(&mut self) {
288        self.flush_accessed();
289        self.discard_pending_accessed();
290        // Deleting these SQLite objects may result in exceptions (rusqlite
291        // closes on drop and ignores the result).
292        self.db = None;
293    }
294
295    /// Sets the callback that runs after a cache hit leaves `accessed`
296    /// timestamps waiting to be written; the owner then calls
297    /// [`flush_accessed`](Self::flush_accessed) later. It runs inside `get`
298    /// and `get_region_resource`, so it must not use this database.
299    pub fn set_accessed_callback(&mut self, callback: Box<dyn FnMut() + Send>) {
300        self.accessed_callback = Some(callback);
301    }
302
303    /// The number of rows whose `accessed` timestamp waits to be written.
304    #[must_use]
305    pub fn pending_accessed_count(&self) -> usize {
306        self.pending_resource_accessed.len() + self.pending_tile_accessed.len()
307    }
308
309    /// Writes the waiting `accessed` timestamps in one transaction, never
310    /// moving a row's timestamp back. Returns false and keeps them waiting
311    /// when that fails or the database is read-only or closed.
312    pub fn flush_accessed(&mut self) -> bool {
313        if self.pending_accessed_count() == 0 {
314            return true;
315        }
316        if self.read_only || self.db.is_none() {
317            return false;
318        }
319        match self.with_transaction(TransactionMode::Immediate, Self::apply_pending_accessed) {
320            Ok(()) => {
321                self.discard_pending_accessed();
322                true
323            }
324            Err(e) => {
325                self.accessed_flush_failed = true;
326                self.handle_error(&e, "flush accessed timestamps");
327                false
328            }
329        }
330    }
331
332    fn discard_pending_accessed(&mut self) {
333        self.pending_resource_accessed.clear();
334        self.pending_tile_accessed.clear();
335        self.accessed_flush_failed = false;
336    }
337
338    /// Runs the `accessed` updates in the open transaction.
339    fn apply_pending_accessed(&mut self) -> DbResult<()> {
340        self.get_db()?;
341        let Some(db) = &self.db else {
342            return Ok(());
343        };
344        let conn = db.conn();
345        for (sql, pending) in [
346            ("UPDATE resources SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_resource_accessed),
347            ("UPDATE tiles SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_tile_accessed),
348        ] {
349            if pending.is_empty() {
350                continue;
351            }
352            let mut stmt = conn.prepare_cached(sql)?;
353            for (id, accessed) in pending {
354                stmt.execute(params![accessed, id])?;
355            }
356        }
357        Ok(())
358    }
359
360    /// Queues the `accessed` timestamp of a cache hit, used for LRU
361    /// eviction.
362    fn queue_accessed(&mut self, tile: bool, id: i64) {
363        if self.read_only {
364            return;
365        }
366        let accessed = now().secs_since_epoch();
367        let full = self.pending_accessed_count() >= MAX_PENDING_ACCESSED;
368        let pending = if tile { &mut self.pending_tile_accessed } else { &mut self.pending_resource_accessed };
369        if let Some(existing) = pending.get_mut(&id) {
370            *existing = (*existing).max(accessed);
371        } else if !full {
372            pending.insert(id, accessed);
373        }
374    }
375
376    fn disabled(&mut self) -> bool {
377        if self.maximum_ambient_cache_size != 0 {
378            return false;
379        }
380
381        let regions = self.list_regions();
382        regions.map_or(true, |regions| regions.is_empty())
383    }
384
385    fn handle_error(&mut self, error: &DatabaseError, action: &str) {
386        match error {
387            DatabaseError::Sqlite(ex) => {
388                if ex.code == result_code::NOT_A_DB
389                    || ex.code == result_code::CORRUPT
390                    || (ex.code == result_code::READ_ONLY
391                        && ex.extended_code == extended_result_code::READ_ONLY_DB_MOVED)
392                {
393                    // The database was corruped, moved away, or deleted.
394                    // We're going to start fresh with a clean slate for the
395                    // next operation.
396                    Log::record(
397                        EventSeverity::Error,
398                        Event::Database,
399                        i64::from(ex.code),
400                        &format!("Can't {action}: {}", ex.message),
401                    );
402                    if let Err(io_ex) = self.remove_existing() {
403                        self.handle_error(&io_ex, action);
404                    }
405                } else {
406                    // We treat the error as temporary, and pretend we have an
407                    // inaccessible DB.
408                    Log::record(
409                        EventSeverity::Warning,
410                        Event::Database,
411                        i64::from(ex.code),
412                        &format!("Can't {action}: {}", ex.message),
413                    );
414                }
415            }
416            DatabaseError::Io { code, message } => {
417                // We failed to delete the database file.
418                Log::record(
419                    EventSeverity::Error,
420                    Event::Database,
421                    i64::from(*code),
422                    &format!("Can't {action}: {message}"),
423                );
424            }
425            DatabaseError::Runtime(message) => {
426                Log::error(Event::Database, format!("Can't {action}: {message}"));
427            }
428            DatabaseError::Logic(_) => {
429                // C++: assert(false) in debug builds.
430                Log::error(Event::Database, format!("Can't {action}"));
431            }
432            // `RegionNotFound` is the caller's to report.
433            DatabaseError::RegionNotFound(_) => {}
434        }
435    }
436
437    fn remove_existing(&mut self) -> DbResult<()> {
438        Log::warning(Event::Database, "Removing existing incompatible offline database");
439
440        self.discard_pending_accessed();
441        let filename = match &self.db {
442            Some(db) => db.get_filename(),
443            None => self.path.clone(),
444        };
445        self.db = None;
446
447        if !filename.is_empty() {
448            delete_file(&filename)?;
449        }
450        Ok(())
451    }
452
453    fn remove_old_cache_table(&mut self) -> DbResult<()> {
454        self.check_flags()?;
455        self.get_db()?.exec("DROP TABLE IF EXISTS http_cache")?;
456        if self.autopack {
457            self.vacuum()?;
458        }
459        Ok(())
460    }
461
462    fn create_schema(&mut self) -> DbResult<()> {
463        self.check_flags()?;
464
465        self.vacuum()?;
466        let db = self.get_db()?;
467        db.exec("PRAGMA journal_mode = DELETE")?;
468        db.exec("PRAGMA synchronous = FULL")?;
469        self.with_transaction(TransactionMode::Deferred, |this| {
470            let db = this.get_db()?;
471            db.exec(OFFLINE_DATABASE_SCHEMA)?;
472            db.exec("PRAGMA user_version = 6")?;
473            Ok(())
474        })
475    }
476
477    fn migrate_to_version3(&mut self) -> DbResult<()> {
478        self.check_flags()?;
479        self.vacuum()?;
480        self.get_db()?.exec("PRAGMA user_version = 3")?;
481        Ok(())
482    }
483
484    // Schema version 4 was WAL journal + NORMAL sync. It was reverted during
485    // pre-release development and the migration was removed entirely to
486    // avoid potential conflicts from quickly (and needlessly) switching
487    // journal and sync modes.
488    //
489    // See: https://github.com/mapbox/mapbox-gl-native/pull/6320
490
491    fn migrate_to_version5(&mut self) -> DbResult<()> {
492        self.check_flags()?;
493        let db = self.get_db()?;
494        db.exec("PRAGMA journal_mode = DELETE")?;
495        db.exec("PRAGMA synchronous = FULL")?;
496        db.exec("PRAGMA user_version = 5")?;
497        Ok(())
498    }
499
500    fn migrate_to_version6(&mut self) -> DbResult<()> {
501        self.check_flags()?;
502        self.with_transaction(TransactionMode::Deferred, |this| {
503            let db = this.get_db()?;
504            db.exec("ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
505            db.exec("ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
506            db.exec("PRAGMA user_version = 6")?;
507            Ok(())
508        })
509    }
510
511    fn vacuum(&mut self) -> DbResult<()> {
512        self.check_flags()?;
513        if self.get_pragma_i64("PRAGMA auto_vacuum")? == 2 {
514            self.get_db()?.exec("PRAGMA incremental_vacuum")?;
515        } else {
516            let db = self.get_db()?;
517            db.exec("PRAGMA auto_vacuum = INCREMENTAL")?;
518            db.exec("VACUUM")?;
519        }
520        Ok(())
521    }
522
523    fn check_flags(&self) -> DbResult<()> {
524        if self.read_only {
525            return Err(DatabaseError::Runtime("Cannot modify database in read-only mode".to_owned()));
526        }
527        Ok(())
528    }
529
530    /// `getStatement`'s `if (!db) initialize();`.
531    fn get_db(&mut self) -> DbResult<&Database> {
532        if self.db.is_none() {
533            self.initialize()?;
534        }
535        Ok(self.db.as_ref().expect("initialized database"))
536    }
537
538    /// `Query{getStatement(sql)}` with the parameters bound, then `run()`
539    /// on a statement that returns no rows; returns `changes()`.
540    fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
541        let conn = self.get_db()?.conn();
542        let mut stmt = conn.prepare_cached(sql)?;
543        Ok(stmt.execute(params)? as u64)
544    }
545
546    /// `Query{getStatement(sql)}` with the parameters bound and one `run()`:
547    /// `f` reads the row, `None` when there is none.
548    fn query_row<T>(
549        &mut self,
550        sql: &str,
551        params: impl rusqlite::Params,
552        f: impl FnOnce(&rusqlite::Row<'_>) -> DbResult<T>,
553    ) -> DbResult<Option<T>> {
554        let conn = self.get_db()?.conn();
555        let mut stmt = conn.prepare_cached(sql)?;
556        let mut rows = stmt.query(params)?;
557        match rows.next()? {
558            None => Ok(None),
559            Some(row) => f(row).map(Some),
560        }
561    }
562
563    /// `query.lastInsertRowId()` of the last statement.
564    fn last_insert_row_id(&mut self) -> DbResult<i64> {
565        let conn = self.get_db()?.conn();
566        Ok(conn.last_insert_rowid())
567    }
568
569    /// `mapbox::sqlite::Transaction transaction(*db, mode)` around `f`: the
570    /// transaction commits after `f` succeeds and rolls back (in its
571    /// destructor) when `f` fails.
572    fn with_transaction<T>(&mut self, mode: TransactionMode, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
573        let mut transaction = Transaction::new(self.get_db()?, mode)?;
574        let value = f(self)?;
575        transaction.commit()?;
576        Ok(value)
577    }
578
579    /// `getPragma<int64_t>(sql)`.
580    fn get_pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
581        Ok(self.query_row(sql, [], |row| Ok(sqlite3::get_i64(row, 0)?))?.unwrap_or(0))
582    }
583
584    /// `get(const Resource&)`.
585    pub fn get(&mut self, resource: &Resource) -> Option<Response> {
586        let result = (|| -> DbResult<Option<Response>> {
587            if self.disabled() {
588                return Ok(None);
589            }
590
591            let result = self.get_internal(resource)?;
592            Ok(result.map(|(response, _size)| response))
593        })();
594        match result {
595            Ok(response) => response,
596            Err(e) => {
597                self.handle_error(&e, "read resource");
598                None
599            }
600        }
601    }
602
603    fn get_internal(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
604        let result = if let Some(tile_data) = tile_data(resource) {
605            self.get_tile(tile_data)
606        } else {
607            self.get_resource(resource)
608        }?;
609        if self.pending_accessed_count() >= MAX_PENDING_ACCESSED && !self.accessed_flush_failed {
610            self.flush_accessed();
611        }
612        if result.is_some()
613            && self.pending_accessed_count() > 0
614            && let Some(callback) = &mut self.accessed_callback
615        {
616            callback();
617        }
618        Ok(result)
619    }
620
621    /// (stored size, whether the stored copy can be used without
622    /// revalidating it; see `Response::is_usable`).
623    fn has_internal(&mut self, resource: &Resource) -> DbResult<Option<(i64, bool)>> {
624        if let Some(tile_data) = tile_data(resource) { self.has_tile(tile_data) } else { self.has_resource(resource) }
625    }
626
627    /// `put(const Resource&, const Response&)`: (inserted, stored size). The ambient cache doesn't
628    /// keep a tile the tileset doesn't have (`Response::tile_not_found`), since it would read back as
629    /// an empty tile.
630    pub fn put(&mut self, resource: &Resource, response: &Response) -> (bool, u64) {
631        if self.read_only || response.tile_not_found {
632            return (false, 0);
633        }
634
635        let result = (|| -> DbResult<(bool, u64)> {
636            if self.db.is_none() {
637                self.initialize()?;
638            }
639
640            if self.disabled() {
641                return Ok((false, 0));
642            }
643
644            self.pending_applied_for_eviction = false;
645            let result =
646                self.with_transaction(TransactionMode::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        match result {
653            Ok(result) => result,
654            Err(e) => {
655                self.handle_error(&e, "write resource");
656                (false, 0)
657            }
658        }
659    }
660
661    fn put_internal(&mut self, resource: &Resource, response: &Response, evict: bool) -> DbResult<(bool, u64)> {
662        self.check_flags()?;
663
664        if response.error.is_some() {
665            return Ok((false, 0));
666        }
667
668        // An ambient cache with no room can't store anything, so skip compressing.
669        if evict && self.maximum_ambient_cache_size == 0 {
670            return Ok((false, 0));
671        }
672
673        let mut compressed_data = Vec::new();
674        let mut compressed = false;
675        let mut size = 0u64;
676
677        if let Some(data) = &response.data {
678            compressed_data = compress(data).map_err(DatabaseError::Runtime)?;
679            compressed = compressed_data.len() < data.len();
680            size = if compressed { compressed_data.len() } else { data.len() } as u64;
681        }
682
683        let mut stats = None;
684        if evict {
685            let s = DatabaseSizeChangeStats::new(self)?;
686            if !self.evict(size, &s, true)? {
687                Log::info(Event::Database, "Unable to make space for entry");
688                return Ok((false, 0));
689            }
690            stats = Some(s);
691        }
692
693        let data: &[u8] = if compressed {
694            &compressed_data
695        } else if let Some(data) = &response.data {
696            data
697        } else {
698            b""
699        };
700
701        let inserted = if let Some(tile_data) = tile_data(resource) {
702            self.put_tile(tile_data, response, data, compressed)?
703        } else {
704            self.put_resource(resource, response, data, compressed)?
705        };
706
707        if let Some(stats) = stats {
708            self.update_ambient_cache_size(&stats)?;
709        }
710
711        Ok((inserted, size))
712    }
713
714    /// Reads `etag, expires, must_revalidate, modified, data, compressed,
715    /// id` of the first row, as getResource/getTile do.
716    fn read_response(row: &rusqlite::Row<'_>) -> DbResult<(Response, u64, i64)> {
717        let mut response = Response::new();
718        let mut size = 0u64;
719
720        response.etag = get_optional_string(row, 0)?;
721        response.expires = get_optional_i64(row, 1)?.map(Timestamp::from_secs);
722        response.must_revalidate = get_bool(row, 2)?;
723        response.modified = get_optional_i64(row, 3)?.map(Timestamp::from_secs);
724
725        let data = get_optional_bytes(row, 4)?;
726        match data {
727            None => response.no_content = true,
728            Some(data) => {
729                if get_bool(row, 5)? {
730                    let decompressed = decompress(&data).map_err(DatabaseError::Runtime)?;
731                    response.data = Some(Arc::new(decompressed));
732                } else {
733                    response.data = Some(Arc::new(data.clone()));
734                }
735                size = data.len() as u64;
736            }
737        }
738
739        Ok((response, size, get_i64(row, 6)?))
740    }
741
742    fn get_resource(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
743        let key = Self::cache_key(resource);
744        let row = self.query_row(
745            //        0      1            2            3       4      5          6
746            "SELECT etag, expires, must_revalidate, modified, data, compressed, id \
747             FROM resources \
748             WHERE url = ?",
749            params![key],
750            Self::read_response,
751        )?;
752        Ok(row.map(|(response, size, id)| {
753            self.queue_accessed(false, id);
754            (response, size)
755        }))
756    }
757
758    fn has_resource(&mut self, resource: &Resource) -> DbResult<Option<(i64, bool)>> {
759        let key = Self::cache_key(resource);
760        Ok(self
761            .query_row(
762                "SELECT length(data), must_revalidate, expires FROM resources WHERE url = ?",
763                params![key],
764                Self::read_size_and_usable,
765            )?
766            .flatten())
767    }
768
769    /// Reads `length(data), must_revalidate, expires`, as hasResource/hasTile
770    /// do.
771    fn read_size_and_usable(row: &rusqlite::Row<'_>) -> DbResult<Option<(i64, bool)>> {
772        let Some(size) = get_optional_i64(row, 0)? else {
773            return Ok(None);
774        };
775        let mut response = Response::new();
776        response.must_revalidate = get_bool(row, 1)?;
777        response.expires = get_optional_i64(row, 2)?.map(Timestamp::from_secs);
778        Ok(Some((size, response.is_usable())))
779    }
780
781    fn put_resource(
782        &mut self,
783        resource: &Resource,
784        response: &Response,
785        data: &[u8],
786        compressed: bool,
787    ) -> DbResult<bool> {
788        self.check_flags()?;
789
790        let key = Self::cache_key(resource);
791        let expires = response.expires.map(Timestamp::secs_since_epoch);
792        let modified = response.modified.map(Timestamp::secs_since_epoch);
793
794        if response.not_modified {
795            self.execute(
796                "UPDATE resources \
797                 SET accessed         = ?1, \
798                     expires          = ?2, \
799                     must_revalidate  = ?3 \
800                 WHERE url    = ?4 ",
801                params![now().secs_since_epoch(), expires, response.must_revalidate, key],
802            )?;
803            return Ok(false);
804        }
805
806        // `bindBlob(data.data(), data.size())`: an empty string is an empty
807        // blob, noContent is NULL.
808        let (data, compressed): (Option<&[u8]>, bool) =
809            if response.no_content { (None, false) } else { (Some(data), compressed) };
810
811        // We can't use REPLACE because it would change the id value.
812        let changes = self.execute(
813            "UPDATE resources \
814             SET kind            = ?1, \
815                 etag            = ?2, \
816                 expires         = ?3, \
817                 must_revalidate = ?4, \
818                 modified        = ?5, \
819                 accessed        = ?6, \
820                 data            = ?7, \
821                 compressed      = ?8 \
822             WHERE url           = ?9 ",
823            params![
824                resource.kind as i32,
825                response.etag,
826                expires,
827                response.must_revalidate,
828                modified,
829                now().secs_since_epoch(),
830                data,
831                compressed,
832                key
833            ],
834        )?;
835        if changes != 0 {
836            return Ok(false);
837        }
838
839        self.execute(
840            "INSERT INTO resources (url, kind, etag, expires, must_revalidate, modified, accessed, data, compressed) \
841             VALUES                (?1,  ?2,   ?3,   ?4,      ?5,              ?6,       ?7,       ?8,   ?9) ",
842            params![
843                key,
844                resource.kind as i32,
845                response.etag,
846                expires,
847                response.must_revalidate,
848                modified,
849                now().secs_since_epoch(),
850                data,
851                compressed
852            ],
853        )?;
854
855        Ok(true)
856    }
857
858    fn get_tile(&mut self, tile: &TileData) -> DbResult<Option<(Response, u64)>> {
859        let row = self.query_row(
860            //        0      1           2,            3,      4,      5,         6
861            "SELECT etag, expires, must_revalidate, modified, data, compressed, id \
862             FROM tiles \
863             WHERE url_template = ?1 \
864               AND pixel_ratio  = ?2 \
865               AND x            = ?3 \
866               AND y            = ?4 \
867               AND z            = ?5 ",
868            params![tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
869            Self::read_response,
870        )?;
871        Ok(row.map(|(response, size, id)| {
872            self.queue_accessed(true, id);
873            (response, size)
874        }))
875    }
876
877    fn has_tile(&mut self, tile: &TileData) -> DbResult<Option<(i64, bool)>> {
878        Ok(self
879            .query_row(
880                "SELECT length(data), must_revalidate, expires \
881                 FROM tiles \
882                 WHERE url_template = ?1 \
883                   AND pixel_ratio  = ?2 \
884                   AND x            = ?3 \
885                   AND y            = ?4 \
886                   AND z            = ?5 ",
887                params![tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
888                Self::read_size_and_usable,
889            )?
890            .flatten())
891    }
892
893    fn put_tile(&mut self, tile: &TileData, response: &Response, data: &[u8], compressed: bool) -> DbResult<bool> {
894        self.check_flags()?;
895
896        let expires = response.expires.map(Timestamp::secs_since_epoch);
897        let modified = response.modified.map(Timestamp::secs_since_epoch);
898
899        if response.not_modified {
900            self.execute(
901                "UPDATE tiles \
902                 SET accessed        = ?1, \
903                     expires         = ?2, \
904                     must_revalidate = ?3 \
905                 WHERE url_template  = ?4 \
906                   AND pixel_ratio   = ?5 \
907                   AND x             = ?6 \
908                   AND y             = ?7 \
909                   AND z             = ?8 ",
910                params![
911                    now().secs_since_epoch(),
912                    expires,
913                    response.must_revalidate,
914                    tile.url_template,
915                    tile.pixel_ratio,
916                    tile.x,
917                    tile.y,
918                    tile.z
919                ],
920            )?;
921            return Ok(false);
922        }
923
924        let (data, compressed): (Option<&[u8]>, bool) =
925            if response.no_content { (None, false) } else { (Some(data), compressed) };
926
927        // We can't use REPLACE because it would change the id value.
928        let changes = self.execute(
929            "UPDATE tiles \
930             SET modified        = ?1, \
931                 etag            = ?2, \
932                 expires         = ?3, \
933                 must_revalidate = ?4, \
934                 accessed        = ?5, \
935                 data            = ?6, \
936                 compressed      = ?7 \
937             WHERE url_template  = ?8 \
938               AND pixel_ratio   = ?9 \
939               AND x             = ?10 \
940               AND y             = ?11 \
941               AND z             = ?12 ",
942            params![
943                modified,
944                response.etag,
945                expires,
946                response.must_revalidate,
947                now().secs_since_epoch(),
948                data,
949                compressed,
950                tile.url_template,
951                tile.pixel_ratio,
952                tile.x,
953                tile.y,
954                tile.z
955            ],
956        )?;
957        if changes != 0 {
958            return Ok(false);
959        }
960
961        self.execute(
962            "INSERT INTO tiles (url_template, pixel_ratio, x,  y,  z,  modified, must_revalidate, etag, expires, accessed,  data, compressed) \
963             VALUES            (?1,           ?2,          ?3, ?4, ?5, ?6,       ?7,              ?8,   ?9,      ?10,       ?11,  ?12)",
964            params![
965                tile.url_template,
966                tile.pixel_ratio,
967                tile.x,
968                tile.y,
969                tile.z,
970                modified,
971                response.must_revalidate,
972                response.etag,
973                expires,
974                now().secs_since_epoch(),
975                data,
976                compressed
977            ],
978        )?;
979
980        Ok(true)
981    }
982
983    /// `invalidateAmbientCache()`: force revalidation of the ambient cache's
984    /// tiles and resources with the server before using them.
985    pub fn invalidate_ambient_cache(&mut self) -> Option<DatabaseError> {
986        let result = (|| -> DbResult<()> {
987            self.check_flags()?;
988
989            self.execute(
990                "UPDATE tiles \
991                 SET expires = 0, must_revalidate = 1 \
992                 WHERE id NOT IN (\
993                     SELECT tile_id FROM region_tiles\
994                 )",
995                [],
996            )?;
997
998            self.execute(
999                "UPDATE resources \
1000                 SET expires = 0, must_revalidate = 1 \
1001                 WHERE id NOT IN (\
1002                     SELECT resource_id FROM region_resources\
1003                 )",
1004                [],
1005            )?;
1006            Ok(())
1007        })();
1008        self.exception_ptr(result, "invalidate ambient cache")
1009    }
1010
1011    /// `clearAmbientCache()`: clear the tile cache, freeing resources.
1012    pub fn clear_ambient_cache(&mut self) -> Option<DatabaseError> {
1013        let result = (|| -> DbResult<()> {
1014            self.check_flags()?;
1015            // The deleted rows' ids may be reused.
1016            self.discard_pending_accessed();
1017
1018            self.execute(
1019                "DELETE FROM tiles \
1020                 WHERE id NOT IN (\
1021                     SELECT tile_id FROM region_tiles\
1022                 )",
1023                [],
1024            )?;
1025
1026            self.execute(
1027                "DELETE FROM resources \
1028                 WHERE id NOT IN (\
1029                     SELECT resource_id FROM region_resources\
1030                 )",
1031                [],
1032            )?;
1033
1034            if self.autopack {
1035                self.vacuum()?;
1036            }
1037            Ok(())
1038        })();
1039        self.exception_ptr(result, "clear ambient cache")
1040    }
1041
1042    /// `invalidateRegion(int64_t)`.
1043    pub fn invalidate_region(&mut self, region_id: i64) -> Option<DatabaseError> {
1044        let result = (|| -> DbResult<()> {
1045            self.check_flags()?;
1046
1047            self.execute(
1048                "UPDATE tiles \
1049                 SET expires = 0, must_revalidate = 1 \
1050                 WHERE id IN (\
1051                     SELECT tile_id FROM region_tiles WHERE region_id = ?\
1052                 )",
1053                params![region_id],
1054            )?;
1055
1056            self.execute(
1057                "UPDATE resources \
1058                 SET expires = 0, must_revalidate = 1 \
1059                 WHERE id IN (\
1060                     SELECT resource_id FROM region_resources WHERE region_id = ?\
1061                 )",
1062                params![region_id],
1063            )?;
1064            Ok(())
1065        })();
1066        self.exception_ptr(result, "invalidate region")
1067    }
1068
1069    /// The `try { ...; return nullptr; } catch (...) { handleError(action);
1070    /// return std::current_exception(); }` pattern.
1071    fn exception_ptr(&mut self, result: DbResult<()>, action: &str) -> Option<DatabaseError> {
1072        match result {
1073            Ok(()) => None,
1074            Err(e) => {
1075                self.handle_error(&e, action);
1076                Some(e)
1077            }
1078        }
1079    }
1080
1081    /// The `try { return ...; } catch (...) { handleError(action); return
1082    /// unexpected(std::current_exception()); }` pattern.
1083    fn expected<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
1084        if let Err(e) = &result {
1085            self.handle_error(e, action);
1086        }
1087        result
1088    }
1089
1090    /// `listRegions()`.
1091    pub fn list_regions(&mut self) -> Result<OfflineRegions, DatabaseError> {
1092        let result = (|| -> DbResult<OfflineRegions> {
1093            let rows = {
1094                let conn = self.get_db()?.conn();
1095                let mut stmt = conn.prepare_cached("SELECT id, definition, description FROM regions")?;
1096                let mut rows = stmt.query([])?;
1097                let mut result = Vec::new();
1098                while let Some(row) = rows.next()? {
1099                    result.push((get_i64(row, 0)?, get_bytes(row, 1)?, get_bytes(row, 2)?));
1100                }
1101                result
1102            };
1103            let mut result = OfflineRegions::new();
1104            for (id, definition, description) in rows {
1105                match decode_offline_region_definition(&definition) {
1106                    Ok(definition) => result.push(OfflineRegion::new(id, definition, description)),
1107                    Err(ex) => {
1108                        // Catch errors from malformed offline region
1109                        // definitions and skip them.
1110                        Log::error(Event::General, &ex.message);
1111                    }
1112                }
1113            }
1114            Ok(result)
1115        })();
1116        self.expected(result, "list regions")
1117    }
1118
1119    /// `getRegion(int64_t)`.
1120    pub fn get_region(&mut self, region_id: i64) -> Result<Option<OfflineRegion>, DatabaseError> {
1121        let result = (|| -> DbResult<Option<OfflineRegion>> {
1122            let row = self.query_row(
1123                "SELECT definition, description FROM regions WHERE id = ?1",
1124                params![region_id],
1125                |row| Ok((get_bytes(row, 0)?, get_bytes(row, 1)?)),
1126            )?;
1127            let Some((definition, description)) = row else {
1128                return Ok(None);
1129            };
1130
1131            if definition.is_empty() && description.is_empty() {
1132                return Err(DatabaseError::Runtime(format!("Region {region_id} not found in database")));
1133            }
1134
1135            Ok(Some(OfflineRegion::new(region_id, decode_offline_region_definition(&definition)?, description)))
1136        })();
1137        self.expected(result, "get region")
1138    }
1139
1140    /// `createRegion(const OfflineRegionDefinition&, const OfflineRegionMetadata&)`.
1141    pub fn create_region(
1142        &mut self,
1143        definition: &OfflineRegionDefinition,
1144        metadata: &OfflineRegionMetadata,
1145    ) -> Result<OfflineRegion, DatabaseError> {
1146        let result = (|| -> DbResult<OfflineRegion> {
1147            self.check_flags()?;
1148
1149            self.execute(
1150                "INSERT INTO regions (definition, description) \
1151                 VALUES              (?1,         ?2) ",
1152                params![encode_offline_region_definition(definition), metadata_blob(metadata)],
1153            )?;
1154            Ok(OfflineRegion::new(self.last_insert_row_id()?, definition.clone(), metadata.clone()))
1155        })();
1156        self.expected(result, "create region")
1157    }
1158
1159    /// `mergeDatabase(const std::string& sideDatabasePath)`.
1160    pub fn merge_database(&mut self, side_database_path: &str) -> Result<OfflineRegions, DatabaseError> {
1161        self.check_flags()?;
1162
1163        match self.execute("ATTACH DATABASE ?1 AS side", params![side_database_path]) {
1164            Ok(_) => {}
1165            Err(DatabaseError::Sqlite(ex)) => {
1166                Log::record(
1167                    EventSeverity::Error,
1168                    Event::Database,
1169                    i64::from(ex.code),
1170                    &format!("Can't attach database ({side_database_path}) for merge: {}", ex.message),
1171                );
1172                return Err(DatabaseError::Sqlite(ex));
1173            }
1174            Err(e) => return Err(e),
1175        }
1176
1177        let result = (|| -> DbResult<OfflineRegions> {
1178            // Support sideloaded databases at user_version = 6. Future schema
1179            // version changes will need to implement migration paths for
1180            // sideloaded databases at version 6.
1181            let side_user_version = self.get_pragma_i64("PRAGMA side.user_version")? as i32;
1182            let main_user_version = self.get_pragma_i64("PRAGMA user_version")?;
1183            if side_user_version < 6 || i64::from(side_user_version) != main_user_version {
1184                return Err(DatabaseError::Runtime("Merge database has incorrect user_version".to_owned()));
1185            }
1186
1187            self.with_transaction(TransactionMode::Deferred, |this| {
1188                this.get_db()?.exec(MERGE_SIDELOADED_DATABASE_SQL)?;
1189                Ok(())
1190            })?;
1191
1192            let rows = {
1193                let conn = self.get_db()?.conn();
1194                let mut stmt = conn.prepare_cached(
1195                    "SELECT DISTINCT r.id, r.definition, r.description \
1196                     FROM side.regions sr \
1197                     JOIN regions r ON sr.definition = r.definition  AND sr.description IS r.description",
1198                )?;
1199                let mut rows = stmt.query([])?;
1200                let mut result = Vec::new();
1201                while let Some(row) = rows.next()? {
1202                    result.push((get_i64(row, 0)?, get_bytes(row, 1)?, get_bytes(row, 2)?));
1203                }
1204                result
1205            };
1206            let mut result = OfflineRegions::new();
1207            for (id, definition, description) in rows {
1208                result.push(OfflineRegion::new(id, decode_offline_region_definition(&definition)?, description));
1209            }
1210            self.get_db()?.exec("DETACH DATABASE side")?;
1211            Ok(result)
1212        })();
1213
1214        match result {
1215            // `catch (const std::runtime_error& ex)`: everything but the
1216            // logic errors, which propagate (side stays attached).
1217            Err(e) if !matches!(e, DatabaseError::Logic(_)) => {
1218                self.get_db()?.exec("DETACH DATABASE side")?;
1219                Log::error(Event::Database, e.to_string());
1220                Err(e)
1221            }
1222            result => result,
1223        }
1224    }
1225
1226    /// `updateMetadata(int64_t, const OfflineRegionMetadata&)`.
1227    pub fn update_metadata(
1228        &mut self,
1229        region_id: i64,
1230        metadata: &OfflineRegionMetadata,
1231    ) -> Result<OfflineRegionMetadata, DatabaseError> {
1232        let result = (|| -> DbResult<OfflineRegionMetadata> {
1233            self.check_flags()?;
1234
1235            self.execute(
1236                "UPDATE regions SET description = ?1 \
1237                 WHERE id = ?2",
1238                params![metadata_blob(metadata), region_id],
1239            )?;
1240
1241            Ok(metadata.clone())
1242        })();
1243        self.expected(result, "update region metadata")
1244    }
1245
1246    /// `deleteRegion(OfflineRegion&&)`.
1247    pub fn delete_region(&mut self, region: &OfflineRegion) -> Option<DatabaseError> {
1248        let result = (|| -> DbResult<()> {
1249            self.check_flags()?;
1250            // Eviction uses the stored timestamps if this fails.
1251            self.flush_accessed();
1252
1253            self.execute("DELETE FROM regions WHERE id = ?", params![region.get_id()])?;
1254
1255            let stats = DatabaseSizeChangeStats::new(self)?;
1256            self.evict(0, &stats, false)?;
1257            if self.autopack {
1258                self.vacuum()?;
1259            }
1260            self.update_ambient_cache_size(&stats)?;
1261            Ok(())
1262        })();
1263        self.exception_ptr(result, "delete region")
1264    }
1265
1266    /// `getRegionResource(const Resource&)`: (response, stored size).
1267    pub fn get_region_resource(&mut self, resource: &Resource) -> Option<(Response, u64)> {
1268        match self.get_internal(resource) {
1269            Ok(result) => result,
1270            Err(e) => {
1271                self.handle_error(&e, "read region resource");
1272                None
1273            }
1274        }
1275    }
1276
1277    /// `hasRegionResource(const Resource&)`.
1278    pub fn has_region_resource(&mut self, resource: &Resource) -> Option<i64> {
1279        self.check_region_resource(resource).map(|(size, _)| size)
1280    }
1281
1282    /// `checkRegionResource(const Resource&)`: (stored size, whether the
1283    /// stored copy can be used without revalidating it; see
1284    /// `Response::is_usable`).
1285    pub fn check_region_resource(&mut self, resource: &Resource) -> Option<(i64, bool)> {
1286        match self.has_internal(resource) {
1287            Ok(result) => result,
1288            Err(e) => {
1289                self.handle_error(&e, "query region resource");
1290                None
1291            }
1292        }
1293    }
1294
1295    /// `putRegionResource(int64_t, const Resource&, const Response&)`.
1296    pub fn put_region_resource(&mut self, region_id: i64, resource: &Resource, response: &Response) -> u64 {
1297        let result = (|| -> DbResult<u64> {
1298            self.check_flags()?;
1299
1300            if self.db.is_none() {
1301                self.initialize()?;
1302            }
1303            self.with_transaction(TransactionMode::Deferred, |this| {
1304                this.put_region_resource_internal(region_id, resource, response)
1305            })
1306        })();
1307        result.unwrap_or_else(|e| {
1308            self.handle_error(&e, "write region resource");
1309            0
1310        })
1311    }
1312
1313    /// `putRegionResources(int64_t, const std::list<std::tuple<Resource,
1314    /// Response>>&, OfflineRegionStatus&)`.
1315    pub fn put_region_resources(
1316        &mut self,
1317        region_id: i64,
1318        resources: &[(Resource, Response)],
1319        status: &mut OfflineRegionStatus,
1320    ) {
1321        let result = (|| -> DbResult<()> {
1322            self.check_flags()?;
1323
1324            if self.db.is_none() {
1325                self.initialize()?;
1326            }
1327            let mut transaction = Transaction::new(self.get_db()?, TransactionMode::Deferred)?;
1328
1329            // Accumulate all statistics locally first before adding them to
1330            // the OfflineRegionStatus object to ensure correctness when the
1331            // transaction fails.
1332            let mut completed_resource_count = 0u64;
1333            let mut completed_resource_size = 0u64;
1334            let mut completed_tile_count = 0u64;
1335            let mut completed_tile_size = 0u64;
1336
1337            for (resource, response) in resources {
1338                let resource_size = self.put_region_resource_internal(region_id, resource, response)?;
1339                completed_resource_count += 1;
1340                completed_resource_size += resource_size;
1341                if resource.kind == Kind::Tile {
1342                    completed_tile_count += 1;
1343                    completed_tile_size += resource_size;
1344                }
1345            }
1346
1347            // Commit the completed batch
1348            transaction.commit()?;
1349
1350            status.completed_resource_count += completed_resource_count;
1351            status.completed_resource_size += completed_resource_size;
1352            status.completed_tile_count += completed_tile_count;
1353            status.completed_tile_size += completed_tile_size;
1354            Ok(())
1355        })();
1356        if let Err(e) = result {
1357            self.handle_error(&e, "write region resources");
1358        }
1359    }
1360
1361    fn put_region_resource_internal(
1362        &mut self,
1363        region_id: i64,
1364        resource: &Resource,
1365        response: &Response,
1366    ) -> DbResult<u64> {
1367        self.check_flags()?;
1368
1369        let mut size = self.put_internal(resource, response, false)?.1;
1370        if response.not_modified {
1371            // A 304 keeps the stored data, so report the size it takes up.
1372            size = self.has_internal(resource)?.map_or(0, |(stored, _)| stored as u64);
1373        }
1374        self.mark_used(region_id, resource)?;
1375        Ok(size)
1376    }
1377
1378    /// Adds `resource`, which the database holds, to the region.
1379    fn mark_used(&mut self, region_id: i64, resource: &Resource) -> DbResult<()> {
1380        self.check_flags()?;
1381
1382        if let Some(tile) = tile_data(resource) {
1383            self.execute(
1384                "INSERT OR IGNORE INTO region_tiles (region_id, tile_id) \
1385                 SELECT                              ?1,        tiles.id \
1386                 FROM tiles \
1387                 WHERE url_template = ?2 \
1388                   AND pixel_ratio  = ?3 \
1389                   AND x            = ?4 \
1390                   AND y            = ?5 \
1391                   AND z            = ?6 ",
1392                params![region_id, tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
1393            )?;
1394        } else {
1395            self.execute(
1396                "INSERT OR IGNORE INTO region_resources (region_id, resource_id) \
1397                 SELECT                                  ?1,        resources.id \
1398                 FROM resources \
1399                 WHERE resources.url = ?2 ",
1400                params![region_id, Self::cache_key(resource)],
1401            )?;
1402        }
1403        Ok(())
1404    }
1405
1406    /// `getRegionDefinition(int64_t)`.
1407    pub fn get_region_definition(&mut self, region_id: i64) -> Result<OfflineRegionDefinition, DatabaseError> {
1408        let result = (|| -> DbResult<OfflineRegionDefinition> {
1409            // `query.run(); query.get<std::string>(0)`: no row reads as "".
1410            let definition = self
1411                .query_row("SELECT definition FROM regions WHERE id = ?1", params![region_id], |row| {
1412                    Ok(get_bytes(row, 0)?)
1413                })?
1414                .unwrap_or_default();
1415
1416            Ok(decode_offline_region_definition(&definition)?)
1417        })();
1418        self.expected(result, "load region")
1419    }
1420
1421    /// `getRegionCompletedStatus(int64_t)`.
1422    pub fn get_region_completed_status(&mut self, region_id: i64) -> Result<OfflineRegionStatus, DatabaseError> {
1423        let result = (|| -> DbResult<OfflineRegionStatus> {
1424            let mut result = OfflineRegionStatus::default();
1425
1426            let (count, size) = self.get_completed_resource_count_and_size(region_id)?;
1427            result.completed_resource_count = count as u64;
1428            result.completed_resource_size = size as u64;
1429            let (count, size) = self.get_completed_tile_count_and_size(region_id)?;
1430            result.completed_tile_count = count as u64;
1431            result.completed_tile_size = size as u64;
1432
1433            result.completed_resource_count += result.completed_tile_count;
1434            result.completed_resource_size += result.completed_tile_size;
1435
1436            Ok(result)
1437        })();
1438        self.expected(result, "get region status")
1439    }
1440
1441    fn get_completed_resource_count_and_size(&mut self, region_id: i64) -> DbResult<(i64, i64)> {
1442        Ok(self
1443            .query_row(
1444                "SELECT COUNT(*), SUM(LENGTH(data)) \
1445                 FROM region_resources, resources \
1446                 WHERE region_id = ?1 \
1447                 AND resource_id = resources.id ",
1448                params![region_id],
1449                |row| Ok((get_i64(row, 0)?, get_i64(row, 1)?)),
1450            )?
1451            .unwrap_or_default())
1452    }
1453
1454    fn get_completed_tile_count_and_size(&mut self, region_id: i64) -> DbResult<(i64, i64)> {
1455        Ok(self
1456            .query_row(
1457                "SELECT COUNT(*), SUM(LENGTH(data)) \
1458                 FROM region_tiles, tiles \
1459                 WHERE region_id = ?1 \
1460                 AND tile_id = tiles.id ",
1461                params![region_id],
1462                |row| Ok((get_i64(row, 0)?, get_i64(row, 1)?)),
1463            )?
1464            .unwrap_or_default())
1465    }
1466
1467    // Remove least-recently used resources and tiles until the used database
1468    // size, as calculated by multiplying the number of in-use pages by the
1469    // page size, is less than the maximum cache size. Returns false if this
1470    // condition cannot be satisfied.
1471    //
1472    // SQLite database never shrinks in size unless we call VACUUM. We here
1473    // are monitoring the soft limit (i.e. number of free pages in the file)
1474    // and as it approaches to the hard limit (i.e. the actual file size) we
1475    // delete an arbitrary number of old cache entries. The free pages
1476    // approach saves us from calling VACUUM or keeping a running total,
1477    // which can be costly.
1478    //
1479    // `apply_accessed` (put only) writes the pending `accessed` timestamps in
1480    // the caller's transaction before choosing what to evict.
1481    fn evict(
1482        &mut self,
1483        needed_free_size: u64,
1484        stats: &DatabaseSizeChangeStats,
1485        apply_accessed: bool,
1486    ) -> DbResult<bool> {
1487        self.check_flags()?;
1488        let ambient_cache_size = if self.init_ambient_cache_size()?.is_none() {
1489            self.current_ambient_cache_size.expect("initialized ambient cache size")
1490        } else {
1491            self.maximum_ambient_cache_size
1492        };
1493        let mut new_ambient_cache_size =
1494            ambient_cache_size.wrapping_add(needed_free_size).wrapping_add(stats.page_size());
1495
1496        if apply_accessed
1497            && new_ambient_cache_size > self.maximum_ambient_cache_size
1498            && self.pending_accessed_count() > 0
1499        {
1500            self.apply_pending_accessed()?;
1501            self.pending_applied_for_eviction = true;
1502        }
1503        while new_ambient_cache_size > self.maximum_ambient_cache_size {
1504            let accessed = self.query_row(
1505                "SELECT max(accessed) \
1506                 FROM ( \
1507                     SELECT accessed \
1508                     FROM resources \
1509                     LEFT JOIN region_resources \
1510                     ON resource_id = resources.id \
1511                     WHERE resource_id IS NULL \
1512                   UNION ALL \
1513                     SELECT accessed \
1514                     FROM tiles \
1515                     LEFT JOIN region_tiles \
1516                     ON tile_id = tiles.id \
1517                     WHERE tile_id IS NULL \
1518                   ORDER BY accessed ASC LIMIT ?1 \
1519                 ) ",
1520                params![50],
1521                |row| Ok(get_i64(row, 0)?),
1522            )?;
1523            let Some(accessed) = accessed else {
1524                return Ok(false);
1525            };
1526
1527            let resource_changes = self.execute(
1528                "DELETE FROM resources \
1529                 WHERE id IN ( \
1530                   SELECT id FROM resources \
1531                   LEFT JOIN region_resources \
1532                   ON resource_id = resources.id \
1533                   WHERE resource_id IS NULL \
1534                   AND accessed <= ?1 \
1535                 ) ",
1536                params![accessed],
1537            )?;
1538
1539            let tile_changes = self.execute(
1540                "DELETE FROM tiles \
1541                 WHERE id IN ( \
1542                   SELECT id FROM tiles \
1543                   LEFT JOIN region_tiles \
1544                   ON tile_id = tiles.id \
1545                   WHERE tile_id IS NULL \
1546                   AND accessed <= ?1 \
1547                 ) ",
1548                params![accessed],
1549            )?;
1550
1551            // Update current ambient cache size, based on how many bytes were
1552            // released.
1553            let released = stats.bytes_released(self)?;
1554            new_ambient_cache_size = (new_ambient_cache_size as i64).wrapping_sub(released as i64).max(0) as u64;
1555
1556            // The cached value of offlineTileCount does not need to be
1557            // updated here because only non-offline tiles can be removed by
1558            // eviction.
1559            if resource_changes == 0 && tile_changes == 0 {
1560                return Ok(false);
1561            }
1562        }
1563
1564        Ok(true)
1565    }
1566
1567    /// Lazily initializes currentAmbientCacheSize. `Ok(Some(e))` is the
1568    /// returned `exception_ptr` (SQLite errors, handled); `Err` propagates.
1569    fn init_ambient_cache_size(&mut self) -> DbResult<Option<DatabaseError>> {
1570        if self.current_ambient_cache_size.is_none() {
1571            let size = self.query_row(
1572                "SELECT SUM(data) \
1573                 FROM ( \
1574                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1575                                + IFNULL(LENGTH(id), 0) \
1576                                + IFNULL(LENGTH(url_template), 0) \
1577                                + IFNULL(LENGTH(pixel_ratio), 0) \
1578                                + IFNULL(LENGTH(x), 0) \
1579                                + IFNULL(LENGTH(y), 0) \
1580                                + IFNULL(LENGTH(z), 0) \
1581                                + IFNULL(LENGTH(expires), 0) \
1582                                + IFNULL(LENGTH(modified), 0) \
1583                                + IFNULL(LENGTH(etag), 0) \
1584                                + IFNULL(LENGTH(compressed), 0) \
1585                                + IFNULL(LENGTH(accessed), 0) \
1586                                + IFNULL(LENGTH(must_revalidate), 0) \
1587                                ) as data \
1588                     FROM tiles \
1589                     LEFT JOIN region_tiles \
1590                     ON tile_id = tiles.id \
1591                     WHERE tile_id IS NULL \
1592                   UNION ALL \
1593                     SELECT SUM(IFNULL(LENGTH(data), 0) \
1594                                + IFNULL(LENGTH(id), 0) \
1595                                + IFNULL(LENGTH(url), 0) \
1596                                + IFNULL(LENGTH(kind), 0) \
1597                                + IFNULL(LENGTH(expires), 0) \
1598                                + IFNULL(LENGTH(modified), 0) \
1599                                + IFNULL(LENGTH(etag), 0) \
1600                                + IFNULL(LENGTH(compressed), 0) \
1601                                + IFNULL(LENGTH(accessed), 0) \
1602                                + IFNULL(LENGTH(must_revalidate), 0) \
1603                                ) as data \
1604                     FROM resources \
1605                     LEFT JOIN region_resources \
1606                     ON resource_id = resources.id \
1607                     WHERE resource_id IS NULL \
1608                 ) ",
1609                [],
1610                |row| Ok(get_i64(row, 0)?),
1611            );
1612            match size {
1613                Ok(size) => self.current_ambient_cache_size = Some(size.unwrap_or(0) as u64),
1614                Err(DatabaseError::Sqlite(ex)) => {
1615                    let e = DatabaseError::Sqlite(ex);
1616                    self.handle_error(&e, "cannot get current ambient cache size");
1617                    return Ok(Some(e));
1618                }
1619                Err(e) => return Err(e),
1620            }
1621        }
1622
1623        Ok(None)
1624    }
1625
1626    /// `setMaximumAmbientCacheSize(uint64_t)`.
1627    pub fn set_maximum_ambient_cache_size(&mut self, size: u64) -> Option<DatabaseError> {
1628        // Eviction uses the stored timestamps if this fails.
1629        self.flush_accessed();
1630        let previous_maximum_ambient_cache_size = self.maximum_ambient_cache_size;
1631
1632        // C++ lets errors other than SQLite's escape here; they are returned.
1633        match self.init_ambient_cache_size() {
1634            Ok(Some(exception)) | Err(exception) => return Some(exception),
1635            Ok(None) => {}
1636        }
1637
1638        let result = (|| -> DbResult<()> {
1639            self.maximum_ambient_cache_size = size;
1640
1641            if self.current_ambient_cache_size.expect("initialized ambient cache size")
1642                > self.maximum_ambient_cache_size
1643            {
1644                let stats = DatabaseSizeChangeStats::new(self)?;
1645                self.evict(0, &stats, false)?;
1646                if self.autopack {
1647                    self.vacuum()?;
1648                }
1649                self.update_ambient_cache_size(&stats)?;
1650            }
1651
1652            Ok(())
1653        })();
1654        match result {
1655            Ok(()) => None,
1656            Err(e) => {
1657                self.maximum_ambient_cache_size = previous_maximum_ambient_cache_size;
1658                self.handle_error(&e, "set maximum ambient cache size");
1659                Some(e)
1660            }
1661        }
1662    }
1663
1664    /// `markUsedResources(int64_t, const std::list<Resource>&)`.
1665    pub fn mark_used_resources(&mut self, region_id: i64, resources: &[Resource]) {
1666        let result = (|| -> DbResult<()> {
1667            if self.db.is_none() {
1668                self.initialize()?;
1669            }
1670            self.with_transaction(TransactionMode::Deferred, |this| {
1671                for resource in resources {
1672                    this.mark_used(region_id, resource)?;
1673                }
1674                Ok(())
1675            })
1676        })();
1677        if let Err(e) = result {
1678            self.handle_error(&e, "mark resources as used");
1679        }
1680    }
1681
1682    /// `pack()`.
1683    pub fn pack(&mut self) -> Option<DatabaseError> {
1684        let result = (|| -> DbResult<()> {
1685            if self.db.is_none() {
1686                self.initialize()?;
1687            }
1688            self.vacuum()
1689        })();
1690        self.exception_ptr(result, "pack storage")
1691    }
1692
1693    /// `runPackDatabaseAutomatically`.
1694    pub fn run_pack_database_automatically(&mut self, autopack: bool) {
1695        self.autopack = autopack;
1696    }
1697
1698    /// `reopenDatabaseReadOnly(bool)`.
1699    pub fn reopen_database_read_only(&mut self, read_only: bool) {
1700        if self.read_only == read_only {
1701            return;
1702        }
1703        self.cleanup();
1704        self.read_only = read_only;
1705        if let Err(e) = self.initialize() {
1706            self.handle_error(&e, "reopen database read-only");
1707        }
1708    }
1709
1710    /// `resetDatabase()`: C++ returns the exception (or null).
1711    pub fn reset_database(&mut self) -> Option<DatabaseError> {
1712        let result = self.remove_existing().and_then(|()| self.initialize());
1713        self.exception_ptr(result, "reset database")
1714    }
1715
1716    fn update_ambient_cache_size(&mut self, stats: &DatabaseSizeChangeStats) -> DbResult<()> {
1717        debug_assert!(self.current_ambient_cache_size.is_some());
1718        if let Some(current) = self.current_ambient_cache_size {
1719            let diff = stats.diff(self)?;
1720            self.current_ambient_cache_size = Some((current as i64).wrapping_add(diff).max(0) as u64);
1721        }
1722        Ok(())
1723    }
1724}
1725
1726/// `query.bindBlob(n, metadata)`: `sqlite3_bind_blob` with the vector's
1727/// `data()`, which is null for an empty vector, so empty metadata is stored
1728/// as NULL.
1729fn metadata_blob(metadata: &OfflineRegionMetadata) -> Option<&[u8]> {
1730    if metadata.is_empty() { None } else { Some(metadata.as_slice()) }
1731}