Skip to main content

martin_core/tiles/postgres/
engine.rs

1//! Serves a table with `layers`: one query reads the features around a tile, Martin's engine renders them.
2
3use std::collections::HashMap;
4use std::num::NonZeroU8;
5use std::sync::Arc;
6
7use martin_tile_utils::{EARTH_CIRCUMFERENCE, Encoding, TileCoord, TileData, TileRect};
8use martin_tilegen::plan::Plan;
9use martin_tilegen::{Summary, TileFormat, TileGenError, render_block};
10use tracing::{debug, warn};
11
12use super::{PostgresError, PostgresPool, PostgresResult};
13use crate::tiles::postgres::scan::{ScanLayout, scan_features};
14
15/// How a table with `layers` is read and rendered.
16#[derive(Clone, Debug)]
17pub struct PostgresEngineInfo {
18    /// The plan of the table's layers, the table being its only one.
19    pub plan: Arc<Plan>,
20    /// SQL by zoom from 0, the last one serving every zoom past it, taking `$1..$4` and `$5..$8` as two
21    /// Web Mercator `xmin, ymin, xmax, ymax` envelopes of the area to read, and returning its features
22    /// once each, as `layout` says.
23    pub sql_queries: Vec<String>,
24    /// How the query's columns map to the plan's table.
25    pub layout: ScanLayout,
26    /// How far past a tile its features are read, as a fraction of a tile's side: the largest buffer
27    /// of the layers plus half a grid unit, since a vertex that far out still rounds onto the buffer edge.
28    pub margin: f64,
29    /// Tiles per side of the block a cache miss renders; `None` renders just the tile.
30    pub prefetch: Option<NonZeroU8>,
31}
32
33impl PostgresEngineInfo {
34    /// Reads the features reaching `xyz` and renders them into an uncompressed MVT tile.
35    pub(super) async fn render_tile(
36        &self,
37        pool: &PostgresPool,
38        source_id: &str,
39        xyz: TileCoord,
40    ) -> PostgresResult<TileData> {
41        let block = TileRect::new(xyz.z(), xyz.x(), xyz.y(), xyz.x(), xyz.y());
42        let tiles = self.render(pool, source_id, xyz, block).await?;
43        Ok(tiles.into_iter().next().map(|(_, data)| data).unwrap_or_default())
44    }
45
46    /// Every tile of the [`prefetch`](Self::prefetch) block holding `xyz`, empty ones included, or
47    /// `None` without prefetching. Blocks are aligned, so the tiles of one block share it.
48    pub(super) async fn render_prefetch(
49        &self,
50        pool: &PostgresPool,
51        source_id: &str,
52        xyz: TileCoord,
53    ) -> PostgresResult<Option<Vec<(TileCoord, TileData)>>> {
54        let Some(side) = self.prefetch else {
55            return Ok(None);
56        };
57        let side = u32::from(side.get());
58        let last = (1u32 << xyz.z()) - 1;
59        let (x, y) = (xyz.x() / side * side, xyz.y() / side * side);
60        let block = TileRect::new(xyz.z(), x, y, (x + side - 1).min(last), (y + side - 1).min(last));
61        let mut rendered: HashMap<_, _> = self.render(pool, source_id, xyz, block).await?.into_iter().collect();
62        let tiles = (block.min_x..=block.max_x)
63            .flat_map(|x| (block.min_y..=block.max_y).map(move |y| (x, y)))
64            .map(|(x, y)| {
65                let coord = TileCoord::new_unchecked(xyz.z(), x, y);
66                (coord, rendered.remove(&coord).unwrap_or_default())
67            })
68            .collect();
69        Ok(Some(tiles))
70    }
71
72    /// Reads the features reaching `block` and renders its tiles that have any, in TMS order.
73    async fn render(
74        &self,
75        pool: &PostgresPool,
76        source_id: &str,
77        xyz: TileCoord,
78        block: TileRect,
79    ) -> PostgresResult<Vec<(TileCoord, TileData)>> {
80        let failed = |err: TileGenError| PostgresError::EngineError(Box::new(err), source_id.to_owned(), xyz);
81        let [[x1, y1, x2, y2], [x3, y3, x4, y4]] = self.envelopes(block);
82        let sql = self.sql_query(block.zoom);
83        let conn = pool.get().await?;
84        let _cancel_guard = pool.active_query_registry().register(conn.cancel_token());
85        let statement = conn
86            .prepare_cached(sql)
87            .await
88            .map_err(|e| PostgresError::PostgresError(e, "preparing a table's feature query"))?;
89        debug!(sql = %sql, tile.coord = %xyz, "Running feature query");
90        let mut batches = Vec::new();
91        scan_features(
92            &conn,
93            &statement,
94            &[&x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4],
95            &self.layout,
96            0,
97            &self.plan.table_keys()[usize::from(self.layout.table)],
98            |batch| {
99                batches.push(batch);
100                Ok(())
101            },
102        )
103        .await
104        .map_err(|err| failed(err.into()))?;
105        drop(conn);
106
107        let plan = Arc::clone(&self.plan);
108        let (tiles, summary) = tokio::task::spawn_blocking(move || {
109            render_block(&plan, &mut batches, block, TileFormat::Mvt, Encoding::Uncompressed)
110        })
111        .await
112        .unwrap_or_else(|panic| std::panic::resume_unwind(panic.into_panic()))
113        .map_err(failed)?;
114        report(source_id, xyz, &summary);
115        Ok(tiles
116            .into_iter()
117            .map(|tile| (tile.coord, TileData::from(tile.data)))
118            .collect())
119    }
120
121    /// The query reading the features of a block at `zoom`.
122    fn sql_query(&self, zoom: u8) -> &str {
123        self.sql_queries
124            .get(usize::from(zoom))
125            .or_else(|| self.sql_queries.last())
126            .expect("an engine has a query for zoom 0")
127    }
128
129    /// The Web Mercator bounds of `block`, grown by [`Self::margin`] tiles on every side, as two
130    /// envelopes within the world's columns: the second is the part that wraps past the antimeridian,
131    /// or the first again when nothing does.
132    fn envelopes(&self, block: TileRect) -> [[f64; 4]; 2] {
133        let side = EARTH_CIRCUMFERENCE / f64::from(1u32 << block.zoom);
134        let half = EARTH_CIRCUMFERENCE / 2.0;
135        let margin = self.margin * side;
136        let xmin = f64::from(block.min_x).mul_add(side, -half) - margin;
137        let xmax = f64::from(block.max_x + 1).mul_add(side, -half) + margin;
138        let ymin = half - f64::from(block.max_y + 1) * side - margin;
139        let ymax = half - f64::from(block.min_y) * side + margin;
140        let main = [xmin.max(-half), ymin, xmax.min(half), ymax];
141        let wrapped = if xmax - xmin >= EARTH_CIRCUMFERENCE {
142            main
143        } else if xmin < -half {
144            [xmin + EARTH_CIRCUMFERENCE, ymin, half, ymax]
145        } else if xmax > half {
146            [-half, ymin, xmax - EARTH_CIRCUMFERENCE, ymax]
147        } else {
148            main
149        };
150        [main, wrapped]
151    }
152}
153
154/// Logs what rendering the block around `xyz` could not do. The plan already warns about the first
155/// failure of each expression and of each merge, so those only show at debug level here.
156fn report(source_id: &str, xyz: TileCoord, summary: &Summary) {
157    for failed in &summary.slice_errors {
158        warn!(
159            source.id = source_id,
160            tile.coord = %xyz,
161            layer.id = %failed.layer,
162            feature_zooms.skipped = failed.errors,
163            feature.id = failed.id,
164            tile.zoom = failed.zoom,
165            error = %failed.error,
166            "Skipped feature-zooms whose geometry the slicer could not handle"
167        );
168    }
169    for failed in &summary.expr_errors {
170        debug!(
171            source.id = source_id,
172            tile.coord = %xyz,
173            "Layer `{}`: `{}` failed {} times and was taken as null",
174            failed.layer,
175            failed.expr,
176            failed.errors
177        );
178    }
179    for op in summary.per_tile.iter().filter(|op| op.counts.groups_failed > 0) {
180        debug!(
181            source.id = source_id,
182            tile.coord = %xyz,
183            "Layer `{}`: `{}` could not merge {} groups, which kept their features",
184            op.layer,
185            op.op.name(),
186            op.counts.groups_failed
187        );
188    }
189    debug!(
190        source.id = source_id,
191        tile.coord = %xyz,
192        features = summary.features,
193        features.skipped = summary.skipped,
194        tiles = summary.tiles,
195        "Rendered the block around a tile"
196    );
197}