use std::sync::Arc;
use rusqlite::{Row, params};
use super::{Begin, DatabaseError, DbResult, MAX_PENDING_ACCESSED, OfflineDatabase, Stored};
use crate::log_target;
use crate::storage::chrono::{Timestamp, now};
use crate::storage::compression::{compress, decompress};
use crate::storage::resource::Resource;
use crate::storage::response::{Caching, Response};
pub(super) const CACHING_COLUMNS: &str = "expires, must_revalidate";
pub(super) fn read_caching(row: &Row<'_>, start: usize) -> DbResult<Caching> {
Ok(Caching {
expires: row.get::<_, Option<i64>>(start)?.map(Timestamp::from_secs),
must_revalidate: row.get(start + 1)?,
})
}
pub(super) struct DatabaseSizeChangeStats {
page_size: i64,
page_count: i64,
initial_size: i64,
}
impl DatabaseSizeChangeStats {
fn size(&self, page_count: i64, freelist_count: i64) -> i64 {
self.page_size.saturating_mul(page_count.saturating_sub(freelist_count).max(0))
}
pub(super) fn new(db: &mut OfflineDatabase) -> DbResult<Self> {
let page_size = db.pragma_i64("PRAGMA page_size")?.max(0);
let page_count = db.pragma_i64("PRAGMA page_count")?;
let freelist_count = db.pragma_i64("PRAGMA freelist_count")?;
let mut stats = DatabaseSizeChangeStats { page_size, page_count, initial_size: 0 };
stats.initial_size = stats.size(page_count, freelist_count);
Ok(stats)
}
fn diff(&self, db: &mut OfflineDatabase) -> DbResult<i64> {
let page_count = db.pragma_i64("PRAGMA page_count")?;
let freelist_count = db.pragma_i64("PRAGMA freelist_count")?;
Ok(self.size(page_count, freelist_count).saturating_sub(self.initial_size))
}
fn bytes_released(&self, db: &mut OfflineDatabase) -> DbResult<u64> {
let freelist_count = db.pragma_i64("PRAGMA freelist_count")?;
let released = self.initial_size.saturating_sub(self.size(self.page_count, freelist_count));
Ok(u64::try_from(released).unwrap_or(0))
}
fn page_size(&self) -> u64 {
self.page_size.unsigned_abs()
}
}
impl OfflineDatabase {
#[must_use]
pub(crate) fn cache_key(resource: &Resource) -> String {
let Some((first, second)) = resource.data_range else {
return resource.url.clone();
};
let sep = if resource.url.contains('?') { '&' } else { '?' };
format!("{}{}_mlnRange={}-{}", resource.url, sep, first, second)
}
pub(crate) fn set_accessed_callback(&mut self, callback: Box<dyn FnMut() + Send>) {
self.accessed_callback = Some(callback);
}
#[must_use]
pub(crate) fn pending_accessed_count(&self) -> usize {
self.pending_resource_accessed.len() + self.pending_tile_accessed.len()
}
pub(crate) fn flush_accessed(&mut self) -> bool {
if self.pending_accessed_count() == 0 {
return true;
}
if self.read_only || self.db.is_none() {
return false;
}
match self.with_transaction(Begin::Immediate, Self::apply_pending_accessed) {
Ok(()) => {
self.discard_pending_accessed();
true
}
Err(e) => {
self.accessed_flush_failed = true;
self.handle_error(&e, "flush accessed timestamps");
false
}
}
}
pub(super) fn discard_pending_accessed(&mut self) {
self.pending_resource_accessed.clear();
self.pending_tile_accessed.clear();
self.accessed_flush_failed = false;
}
fn apply_pending_accessed(&mut self) -> DbResult<()> {
self.db()?;
let Some(conn) = &self.db else {
return Ok(());
};
for (sql, pending) in [
("UPDATE resources SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_resource_accessed),
("UPDATE tiles SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_tile_accessed),
] {
if pending.is_empty() {
continue;
}
let mut stmt = conn.prepare_cached(sql)?;
for (id, accessed) in pending {
stmt.execute(params![accessed, id])?;
}
}
Ok(())
}
fn queue_accessed(&mut self, tile: bool, id: i64) {
if self.read_only {
return;
}
let accessed = now().secs_since_epoch();
let full = self.pending_accessed_count() >= MAX_PENDING_ACCESSED;
let pending = if tile { &mut self.pending_tile_accessed } else { &mut self.pending_resource_accessed };
if let Some(existing) = pending.get_mut(&id) {
*existing = (*existing).max(accessed);
} else if !full {
pending.insert(id, accessed);
}
}
pub(crate) fn get(&mut self, resource: &Resource) -> Option<Response> {
let result = if self.disabled() { Ok(None) } else { self.get_internal(resource) };
self.report(result, "read resource").ok().flatten().map(|(response, _size)| response)
}
pub(super) fn get_internal(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
let stored = Stored::of(resource);
let (sql, params) = match &stored {
Stored::Tile(t) => (
"SELECT etag, modified, data, compressed, id, expires, must_revalidate FROM tiles \
WHERE url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?",
params![t.url_template, t.pixel_ratio, t.x, t.y, t.z],
),
Stored::Resource { url, .. } => (
"SELECT etag, modified, data, compressed, id, expires, must_revalidate FROM resources WHERE url = ?",
params![*url],
),
};
let Some((response, size, id)) = self.query_row(sql, params, read_response)? else {
return Ok(None);
};
self.queue_accessed(stored.is_tile(), id);
if self.pending_accessed_count() >= MAX_PENDING_ACCESSED && !self.accessed_flush_failed {
self.flush_accessed();
}
if self.pending_accessed_count() > 0
&& let Some(callback) = &mut self.accessed_callback
{
callback();
}
Ok(Some((response, size)))
}
pub(super) fn has_internal(&mut self, resource: &Resource) -> DbResult<Option<(u64, Caching)>> {
let stored = Stored::of(resource);
let (sql, params) = match &stored {
Stored::Tile(t) => (
"SELECT length(data), expires, must_revalidate FROM tiles \
WHERE url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?",
params![t.url_template, t.pixel_ratio, t.x, t.y, t.z],
),
Stored::Resource { url, .. } => {
("SELECT length(data), expires, must_revalidate FROM resources WHERE url = ?", params![*url])
}
};
let row = self.query_row(sql, params, |row| {
let size: Option<i64> = row.get(0)?;
size.map(|size| Ok((size as u64, read_caching(row, 1)?))).transpose()
})?;
Ok(row.flatten())
}
pub(crate) fn put(&mut self, resource: &Resource, response: &Response) -> (bool, u64) {
if self.read_only || response.tile_not_found {
return (false, 0);
}
let result = (|| -> DbResult<(bool, u64)> {
if self.disabled() {
return Ok((false, 0));
}
self.pending_applied_for_eviction = false;
let result = self.with_transaction(Begin::Immediate, |this| this.put_internal(resource, response, true))?;
if self.pending_applied_for_eviction {
self.discard_pending_accessed();
}
Ok(result)
})();
self.report(result, "write resource").unwrap_or((false, 0))
}
pub(super) fn put_internal(
&mut self,
resource: &Resource,
response: &Response,
evict: bool,
) -> DbResult<(bool, u64)> {
self.check_flags()?;
if response.error.is_some() || response.no_store {
return Ok((false, 0));
}
if evict && self.maximum_ambient_cache_size == 0 {
return Ok((false, 0));
}
let renews = renews(response);
let compressed = match &response.data {
Some(data) if !renews => {
Some(compress(data).map_err(DatabaseError::Failed)?).filter(|c| c.len() < data.len())
}
_ => None,
};
let data = if renews {
&[]
} else {
compressed.as_deref().or(response.data.as_deref().map(Vec::as_slice)).unwrap_or_default()
};
let size = data.len() as u64;
let stats = if evict {
let stats = DatabaseSizeChangeStats::new(self)?;
if !self.evict(size, &stats, true)? {
tracing::info!(target: log_target::DATABASE, "Unable to make space for entry");
return Ok((false, 0));
}
Some(stats)
} else {
None
};
let inserted = self.write(&Stored::of(resource), response, data, compressed.is_some())?;
if let Some(stats) = stats {
self.update_ambient_cache_size(&stats)?;
}
Ok((inserted, size))
}
fn write(&mut self, stored: &Stored<'_>, response: &Response, data: &[u8], compressed: bool) -> DbResult<bool> {
let secs = |time: Option<Timestamp>| time.map(Timestamp::secs_since_epoch);
let (expires, modified) = (secs(response.caching.expires), secs(response.modified));
let accessed = now().secs_since_epoch();
let data = (!response.no_content).then_some(data);
let compressed = compressed && data.is_some();
let must_revalidate = response.caching.must_revalidate;
let (update, insert, params) = match (stored, renews(response)) {
(Stored::Tile(t), true) => (
"UPDATE tiles SET accessed = ?, expires = ?, must_revalidate = ? \
WHERE url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?",
None,
params![accessed, expires, must_revalidate, t.url_template, t.pixel_ratio, t.x, t.y, t.z],
),
(Stored::Tile(t), false) => (
"UPDATE tiles SET accessed = ?, expires = ?, must_revalidate = ?, \
etag = ?, modified = ?, data = ?, compressed = ? \
WHERE url_template = ? AND pixel_ratio = ? AND x = ? AND y = ? AND z = ?",
Some(
"INSERT INTO tiles (accessed, expires, must_revalidate, etag, modified, data, compressed, \
url_template, pixel_ratio, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
),
params![
accessed,
expires,
must_revalidate,
response.etag,
modified,
data,
compressed,
t.url_template,
t.pixel_ratio,
t.x,
t.y,
t.z
],
),
(Stored::Resource { url, .. }, true) => (
"UPDATE resources SET accessed = ?, expires = ?, must_revalidate = ? WHERE url = ?",
None,
params![accessed, expires, must_revalidate, *url],
),
(Stored::Resource { url, kind }, false) => (
"UPDATE resources SET accessed = ?, expires = ?, must_revalidate = ?, \
etag = ?, modified = ?, data = ?, compressed = ?, kind = ? WHERE url = ?",
Some(
"INSERT INTO resources (accessed, expires, must_revalidate, etag, modified, data, compressed, \
kind, url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
),
params![accessed, expires, must_revalidate, response.etag, modified, data, compressed, *kind, *url],
),
};
if self.execute(update, params)? != 0 {
return Ok(false);
}
let Some(insert) = insert else {
return Ok(false);
};
self.execute(insert, params)?;
Ok(true)
}
pub(crate) fn invalidate_ambient_cache(&mut self) -> DbResult<()> {
let result = self.invalidate(
"id NOT IN (SELECT tile_id FROM region_tiles)",
"id NOT IN (SELECT resource_id FROM region_resources)",
[],
);
self.report(result, "invalidate ambient cache")
}
pub(super) fn invalidate(
&mut self,
tiles: &str,
resources: &str,
params: impl rusqlite::Params + Copy,
) -> DbResult<()> {
self.check_flags()?;
let now = now().secs_since_epoch();
for (table, ids) in [("tiles", tiles), ("resources", resources)] {
self.execute(
&format!("UPDATE {table} SET expires = MIN(IFNULL(expires, {now}), {now}) WHERE {ids}"),
params,
)?;
}
Ok(())
}
pub(crate) fn clear_ambient_cache(&mut self) -> DbResult<()> {
let result = (|| -> DbResult<()> {
self.check_flags()?;
self.discard_pending_accessed();
self.execute(
"DELETE FROM tiles \
WHERE id NOT IN (\
SELECT tile_id FROM region_tiles\
)",
[],
)?;
self.execute(
"DELETE FROM resources \
WHERE id NOT IN (\
SELECT resource_id FROM region_resources\
)",
[],
)?;
if self.autopack {
self.vacuum()?;
}
Ok(())
})();
self.report(result, "clear ambient cache")
}
pub(super) fn evict(
&mut self,
needed_free_size: u64,
stats: &DatabaseSizeChangeStats,
apply_accessed: bool,
) -> DbResult<bool> {
self.check_flags()?;
let mut new_ambient_cache_size =
self.ambient_cache_size()?.saturating_add(needed_free_size).saturating_add(stats.page_size());
if apply_accessed
&& new_ambient_cache_size > self.maximum_ambient_cache_size
&& self.pending_accessed_count() > 0
{
self.apply_pending_accessed()?;
self.pending_applied_for_eviction = true;
}
while new_ambient_cache_size > self.maximum_ambient_cache_size {
let accessed = self.query_row(
"SELECT max(accessed) \
FROM ( \
SELECT accessed \
FROM resources \
LEFT JOIN region_resources \
ON resource_id = resources.id \
WHERE resource_id IS NULL \
UNION ALL \
SELECT accessed \
FROM tiles \
LEFT JOIN region_tiles \
ON tile_id = tiles.id \
WHERE tile_id IS NULL \
ORDER BY accessed ASC LIMIT ?1 \
) ",
params![50],
|row| Ok(row.get::<_, Option<i64>>(0)?),
)?;
let Some(accessed) = accessed.flatten() else {
return Ok(false);
};
let resource_changes = self.execute(
"DELETE FROM resources \
WHERE id IN ( \
SELECT id FROM resources \
LEFT JOIN region_resources \
ON resource_id = resources.id \
WHERE resource_id IS NULL \
AND accessed <= ?1 \
) ",
params![accessed],
)?;
let tile_changes = self.execute(
"DELETE FROM tiles \
WHERE id IN ( \
SELECT id FROM tiles \
LEFT JOIN region_tiles \
ON tile_id = tiles.id \
WHERE tile_id IS NULL \
AND accessed <= ?1 \
) ",
params![accessed],
)?;
let released = stats.bytes_released(self)?;
new_ambient_cache_size = new_ambient_cache_size.saturating_sub(released);
if resource_changes == 0 && tile_changes == 0 {
return Ok(false);
}
}
Ok(true)
}
fn ambient_cache_size(&mut self) -> DbResult<u64> {
if let Some(size) = self.current_ambient_cache_size {
return Ok(size);
}
let size = self.query_row(
"SELECT SUM(data) \
FROM ( \
SELECT SUM(IFNULL(LENGTH(data), 0) \
+ IFNULL(LENGTH(id), 0) \
+ IFNULL(LENGTH(url_template), 0) \
+ IFNULL(LENGTH(pixel_ratio), 0) \
+ IFNULL(LENGTH(x), 0) \
+ IFNULL(LENGTH(y), 0) \
+ IFNULL(LENGTH(z), 0) \
+ IFNULL(LENGTH(expires), 0) \
+ IFNULL(LENGTH(modified), 0) \
+ IFNULL(LENGTH(etag), 0) \
+ IFNULL(LENGTH(compressed), 0) \
+ IFNULL(LENGTH(accessed), 0) \
+ IFNULL(LENGTH(must_revalidate), 0) \
) as data \
FROM tiles \
LEFT JOIN region_tiles \
ON tile_id = tiles.id \
WHERE tile_id IS NULL \
UNION ALL \
SELECT SUM(IFNULL(LENGTH(data), 0) \
+ IFNULL(LENGTH(id), 0) \
+ IFNULL(LENGTH(url), 0) \
+ IFNULL(LENGTH(kind), 0) \
+ IFNULL(LENGTH(expires), 0) \
+ IFNULL(LENGTH(modified), 0) \
+ IFNULL(LENGTH(etag), 0) \
+ IFNULL(LENGTH(compressed), 0) \
+ IFNULL(LENGTH(accessed), 0) \
+ IFNULL(LENGTH(must_revalidate), 0) \
) as data \
FROM resources \
LEFT JOIN region_resources \
ON resource_id = resources.id \
WHERE resource_id IS NULL \
) ",
[],
|row| Ok(row.get::<_, Option<i64>>(0)?),
)?;
let size = size.flatten().unwrap_or(0) as u64;
self.current_ambient_cache_size = Some(size);
Ok(size)
}
pub(crate) fn set_maximum_ambient_cache_size(&mut self, size: u64) -> DbResult<()> {
self.flush_accessed();
let previous_maximum_ambient_cache_size = self.maximum_ambient_cache_size;
let result = (|| -> DbResult<()> {
let current = self.ambient_cache_size()?;
self.maximum_ambient_cache_size = size;
if current > size {
let stats = DatabaseSizeChangeStats::new(self)?;
self.evict(0, &stats, false)?;
if self.autopack {
self.vacuum()?;
}
self.update_ambient_cache_size(&stats)?;
}
Ok(())
})();
if result.is_err() {
self.maximum_ambient_cache_size = previous_maximum_ambient_cache_size;
}
self.report(result, "set maximum ambient cache size")
}
pub(super) fn update_ambient_cache_size(&mut self, stats: &DatabaseSizeChangeStats) -> DbResult<()> {
debug_assert!(self.current_ambient_cache_size.is_some());
if let Some(current) = self.current_ambient_cache_size {
let diff = stats.diff(self)?;
self.current_ambient_cache_size = Some(current.saturating_add_signed(diff));
}
Ok(())
}
}
fn renews(response: &Response) -> bool {
response.not_modified || response.prior
}
fn read_response(row: &Row<'_>) -> DbResult<(Response, u64, i64)> {
let mut response = Response::new();
let mut size = 0u64;
response.etag = row.get(0)?;
response.modified = row.get::<_, Option<i64>>(1)?.map(Timestamp::from_secs);
match row.get_ref(2)?.as_bytes_or_null()? {
None => response.no_content = true,
Some(data) => {
size = data.len() as u64;
let data = if row.get(3)? { decompress(data).map_err(DatabaseError::Failed)? } else { data.to_vec() };
response.data = Some(Arc::new(data));
}
}
response.caching = read_caching(row, 5)?;
Ok((response, size, row.get(4)?))
}