mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// Ambient cache reads/writes, accessed-timestamp batching, and LRU eviction.

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};

/// The columns that `read_caching` reads.
pub(super) const CACHING_COLUMNS: &str = "expires, must_revalidate";

/// Reads `CACHING_COLUMNS` from column `start` on.
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)?,
    })
}

/// The database size (pages in use) when it was created. The database is
/// passed to the methods that query it.
pub(super) struct DatabaseSizeChangeStats {
    page_size: i64,
    page_count: i64,
    initial_size: i64,
}

impl DatabaseSizeChangeStats {
    /// The bytes of the pages in use, of `page_count` pages of which
    /// `freelist_count` are free.
    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)
    }

    /// Returns difference between current database size and database size at
    /// the time of creation of this object.
    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))
    }

    /// Returns how many bytes were released comparing to a database size at
    /// the time of creation of this object.
    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))
    }

    /// Returns page size for the database.
    fn page_size(&self) -> u64 {
        self.page_size.unsigned_abs()
    }
}

impl OfflineDatabase {
    /// Single-point transformer for offline storage keys. For sources where
    /// the URL is not enough to guarantee uniqueness (eg. PMTiles where all
    /// requests resolve to the same URL), this function creates a synthetic
    /// key based on the requested data range.
    #[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)
    }

    /// Sets the callback that runs after a cache hit leaves `accessed`
    /// timestamps waiting to be written; the owner then calls
    /// [`flush_accessed`](Self::flush_accessed) later. It runs inside `get`
    /// and `region_resource`, so it must not use this database.
    pub(crate) fn set_accessed_callback(&mut self, callback: Box<dyn FnMut() + Send>) {
        self.accessed_callback = Some(callback);
    }

    /// The number of rows whose `accessed` timestamp waits to be written.
    #[must_use]
    pub(crate) fn pending_accessed_count(&self) -> usize {
        self.pending_resource_accessed.len() + self.pending_tile_accessed.len()
    }

    /// Writes the waiting `accessed` timestamps in one transaction, never
    /// moving a row's timestamp back. Returns false and keeps them waiting
    /// when that fails or the database is read-only or closed.
    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;
    }

    /// Runs the `accessed` updates in the open transaction.
    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(())
    }

    /// Queues the `accessed` timestamp of a cache hit, used for LRU
    /// eviction.
    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);
        }
    }

    /// The stored copy of `resource`, if any.
    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)))
    }

    /// The stored size and caching rules of the copy of `resource`; `None`
    /// without one, or for a copy without data.
    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())
    }

    /// `put(const Resource&, const Response&)`: (inserted, stored size). The ambient cache doesn't
    /// keep a tile the tileset doesn't have (`Response::tile_not_found`), since it would read back as
    /// an empty tile.
    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))
    }

    /// Stores `response` for `resource`, first making room in the ambient
    /// cache when `evict` is set.
    pub(super) fn put_internal(
        &mut self,
        resource: &Resource,
        response: &Response,
        evict: bool,
    ) -> DbResult<(bool, u64)> {
        self.check_flags()?;

        // An error isn't stored, nor what the server forbids storing.
        if response.error.is_some() || response.no_store {
            return Ok((false, 0));
        }

        // An ambient cache with no room can't store anything, so skip compressing.
        if evict && self.maximum_ambient_cache_size == 0 {
            return Ok((false, 0));
        }

        // A copy the database has, as for a 304, only renews its caching
        // rules.
        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))
    }

    /// Writes `response`, with `data` as its stored bytes, to the row of
    /// `stored`, and gives whether it added the row. A copy the database has
    /// (`renews`) updates only its caching rules.
    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();
        // An empty body is an empty blob, and no content is NULL.
        let data = (!response.no_content).then_some(data);
        let compressed = compressed && data.is_some();

        let must_revalidate = response.caching.must_revalidate;

        // Not REPLACE, which would change the row's id. A copy that renews
        // only updates; another inserts the row when there's none to update.
        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)
    }

    /// Makes the ambient cache's copies stale, so maps revalidate them when
    /// they next use them. See `invalidate`.
    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")
    }

    /// Makes the tiles and resources whose ids match the conditions stale
    /// now. A copy that must revalidate then can't be used until it has.
    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(())
    }

    /// Clears the ambient cache, freeing space.
    pub(crate) fn clear_ambient_cache(&mut self) -> DbResult<()> {
        let result = (|| -> DbResult<()> {
            self.check_flags()?;
            // The deleted rows' ids may be reused.
            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")
    }

    // Remove least-recently used resources and tiles until the used database
    // size, as calculated by multiplying the number of in-use pages by the
    // page size, is less than the maximum cache size. Returns false if this
    // condition cannot be satisfied.
    //
    // SQLite database never shrinks in size unless we call VACUUM. We here
    // are monitoring the soft limit (i.e. number of free pages in the file)
    // and as it approaches to the hard limit (i.e. the actual file size) we
    // delete an arbitrary number of old cache entries. The free pages
    // approach saves us from calling VACUUM or keeping a running total,
    // which can be costly.
    //
    // `apply_accessed` (put only) writes the pending `accessed` timestamps in
    // the caller's transaction before choosing what to evict.
    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],
            )?;

            // Update current ambient cache size, based on how many bytes were
            // released.
            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)
    }

    /// The size of the ambient cache's rows, which it reads once and then
    /// keeps up to date.
    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<()> {
        // Eviction uses the stored timestamps if this fails.
        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(())
    }
}

/// Whether `response` brings a copy the database has: a 304, or the copy
/// the request carried, which a 304 delivered.
fn renews(response: &Response) -> bool {
    response.not_modified || response.prior
}

/// Reads `etag, modified, data, compressed, id`, then the caching columns:
/// the response, its stored size, and its row id.
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)?))
}