martin-core 0.16.0

Basic building blocks of MapLibre's Martin tile server.
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
use std::collections::HashMap;

use compact_str::CompactString;
use deadpool_postgres::Object;
use deadpool_postgres::tokio_postgres::types::{Json, ToSql, Type};
use deadpool_postgres::tokio_postgres::{Row, Statement};
use martin_tile_utils::{Encoding, TileCoord, TileData, TileGrid, TileInfo};
use tilejson::TileJSON;
use tracing::{debug, instrument};

use crate::CacheZoomRange;
use crate::tiles::postgres::PostgresEngineInfo;
use crate::tiles::postgres::PostgresError::{GetTileError, GetTileWithQueryError, PrepareQueryError};
use crate::tiles::postgres::features::features_from_rows;
use crate::tiles::postgres::pool::ActiveQueryGuard;
use crate::tiles::postgres::utils::query_to_json;
use crate::tiles::postgres::{ActiveQueryRegistry, PostgresError, PostgresPool, PostgresTileFeatures};
use crate::tiles::source::cap_zoom_range;
use crate::tiles::{MartinCoreResult, Source, Tile, UrlQuery};

#[derive(Clone, Debug)]
/// `PostgreSQL` tile source that executes SQL queries to generate tiles.
pub struct PostgresSource {
    id: String,
    tiler: PostgresTiler,
    pool: PostgresPool,
    tilejson: TileJSON,
    tile_info: TileInfo,
    cache_zoom: CacheZoomRange,
    tile_grid: TileGrid,
}

/// What turns a source's rows into a tile.
#[derive(Clone, Debug)]
pub enum PostgresTiler {
    /// A query that returns the tile itself: `ST_AsMVT` over a table, or a function.
    Sql(PostgresSqlInfo),
    /// A query that returns a table's features, which Martin's engine renders into its `layers`.
    Engine(PostgresEngineInfo),
}

impl From<PostgresSqlInfo> for PostgresTiler {
    fn from(info: PostgresSqlInfo) -> Self {
        Self::Sql(info)
    }
}

impl PostgresSource {
    /// Creates a new `PostgreSQL` tile source.
    #[must_use]
    pub fn new(
        id: String,
        tiler: impl Into<PostgresTiler>,
        mut tilejson: TileJSON,
        pool: PostgresPool,
        tile_info: TileInfo,
        cache_zoom: CacheZoomRange,
        tile_grid: TileGrid,
    ) -> Self {
        cap_zoom_range(&id, &mut tilejson);
        Self {
            id,
            tiler: tiler.into(),
            pool,
            tilejson,
            tile_info,
            cache_zoom,
            tile_grid,
        }
    }
}

impl PostgresSource {
    /// The registry tracking this pool's in-flight queries, so a dropped request
    /// can cancel the statement it started.
    #[must_use]
    pub fn active_query_registry(&self) -> ActiveQueryRegistry {
        self.pool.active_query_registry().clone()
    }

    /// The features of a tile instead of its serialized bytes.
    ///
    /// `None` means this source has no row-per-feature form, which is every source but a table.
    /// A caller that wants a tile format `PostGIS` does not produce itself can encode these
    /// instead of taking an `ST_AsMVT` tile apart again.
    ///
    /// `keep_measures` asks for the M ordinates of polygons too, which `ST_AsMVTGeom` strips, at
    /// the cost of a slower query. A caller whose format has nowhere to put them leaves it off.
    pub async fn get_tile_features(
        &self,
        xyz: TileCoord,
        url_query: Option<&UrlQuery>,
        keep_measures: bool,
    ) -> MartinCoreResult<Option<PostgresTileFeatures>> {
        let Some(info) = self.sql_for(url_query) else {
            return Ok(None);
        };
        let Some(row_query) = &info.row_query else {
            return Ok(None);
        };
        let rows = self
            .query_feature_rows(info, row_query, xyz, url_query, keep_measures)
            .await?;
        Ok(Some(PostgresTileFeatures {
            layer_name: row_query.layer_name.clone(),
            extent: row_query.extent,
            features: features_from_rows(&rows, row_query.has_id_column)?,
        }))
    }
}

