martin_core/tiles/postgres/
engine.rs1use 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#[derive(Clone, Debug)]
17pub struct PostgresEngineInfo {
18 pub plan: Arc<Plan>,
20 pub sql_queries: Vec<String>,
24 pub layout: ScanLayout,
26 pub margin: f64,
29 pub prefetch: Option<NonZeroU8>,
31}
32
33impl PostgresEngineInfo {
34 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 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 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 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 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
154fn 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}