mln_engine/storage/offline_database/
mod.rs1mod regions;
15mod resources;
16mod schema;
17
18use std::collections::BTreeMap;
19
20use mln_style::error::{Error, ErrorKind};
21use rusqlite::types::FromSqlError;
22use rusqlite::{Connection, Row, ffi};
23
24use crate::log_target;
25use crate::storage::constants::DEFAULT_MAX_CACHE_SIZE;
26use crate::storage::resource::{Kind, Resource, TileData};
27
28pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;
31
32#[derive(Clone, Debug, thiserror::Error)]
34pub enum DatabaseError {
35 #[error("{message}")]
37 Sqlite { code: i32, message: String },
38 #[error("{message}")]
40 Io { code: i32, message: String },
41 #[error("{0}")]
44 Failed(String),
45 #[error("{0}")]
47 InvalidArgument(String),
48 #[error("no offline region has ID {0}")]
50 RegionNotFound(i64),
51}
52
53impl From<rusqlite::Error> for DatabaseError {
54 fn from(e: rusqlite::Error) -> Self {
55 let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
56 DatabaseError::Sqlite { code, message: e.to_string() }
57 }
58}
59
60impl From<FromSqlError> for DatabaseError {
61 fn from(e: FromSqlError) -> Self {
63 DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
64 }
65}
66
67impl From<Error> for DatabaseError {
68 fn from(e: Error) -> Self {
69 match e.kind {
70 ErrorKind::InvalidArgument => DatabaseError::InvalidArgument(e.message),
71 _ => DatabaseError::Failed(e.message),
72 }
73 }
74}
75
76impl From<DatabaseError> for Error {
77 fn from(error: DatabaseError) -> Self {
80 let kind = match error {
81 DatabaseError::InvalidArgument(_) => ErrorKind::InvalidArgument,
82 DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
83 _ => ErrorKind::Failed,
84 };
85 Error::new(kind, error.to_string())
86 }
87}
88
89type DbResult<T> = Result<T, DatabaseError>;
90
91fn delete_file(filename: &str) -> DbResult<()> {
92 match std::fs::remove_file(filename) {
93 Ok(()) => Ok(()),
94 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
95 Err(e) => {
96 let code = e.raw_os_error().unwrap_or(0);
97 let what = e.to_string();
98 let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
99 Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
100 }
101 }
102}
103
104pub struct OfflineDatabase {
105 path: String,
106 db: Option<Connection>,
107
108 maximum_ambient_cache_size: u64,
109 current_ambient_cache_size: Option<u64>,
110
111 autopack: bool,
112 read_only: bool,
113
114 pending_resource_accessed: BTreeMap<i64, i64>,
117 pending_tile_accessed: BTreeMap<i64, i64>,
118 pending_applied_for_eviction: bool,
121 accessed_flush_failed: bool,
124 accessed_callback: Option<Box<dyn FnMut() + Send>>,
125}
126
127impl Drop for OfflineDatabase {
128 fn drop(&mut self) {
129 self.cleanup();
130 }
131}
132
133impl OfflineDatabase {
134 pub fn new(path: impl Into<String>) -> Self {
137 let mut db = OfflineDatabase {
138 path: path.into(),
139 db: None,
140 maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
141 current_ambient_cache_size: None,
142 autopack: true,
143 read_only: false,
144 pending_resource_accessed: BTreeMap::new(),
145 pending_tile_accessed: BTreeMap::new(),
146 pending_applied_for_eviction: false,
147 accessed_flush_failed: false,
148 accessed_callback: None,
149 };
150 if let Err(e) = db.initialize() {
153 db.handle_error(&e, "open database");
154 }
155 db
156 }
157
158 #[cfg(test)]
159 pub(crate) fn change_path(&mut self, path: &str) {
160 tracing::info!(target: log_target::DATABASE, "Changing the database path.");
161 self.cleanup();
162 self.path = path.to_owned();
163 if let Err(e) = self.initialize() {
164 self.handle_error(&e, "open database");
165 }
166 }
167
168 fn cleanup(&mut self) {
169 self.flush_accessed();
170 self.discard_pending_accessed();
171 self.db = None;
172 }
173
174 fn disabled(&mut self) -> bool {
175 if self.maximum_ambient_cache_size != 0 {
176 return false;
177 }
178
179 let regions = self.list_regions();
180 regions.map_or(true, |regions| regions.is_empty())
181 }
182
183 fn handle_error(&mut self, error: &DatabaseError, action: &str) {
184 match error {
185 DatabaseError::Sqlite { code, message } => {
186 let primary_code = code & 0xff;
187 if primary_code == ffi::SQLITE_NOTADB
188 || primary_code == ffi::SQLITE_CORRUPT
189 || *code == ffi::SQLITE_READONLY_DBMOVED
190 {
191 tracing::error!(
195 target: log_target::DATABASE,
196 code = i64::from(primary_code),
197 action,
198 error = %message,
199 "Offline database operation failed"
200 );
201 if let Err(io_ex) = self.remove_existing() {
202 self.handle_error(&io_ex, action);
203 }
204 } else {
205 tracing::warn!(
208 target: log_target::DATABASE,
209 code = i64::from(primary_code),
210 action,
211 error = %message,
212 "Offline database operation failed"
213 );
214 }
215 }
216 DatabaseError::Io { code, message } => {
217 tracing::error!(
219 target: log_target::DATABASE,
220 code = i64::from(*code),
221 action,
222 error = %message,
223 "Offline database operation failed"
224 );
225 }
226 DatabaseError::Failed(message) => {
227 tracing::error!(target: log_target::DATABASE, action, error = %message, "Offline database operation failed");
228 }
229 DatabaseError::InvalidArgument(_) => {
230 tracing::error!(target: log_target::DATABASE, action, "Offline database operation failed");
231 }
232 DatabaseError::RegionNotFound(_) => {}
234 }
235 }
236
237 fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
240 if let Err(e) = &result {
241 self.handle_error(e, action);
242 }
243 result
244 }
245
246 fn remove_existing(&mut self) -> DbResult<()> {
247 tracing::warn!(target: log_target::DATABASE, "Removing existing incompatible offline database");
248
249 self.discard_pending_accessed();
250 let filename = match &self.db {
251 Some(db) => db.path().unwrap_or("").to_owned(),
252 None => self.path.clone(),
253 };
254 self.db = None;
255
256 if !filename.is_empty() {
257 delete_file(&filename)?;
258 }
259 Ok(())
260 }
261
262 fn check_flags(&self) -> DbResult<()> {
263 if self.read_only {
264 return Err(DatabaseError::Failed("Cannot modify database in read-only mode".to_owned()));
265 }
266 Ok(())
267 }
268
269 fn db(&mut self) -> DbResult<&Connection> {
271 if self.db.is_none() {
272 self.initialize()?;
273 }
274 self.db.as_ref().ok_or_else(|| DatabaseError::Failed("Database not initialized".to_owned()))
275 }
276
277 fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
280 let conn = self.db()?;
281 let mut stmt = conn.prepare_cached(sql)?;
282 Ok(stmt.execute(params)? as u64)
283 }
284
285 fn query_row<T>(
288 &mut self,
289 sql: &str,
290 params: impl rusqlite::Params,
291 f: impl FnOnce(&Row<'_>) -> DbResult<T>,
292 ) -> DbResult<Option<T>> {
293 let conn = self.db()?;
294 let mut stmt = conn.prepare_cached(sql)?;
295 let mut rows = stmt.query(params)?;
296 match rows.next()? {
297 None => Ok(None),
298 Some(row) => f(row).map(Some),
299 }
300 }
301
302 fn last_insert_row_id(&mut self) -> DbResult<i64> {
304 let conn = self.db()?;
305 Ok(conn.last_insert_rowid())
306 }
307
308 fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
311 exec(self.db()?, begin.sql())?;
312 match f(self) {
313 Ok(value) => {
314 exec(self.db()?, "COMMIT TRANSACTION")?;
315 Ok(value)
316 }
317 Err(e) => {
318 if let Some(db) = &self.db {
320 let _ = exec(db, "ROLLBACK TRANSACTION");
321 }
322 Err(e)
323 }
324 }
325 }
326
327 fn pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
328 Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
329 }
330
331 pub(crate) fn pack(&mut self) -> DbResult<()> {
332 let result = (|| -> DbResult<()> {
333 if self.db.is_none() {
334 self.initialize()?;
335 }
336 self.vacuum()
337 })();
338 self.report(result, "pack storage")
339 }
340
341 #[cfg(test)]
342 pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
343 self.autopack = autopack;
344 }
345
346 pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
347 if self.read_only == read_only {
348 return;
349 }
350 self.cleanup();
351 self.read_only = read_only;
352 if let Err(e) = self.initialize() {
353 self.handle_error(&e, "reopen database read-only");
354 }
355 }
356
357 pub(crate) fn reset_database(&mut self) -> DbResult<()> {
360 let result = self.remove_existing().and_then(|()| self.initialize());
361 self.report(result, "reset database")
362 }
363}
364
365#[derive(Clone, Copy)]
367enum Begin {
368 Deferred,
369 Immediate,
370}
371
372impl Begin {
373 fn sql(self) -> &'static str {
374 match self {
375 Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
376 Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
377 }
378 }
379}
380
381fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
385 use rusqlite::fallible_iterator::FallibleIterator as _;
386
387 let mut batch = rusqlite::Batch::new(conn, sql);
388 while let Some(mut stmt) = batch.next()? {
389 let mut rows = stmt.raw_query();
390 while rows.next()?.is_some() {}
391 }
392 Ok(())
393}
394
395fn tile_data(resource: &Resource) -> Option<&TileData> {
398 resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
399}
400
401#[derive(Clone, Copy)]
403enum Table {
404 Tiles,
405 Resources,
406}
407
408impl Table {
409 fn name(self) -> &'static str {
410 match self {
411 Table::Tiles => "tiles",
412 Table::Resources => "resources",
413 }
414 }
415
416 fn regions(self) -> (&'static str, &'static str) {
419 match self {
420 Table::Tiles => ("region_tiles", "tile_id"),
421 Table::Resources => ("region_resources", "resource_id"),
422 }
423 }
424}
425
426enum Stored<'a> {
429 Tile(&'a TileData),
430 Resource { url: String, kind: i32 },
431}
432
433impl<'a> Stored<'a> {
434 fn of(resource: &'a Resource) -> Self {
435 match tile_data(resource) {
436 Some(tile) => Stored::Tile(tile),
437 None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
438 }
439 }
440
441 fn is_tile(&self) -> bool {
442 matches!(self, Stored::Tile(_))
443 }
444}