impl PostgresSource {
    /// Every tile of the block a cache miss of `xyz` renders, `xyz` among them, or `None` when the
    /// source does not prefetch.
    pub async fn get_tile_block(&self, xyz: TileCoord) -> MartinCoreResult<Option<Vec<(TileCoord, Tile)>>> {
        let PostgresTiler::Engine(engine) = &self.tiler else {
            return Ok(None);
        };
        let Some(tiles) = engine.render_prefetch(&self.pool, &self.id, xyz).await? else {
            return Ok(None);
        };
        Ok(Some(
            tiles
                .into_iter()
                .map(|(coord, data)| (coord, Tile::new_hash_etag(data, self.tile_info)))
                .collect(),
        ))
    }
}

impl Source for PostgresSource {
    fn get_id(&self) -> &str {
        &self.id
    }

    fn get_tilejson(&self) -> &TileJSON {
        &self.tilejson
    }

    fn get_tile_info(&self) -> TileInfo {
        self.tile_info
    }

    fn tile_grid(&self) -> &TileGrid {
        &self.tile_grid
    }

    fn support_url_query(&self) -> bool {
        self.sql().is_some_and(|info| info.use_url_query)
    }

    fn benefits_from_concurrent_scraping(&self) -> bool {
        // pg does not parallelize queries well internally and having more requests in flight is thus beneficial
        true
    }

    fn empty_tile_implies_empty_children(&self) -> bool {
        self.sql().is_some_and(|info| info.empty_tile_implies_empty_children)
    }

    fn cache_zoom(&self) -> CacheZoomRange {
        self.cache_zoom
    }

    async fn get_tile(&self, xyz: TileCoord, url_query: Option<&UrlQuery>) -> MartinCoreResult<TileData> {
        let info = match &self.tiler {
            PostgresTiler::Sql(info) => info.for_query(url_query),
            PostgresTiler::Engine(engine) => {
                return Ok(engine.render_tile(&self.pool, &self.id, xyz).await?);
            }
        };
        Ok(self
            .query_row(info, xyz, url_query)
            .await?
            .and_then(|row| row.get::<_, Option<Vec<u8>>>(0))
            .map_or_default(TileData::from))
    }

    async fn get_tile_with_etag(&self, xyz: TileCoord, url_query: Option<&UrlQuery>) -> MartinCoreResult<Tile> {
        let Some(info) = self.sql_for(url_query).filter(|info| info.has_etag_column) else {
            let data = self.get_tile(xyz, url_query).await?;
            let info = self.tile_info_for(&data);
            return Ok(Tile::new_hash_etag(data, info));
        };
        let row = self.query_row(info, xyz, url_query).await?;
        let data: TileData = row
            .as_ref()
            .and_then(|row| row.get::<_, Option<Vec<u8>>>(0))
            .map_or_default(TileData::from);
        let etag = row
            .and_then(|row| row.get::<_, Option<String>>(1))
            .map(CompactString::from);
        let info = self.tile_info_for(&data);
        match etag {
            Some(etag) if !data.is_empty() && !etag.is_empty() => Ok(Tile::new_with_etag(data, info, etag)),
            _ => Ok(Tile::new_hash_etag(data, info)),
        }
    }
}

impl PostgresSource {
    /// The query returning a request's tile, by whether the request carries a query string.
    /// `None` when the engine renders the tile.
    fn sql_for(&self, url_query: Option<&UrlQuery>) -> Option<&PostgresSqlInfo> {
        self.sql().map(|info| info.for_query(url_query))
    }

    /// The tile query, `None` when the engine renders the tiles.
    fn sql(&self) -> Option<&PostgresSqlInfo> {
        match &self.tiler {
            PostgresTiler::Sql(info) => Some(info),
            PostgresTiler::Engine(_) => None,
        }
    }

    /// The declared tile info, with the encoding the bytes carry when the function compressed them.
    fn tile_info_for(&self, data: &[u8]) -> TileInfo {
        match Encoding::detect(data) {
            Some(encoding) => TileInfo::new(self.tile_info.format, encoding),
            None => self.tile_info,
        }
    }

    /// Runs the tile query, returning the row when the query produced one.
    #[instrument(
        level = "debug",
        skip_all,
        fields(
            source.id = %self.id,
            tile.z = xyz.z(),
            tile.x = xyz.x(),
            tile.y = xyz.y(),
        ),
        err(Debug),
    )]
    async fn query_row(
        &self,
        info: &PostgresSqlInfo,
        xyz: TileCoord,
        url_query: Option<&UrlQuery>,
    ) -> MartinCoreResult<Option<Row>> {
        let query = self.tile_query(info, &info.sql_query, xyz, url_query).await?;
        let row = query.conn.query_opt(&query.statement, &query.params()).await;
        Ok(row.map_err(|e| self.run_error(e, xyz, url_query, info.use_url_query))?)
    }

    /// Runs the row-per-feature query, returning one row per feature of the tile.
    #[instrument(
        level = "debug",
        skip_all,
        fields(
            source.id = %self.id,
            tile.z = xyz.z(),
            tile.x = xyz.x(),
            tile.y = xyz.y(),
        ),
        err(Debug),
    )]
    async fn query_feature_rows(
        &self,
        info: &PostgresSqlInfo,
        row_query: &PostgresRowQuery,
        xyz: TileCoord,
        url_query: Option<&UrlQuery>,
        keep_measures: bool,
    ) -> MartinCoreResult<Vec<Row>> {
        let sql = if keep_measures {
            &row_query.measured_sql_query
        } else {
            &row_query.sql_query
        };
        let query = self.tile_query(info, sql, xyz, url_query).await?;
        let rows = query.conn.query(&query.statement, &query.params()).await;
        Ok(rows.map_err(|e| self.run_error(e, xyz, url_query, info.use_url_query))?)
    }

    /// Prepares one of this source's tile queries and binds `xyz` and the query string to it.
    ///
    /// All of them take `z/x/y` and an optional query string, and differ only in what they
    /// return, so every caller runs the statement itself.
    async fn tile_query(
        &self,
        info: &PostgresSqlInfo,
        sql: &str,
        xyz: TileCoord,
        url_query: Option<&UrlQuery>,
    ) -> MartinCoreResult<TileQuery> {
        let conn = self.pool.get().await?;
        let guard = self.pool.active_query_registry().register(conn.cancel_token());

        let param_types: &[Type] = if info.use_url_query {
            &[Type::INT2, Type::INT8, Type::INT8, Type::JSON]
        } else {
            &[Type::INT2, Type::INT8, Type::INT8]
        };
        let statement = conn
            .prepare_typed_cached(sql, param_types)
            .await
            .map_err(|e| PrepareQueryError {
                source: e,
                source_id: self.id.clone(),
                signature: info.signature.clone(),
                query: sql.to_owned(),
            })?;

        let url_query = if info.use_url_query {
            let json = query_to_json(url_query);
            debug!(sql = %sql, tile.coord = %xyz, url_query = ?json, "Running tile query");
            Some(json)
        } else {
            debug!(sql = %sql, tile.coord = %xyz, "Running tile query");
            None
        };

        Ok(TileQuery {
            conn,
            _cancel_guard: guard,
            statement,
            z: i16::from(xyz.z()),
            x: i64::from(xyz.x()),
            y: i64::from(xyz.y()),
            url_query,
        })
    }

    fn run_error(
        &self,
        e: deadpool_postgres::tokio_postgres::Error,
        xyz: TileCoord,
        url_query: Option<&UrlQuery>,
        use_url_query: bool,
    ) -> PostgresError {
        if use_url_query {
            GetTileWithQueryError(e, self.id.clone(), xyz, url_query.cloned())
        } else {
            GetTileError(e, self.id.clone(), xyz)
        }
    }
}

/// A prepared tile query with its parameters bound, ready to run on `conn`.
///
/// It holds the registry guard, so the statement stays cancellable for exactly as long as the
/// query lives.
struct TileQuery {
    conn: Object,
    _cancel_guard: ActiveQueryGuard,
    statement: Statement,
    z: i16,
    x: i64,
    y: i64,
    url_query: Option<Json<HashMap<String, serde_json::Value>>>,
}

impl TileQuery {
    fn params(&self) -> Vec<&(dyn ToSql + Sync)> {
        let mut params: Vec<&(dyn ToSql + Sync)> = vec![&self.z, &self.x, &self.y];
        if let Some(url_query) = &self.url_query {
            params.push(url_query);
        }
        params
    }
}

#[derive(Clone, Debug)]
/// SQL query information for `PostgreSQL` tile sources.
pub struct PostgresSqlInfo {
    /// SQL query string.
    pub sql_query: String,
    /// Whether the query uses URL query parameters.
    pub use_url_query: bool,
    /// Whether an empty tile implies that all tiles below it are empty.
    pub empty_tile_implies_empty_children: bool,
    /// Signature of the query.
    pub signature: String,
    /// Whether the query's second column is the tile's `ETag`.
    pub has_etag_column: bool,
    /// The variant to run for a request without a query string, when the function has one.
    pub queryless: Option<Box<Self>>,
    /// The same tile as one row per feature, when the source can be read that way.
    pub row_query: Option<PostgresRowQuery>,
}

/// The row-per-feature form of a tile query, and what its rows make up.
///
/// Unlike [`PostgresSqlInfo::sql_query`] this hands out the features themselves rather than an
/// MVT blob, so a caller that wants another tile format does not have to take `ST_AsMVT`'s
/// output apart again. Only table sources have one: a function source returns a blob built by
/// user SQL, which has no row form.
#[derive(Clone, Debug)]
pub struct PostgresRowQuery {
    /// SQL taking `$1/$2/$3` as `z/x/y` and returning one row per feature, the geometry first.
    pub sql_query: String,
    /// [`Self::sql_query`], but keeping the M ordinates of polygons, which `ST_AsMVTGeom` strips.
    pub measured_sql_query: String,
    /// Whether the second column is the feature id.
    pub has_id_column: bool,
    /// The name of the layer the features make up.
    pub layer_name: String,
    /// The tile extent the geometries are expressed in.
    pub extent: u32,
}

impl PostgresSqlInfo {
    /// Creates new SQL query information.
    #[must_use]
    pub const fn new(
        query: String,
        has_query_params: bool,
        empty_tile_implies_empty_children: bool,
        signature: String,
        has_etag_column: bool,
    ) -> Self {
        Self {
            sql_query: query,
            use_url_query: has_query_params,
            empty_tile_implies_empty_children,
            signature,
            has_etag_column,
            queryless: None,
            row_query: None,
        }
    }

    /// This query with `queryless` answering the requests that carry no query string.
    #[must_use]
    pub fn with_queryless(mut self, queryless: Self) -> Self {
        self.queryless = Some(Box::new(queryless));
        self
    }

    /// This query with `row_query` as the row-per-feature form of the same tile.
    #[must_use]
    pub fn with_row_query(mut self, row_query: PostgresRowQuery) -> Self {
        self.row_query = Some(row_query);
        self
    }

    /// The query answering a request, by whether the request carries a query string.
    fn for_query(&self, url_query: Option<&UrlQuery>) -> &Self {
        match (&self.queryless, url_query) {
            (Some(queryless), None) => queryless,
            _ => self,
        }
    }
}