macrostrat.raster_layers 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.3
2
+ Name: macrostrat.raster_layers
3
+ Version: 0.1.0
4
+ Summary: Serve indexed cloud-optimized rasters as mosaicked tile layers
5
+ Author: Daven Quinn
6
+ Author-email: Daven Quinn <dev@davenquinn.com>
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: macrostrat-raster-index>=0.1.0,<1
12
+ Requires-Dist: macrostrat-utils>=1.3.3,<2
13
+ Requires-Dist: titiler-core>=1,<2
14
+ Requires-Dist: titiler-mosaic>=1,<2
15
+ Requires-Dist: rio-tiler>=8,<9
16
+ Requires-Dist: fastapi>=0.111,<0.140
17
+ Requires-Dist: attrs>=23.1
18
+ Requires-Dist: pydantic>=2.7,<3
19
+ Requires-Python: >=3.11, <4
20
+ Project-URL: Repository, https://github.com/UW-Macrostrat/python-libraries
21
+ Project-URL: Documentation, https://github.com/UW-Macrostrat/python-libraries/tree/main/raster-layers#readme
22
+ Description-Content-Type: text/markdown
23
+
24
+ # `macrostrat.raster_layers`
25
+
26
+ Serve the layers in a [`macrostrat.raster_index`](https://github.com/UW-Macrostrat/python-libraries/tree/main/raster-index) database as
27
+ mosaicked map tiles, as FastAPI routes mountable in any application.
28
+
29
+ Given a tile, the index says which COGs cover it and in what order; this package
30
+ reads them, composites them, and renders the result. It is titiler's
31
+ `MosaicTilerFactory` with the assets coming from a live spatial query instead of
32
+ a MosaicJSON document, so tiling, rescaling, colormaps and output formats are all
33
+ inherited rather than reimplemented.
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from fastapi import FastAPI
39
+ from macrostrat.raster_index import RasterIndex
40
+ from macrostrat.raster_layers import RasterLayerConfig, register_raster_layers
41
+
42
+ app = FastAPI()
43
+ index = RasterIndex("postgresql://localhost:5432/macrostrat")
44
+
45
+ register_raster_layers(
46
+ app,
47
+ index,
48
+ [
49
+ # A unified layer over several indexed collections, composited in order.
50
+ RasterLayerConfig(
51
+ slug="mineral-maps",
52
+ layers=["emit-minerals", "aviris-minerals"],
53
+ resampling="nearest", # categorical data
54
+ ),
55
+ RasterLayerConfig(slug="elevation", resampling="bilinear"),
56
+ ],
57
+ prefix="/rasters",
58
+ )
59
+ ```
60
+
61
+ Each layer gets titiler's full mosaic route set — `/tiles/{tileMatrixSetId}/{z}/{x}/{y}`,
62
+ `/{tileMatrixSetId}/tilejson.json`, `/info`, `/point/{lon},{lat}`, the
63
+ `/assets` lookups — plus two of its own:
64
+
65
+ - `/footprints/{z}/{x}/{y}` — coverage as a **vector tile**, MVT layer
66
+ `raster_footprints`. The raster counterpart to a map-footprints layer: where
67
+ the data is, without reading a pixel.
68
+ - `/footprints` — the same thing as GeoJSON, for small layers and diagnostics.
69
+
70
+ `register_raster_layers` installs its own exception handlers, so a host
71
+ application needs no extra setup. Don't register titiler's `MOSAIC_STATUS_CODES`
72
+ *after* mounting — it would replace the no-coverage handler with one that
73
+ returns a body-carrying 204 (see below).
74
+
75
+ ## Behavior worth knowing
76
+
77
+ - **Overscaled tiles keep rendering.** Zooming past a raster's native
78
+ resolution magnifies it rather than making the layer vanish, which is what
79
+ every other raster service does. Set `allow_overscaled=False` in
80
+ `backend_options` for the opposite; `raster_layers.should_generate_tile` in
81
+ the index is the right tool for deciding what to *cache*.
82
+ - **No coverage is a bodyless `204`, with an explicit `Content-Length: 0`.**
83
+ Both details matter: titiler's stock handler returns a 204 carrying a JSON
84
+ body, and Starlette omits the length header entirely — either one makes
85
+ Varnish fail the fetch and turn ordinary panning into 503s. Watch out for
86
+ compression middleware too: gzipping an empty body re-attaches a
87
+ `content-length` and reintroduces the same failure.
88
+ - **Colormaps default per layer.** Categorical rasters are unreadable without
89
+ their palette, so when a request doesn't send one, the layer's `colormap` from
90
+ the index is used. An explicit `colormap` / `colormap_name` query parameter
91
+ always wins.
92
+ - **Whole-mosaic operations are unsupported.** `/info`, `/statistics`, `/preview`
93
+ and friends would mean reading every raster in a layer; layer-wide metadata
94
+ belongs to the index.
95
+ - **No tile caching.** Left to the host application's caching layer.
@@ -0,0 +1,72 @@
1
+ # `macrostrat.raster_layers`
2
+
3
+ Serve the layers in a [`macrostrat.raster_index`](https://github.com/UW-Macrostrat/python-libraries/tree/main/raster-index) database as
4
+ mosaicked map tiles, as FastAPI routes mountable in any application.
5
+
6
+ Given a tile, the index says which COGs cover it and in what order; this package
7
+ reads them, composites them, and renders the result. It is titiler's
8
+ `MosaicTilerFactory` with the assets coming from a live spatial query instead of
9
+ a MosaicJSON document, so tiling, rescaling, colormaps and output formats are all
10
+ inherited rather than reimplemented.
11
+
12
+ ## Usage
13
+
14
+ ```python
15
+ from fastapi import FastAPI
16
+ from macrostrat.raster_index import RasterIndex
17
+ from macrostrat.raster_layers import RasterLayerConfig, register_raster_layers
18
+
19
+ app = FastAPI()
20
+ index = RasterIndex("postgresql://localhost:5432/macrostrat")
21
+
22
+ register_raster_layers(
23
+ app,
24
+ index,
25
+ [
26
+ # A unified layer over several indexed collections, composited in order.
27
+ RasterLayerConfig(
28
+ slug="mineral-maps",
29
+ layers=["emit-minerals", "aviris-minerals"],
30
+ resampling="nearest", # categorical data
31
+ ),
32
+ RasterLayerConfig(slug="elevation", resampling="bilinear"),
33
+ ],
34
+ prefix="/rasters",
35
+ )
36
+ ```
37
+
38
+ Each layer gets titiler's full mosaic route set — `/tiles/{tileMatrixSetId}/{z}/{x}/{y}`,
39
+ `/{tileMatrixSetId}/tilejson.json`, `/info`, `/point/{lon},{lat}`, the
40
+ `/assets` lookups — plus two of its own:
41
+
42
+ - `/footprints/{z}/{x}/{y}` — coverage as a **vector tile**, MVT layer
43
+ `raster_footprints`. The raster counterpart to a map-footprints layer: where
44
+ the data is, without reading a pixel.
45
+ - `/footprints` — the same thing as GeoJSON, for small layers and diagnostics.
46
+
47
+ `register_raster_layers` installs its own exception handlers, so a host
48
+ application needs no extra setup. Don't register titiler's `MOSAIC_STATUS_CODES`
49
+ *after* mounting — it would replace the no-coverage handler with one that
50
+ returns a body-carrying 204 (see below).
51
+
52
+ ## Behavior worth knowing
53
+
54
+ - **Overscaled tiles keep rendering.** Zooming past a raster's native
55
+ resolution magnifies it rather than making the layer vanish, which is what
56
+ every other raster service does. Set `allow_overscaled=False` in
57
+ `backend_options` for the opposite; `raster_layers.should_generate_tile` in
58
+ the index is the right tool for deciding what to *cache*.
59
+ - **No coverage is a bodyless `204`, with an explicit `Content-Length: 0`.**
60
+ Both details matter: titiler's stock handler returns a 204 carrying a JSON
61
+ body, and Starlette omits the length header entirely — either one makes
62
+ Varnish fail the fetch and turn ordinary panning into 503s. Watch out for
63
+ compression middleware too: gzipping an empty body re-attaches a
64
+ `content-length` and reintroduces the same failure.
65
+ - **Colormaps default per layer.** Categorical rasters are unreadable without
66
+ their palette, so when a request doesn't send one, the layer's `colormap` from
67
+ the index is used. An explicit `colormap` / `colormap_name` query parameter
68
+ always wins.
69
+ - **Whole-mosaic operations are unsupported.** `/info`, `/statistics`, `/preview`
70
+ and friends would mean reading every raster in a layer; layer-wide metadata
71
+ belongs to the index.
72
+ - **No tile caching.** Left to the host application's caching layer.
@@ -0,0 +1,29 @@
1
+ """Serve indexed cloud-optimized rasters as mosaicked tile layers.
2
+
3
+ Reads assets from a `macrostrat.raster_index` database and composites them into
4
+ tiles, as FastAPI routes that can be mounted into any application.
5
+ """
6
+
7
+ from .backend import PGRasterMosaic
8
+ from .factory import (
9
+ MVT_MEDIA_TYPE,
10
+ LayerListParams,
11
+ RasterMosaicFactory,
12
+ fixed_layers,
13
+ )
14
+ from .layers import (
15
+ RasterLayerConfig,
16
+ install_exception_handlers,
17
+ register_raster_layers,
18
+ )
19
+
20
+ __all__ = [
21
+ "PGRasterMosaic",
22
+ "RasterMosaicFactory",
23
+ "RasterLayerConfig",
24
+ "register_raster_layers",
25
+ "install_exception_handlers",
26
+ "fixed_layers",
27
+ "LayerListParams",
28
+ "MVT_MEDIA_TYPE",
29
+ ]
@@ -0,0 +1,118 @@
1
+ """A mosaic reader whose assets come from the raster index.
2
+
3
+ rio-tiler 8 owns the mosaic backend contract (`rio_tiler.mosaic.backend`), so all
4
+ this class supplies is the three asset-lookup methods — "which rasters cover
5
+ this tile / point / bbox?" — and the answer is a spatial query rather than a
6
+ MosaicJSON document. Reading, compositing and pixel selection are inherited.
7
+
8
+ Assets are hrefs (plain strings), which is what the base class expects: it
9
+ passes them straight to the reader and reports them back as the asset list.
10
+ """
11
+
12
+ from typing import Any, Optional
13
+
14
+ import attr
15
+ from morecantile import TileMatrixSet
16
+ from rasterio.crs import CRS
17
+ from rasterio.warp import transform_bounds
18
+ from rio_tiler.constants import WEB_MERCATOR_TMS, WGS84_CRS
19
+ from rio_tiler.io import BaseReader, Reader
20
+ from rio_tiler.mosaic.backend import BaseBackend
21
+ from rio_tiler.types import BBox
22
+
23
+ from macrostrat.raster_index import RasterIndex
24
+ from macrostrat.utils import get_logger
25
+
26
+ log = get_logger(__name__)
27
+
28
+ __all__ = ["PGRasterMosaic"]
29
+
30
+ # The zoom at which a point query is resolved to a tile for asset lookup. Deep
31
+ # enough that a point in a small raster doesn't pull in every raster nearby.
32
+ POINT_LOOKUP_ZOOM = 14
33
+
34
+
35
+ @attr.s
36
+ class PGRasterMosaic(BaseBackend):
37
+ """Composite every indexed raster covering the requested area.
38
+
39
+ `input` is the list of layer slugs to composite, in priority order — the
40
+ mosaic's identity is the layer list, not a path.
41
+ """
42
+
43
+ input: list[str] = attr.ib()
44
+ index: Optional[RasterIndex] = attr.ib(default=None)
45
+
46
+ tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
47
+ reader: type[BaseReader] = attr.ib(default=Reader)
48
+ reader_options: dict = attr.ib(factory=dict)
49
+
50
+ # Forwarded to `raster_layers.get_rasters`: how far below a raster's own
51
+ # minzoom it may still be read.
52
+ zoom_tolerance: int = attr.ib(default=3)
53
+ # Whether to keep serving data past its native resolution. On by default: a
54
+ # layer that vanishes when you zoom in reads as a bug, and a magnified tile
55
+ # is what every other raster service gives you. `should_generate_tile` in
56
+ # the index is the right tool for deciding what to *cache*.
57
+ allow_overscaled: bool = attr.ib(default=True)
58
+
59
+ bounds: BBox = attr.ib(init=False, default=(-180, -90, 180, 90))
60
+ crs: CRS = attr.ib(init=False, default=WGS84_CRS)
61
+ minzoom: int = attr.ib(init=False, default=None)
62
+ maxzoom: int = attr.ib(init=False, default=None)
63
+
64
+ def __attrs_post_init__(self):
65
+ if self.index is None:
66
+ raise ValueError("PGRasterMosaic requires a RasterIndex")
67
+ if isinstance(self.input, str):
68
+ self.input = [self.input]
69
+
70
+ bounds = self.index.layer_bounds(self.input)
71
+ if bounds is not None:
72
+ self.bounds = bounds
73
+
74
+ # Without a mosaic document, the grid is the only authority on zoom range.
75
+ self.minzoom = self.tms.minzoom
76
+ self.maxzoom = self.tms.maxzoom
77
+
78
+ # -- Asset lookup ------------------------------------------------------
79
+ #
80
+ # Each returns hrefs, and an empty list where there's no coverage. The base
81
+ # class turns "empty" into `NoAssetFoundError` *before* opening any reader,
82
+ # so a miss costs one indexed query and nothing more.
83
+
84
+ def assets_for_tile(self, x: int, y: int, z: int, **kwargs: Any) -> list[str]:
85
+ assets = self.index.assets_for_tile(
86
+ x, y, z, self.input, zoom_tolerance=self.zoom_tolerance
87
+ )
88
+ if not self.allow_overscaled:
89
+ assets = [a for a in assets if not a.overscaled]
90
+ return [a.href for a in assets]
91
+
92
+ def assets_for_point(
93
+ self,
94
+ lng: float,
95
+ lat: float,
96
+ coord_crs: Optional[CRS] = None,
97
+ **kwargs: Any,
98
+ ) -> list[str]:
99
+ if coord_crs is not None and coord_crs != WGS84_CRS:
100
+ lng, lat, _, _ = transform_bounds(coord_crs, WGS84_CRS, lng, lat, lng, lat)
101
+ tile = self.tms.tile(lng, lat, POINT_LOOKUP_ZOOM)
102
+ return self.assets_for_tile(tile.x, tile.y, tile.z)
103
+
104
+ def assets_for_bbox(
105
+ self,
106
+ xmin: float,
107
+ ymin: float,
108
+ xmax: float,
109
+ ymax: float,
110
+ coord_crs: Optional[CRS] = None,
111
+ **kwargs: Any,
112
+ ) -> list[str]:
113
+ if coord_crs is not None and coord_crs != WGS84_CRS:
114
+ xmin, ymin, xmax, ymax = transform_bounds(
115
+ coord_crs, WGS84_CRS, xmin, ymin, xmax, ymax
116
+ )
117
+ assets = self.index.assets_for_bbox(xmin, ymin, xmax, ymax, self.input)
118
+ return [a.href for a in assets]
@@ -0,0 +1,174 @@
1
+ """FastAPI routes for serving indexed raster layers.
2
+
3
+ `RasterMosaicFactory` is titiler's `MosaicTilerFactory` with the index bound in
4
+ as its backend. Since rio-tiler 8 moved the mosaic backend contract into
5
+ rio-tiler itself, every route titiler registers — tiles, tilejson, info, point,
6
+ assets — works against an index-backed mosaic unchanged. What's added here is
7
+ the layer's own default colormap and a footprints layer.
8
+ """
9
+
10
+ from collections.abc import Callable
11
+ from functools import partial
12
+ from typing import Any, Optional
13
+
14
+ from attrs import define, field
15
+ from fastapi import Depends, Path, Query
16
+ from starlette.responses import JSONResponse, Response
17
+ from titiler.core.dependencies import ColorMapParams
18
+ from titiler.mosaic.factory import MosaicTilerFactory
19
+ from typing_extensions import Annotated
20
+
21
+ from macrostrat.raster_index import RasterIndex
22
+ from macrostrat.utils import get_logger
23
+
24
+ from .backend import PGRasterMosaic
25
+
26
+ log = get_logger(__name__)
27
+
28
+ __all__ = ["RasterMosaicFactory", "fixed_layers", "LayerListParams", "MVT_MEDIA_TYPE"]
29
+
30
+ MVT_MEDIA_TYPE = "application/vnd.mapbox-vector-tile"
31
+
32
+
33
+ def fixed_layers(*slugs: str) -> Callable[[], list[str]]:
34
+ """A path dependency serving a fixed set of layers.
35
+
36
+ The usual case: a route that *is* a layer, with the layer list baked in
37
+ rather than accepted from the client.
38
+ """
39
+
40
+ def dependency() -> list[str]:
41
+ return list(slugs)
42
+
43
+ return dependency
44
+
45
+
46
+ def LayerListParams(
47
+ layers: Annotated[
48
+ str, Query(description="Comma-delimited raster layers to composite")
49
+ ] = "",
50
+ ) -> list[str]:
51
+ """A path dependency letting the client choose and order layers."""
52
+ return [slug for slug in layers.split(",") if slug]
53
+
54
+
55
+ @define(kw_only=True)
56
+ class RasterMosaicFactory(MosaicTilerFactory):
57
+ """Tile routes for one or more layers in a raster index."""
58
+
59
+ index: Optional[RasterIndex] = field(default=None)
60
+
61
+ # Required by the parent, but we always supply it ourselves in
62
+ # `__attrs_post_init__` — the backend has to carry the index.
63
+ backend: Any = field(default=None)
64
+
65
+ # Colormap used when the request doesn't specify one. Falls back to the
66
+ # layer's own colormap in the index (categorical rasters are unreadable
67
+ # without it, and clients shouldn't have to know a 40-entry palette).
68
+ default_colormap: Optional[dict] = field(default=None)
69
+ use_index_colormap: bool = field(default=True)
70
+
71
+ # Forwarded to `PGRasterMosaic` (e.g. `allow_overscaled`, `zoom_tolerance`).
72
+ backend_options: dict = field(factory=dict)
73
+
74
+ # The viewer template pulls in remote assets; not useful for these layers.
75
+ add_viewer: bool = field(default=False)
76
+
77
+ _colormap_cache: dict = field(factory=dict, init=False)
78
+
79
+ def __attrs_post_init__(self):
80
+ if self.index is None:
81
+ raise ValueError("RasterMosaicFactory requires a RasterIndex")
82
+ # titiler constructs the backend itself, and `backend_dependency` can't
83
+ # carry a non-request-scoped object, so bind the index with a partial.
84
+ self.backend = partial(PGRasterMosaic, index=self.index, **self.backend_options)
85
+ self.colormap_dependency = self._colormap_dependency()
86
+ super().__attrs_post_init__()
87
+
88
+ def register_routes(self):
89
+ super().register_routes()
90
+ self.footprints()
91
+
92
+ def footprints(self):
93
+ """Coverage of these layers, without reading any pixels."""
94
+
95
+ @self.router.get(
96
+ "/footprints/{z}/{x}/{y}",
97
+ responses={
98
+ 200: {
99
+ "content": {MVT_MEDIA_TYPE: {}},
100
+ "description": "Raster footprints as a vector tile",
101
+ }
102
+ },
103
+ response_class=Response,
104
+ )
105
+ def footprint_tile(
106
+ z: Annotated[int, Path(description="Tile zoom level")],
107
+ x: Annotated[int, Path(description="Tile column")],
108
+ y: Annotated[int, Path(description="Tile row")],
109
+ src_path=Depends(self.path_dependency),
110
+ ):
111
+ """Raster footprints as a vector tile (layer `raster_footprints`)."""
112
+ data = self.index.footprint_tile(x, y, z, src_path)
113
+ return Response(data, media_type=MVT_MEDIA_TYPE)
114
+
115
+ @self.router.get(
116
+ "/footprints",
117
+ responses={200: {"description": "Raster footprints as GeoJSON"}},
118
+ )
119
+ def footprints(src_path=Depends(self.path_dependency)):
120
+ """Every footprint in these layers, as a GeoJSON FeatureCollection."""
121
+ return JSONResponse(self.index.footprints(src_path))
122
+
123
+ # -- Colormap resolution -----------------------------------------------
124
+
125
+ def _colormap_dependency(self) -> Callable[..., Optional[Any]]:
126
+ """Wrap titiler's colormap params with a per-layer default."""
127
+
128
+ def dependency(
129
+ colormap=Depends(ColorMapParams),
130
+ src_path=Depends(self.path_dependency),
131
+ ) -> Optional[Any]:
132
+ if colormap:
133
+ return colormap
134
+ return self._layer_colormap(tuple(src_path))
135
+
136
+ return dependency
137
+
138
+ def _layer_colormap(self, layers: tuple[str, ...]) -> Optional[dict]:
139
+ if self.default_colormap is not None:
140
+ return self.default_colormap
141
+ if not self.use_index_colormap:
142
+ return None
143
+ if layers in self._colormap_cache:
144
+ return self._colormap_cache[layers]
145
+
146
+ colormap = None
147
+ try:
148
+ # First layer that defines one wins, matching compositing priority.
149
+ by_slug = {l.slug: l.colormap for l in self.index.layers()}
150
+ for slug in layers:
151
+ if by_slug.get(slug):
152
+ colormap = normalize_colormap(by_slug[slug])
153
+ break
154
+ except Exception as err: # pragma: no cover - degraded, not fatal
155
+ log.warning("Could not resolve colormap for %s: %s", layers, err)
156
+ return None
157
+
158
+ self._colormap_cache[layers] = colormap
159
+ return colormap
160
+
161
+
162
+ def normalize_colormap(colormap: dict) -> dict:
163
+ """Coerce a stored colormap into rio-tiler's `{int: (r, g, b, a)}` form.
164
+
165
+ JSON object keys are strings, and colormaps captured from a GDAL color table
166
+ may be RGB triples rather than RGBA.
167
+ """
168
+ result = {}
169
+ for key, value in colormap.items():
170
+ color = list(value)
171
+ if len(color) == 3:
172
+ color.append(255)
173
+ result[int(key)] = tuple(color[:4])
174
+ return result
@@ -0,0 +1,139 @@
1
+ """Canned layer definitions.
2
+
3
+ A `RasterLayerConfig` is the serving-side counterpart to a row in
4
+ `raster_layers.layer`: the index says what a layer *is*, this says how it should
5
+ be *rendered and mounted*. Written as data so a host application declares its
6
+ raster layers in a list, the way the tileserver already declares vector layers.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Optional
11
+
12
+ from fastapi import APIRouter, FastAPI, Query, Request
13
+ from starlette.responses import Response
14
+ from rio_tiler.types import RIOResampling
15
+ from titiler.core.dependencies import DatasetParams
16
+ from titiler.core.errors import add_exception_handlers
17
+ from titiler.core.resources.enums import OptionalHeader
18
+ from titiler.mosaic.errors import MOSAIC_STATUS_CODES
19
+ from typing_extensions import Annotated
20
+
21
+ from macrostrat.raster_index import RasterIndex
22
+
23
+ from .factory import RasterMosaicFactory, fixed_layers
24
+
25
+ __all__ = [
26
+ "RasterLayerConfig",
27
+ "register_raster_layers",
28
+ "install_exception_handlers",
29
+ ]
30
+
31
+
32
+ @dataclass
33
+ class RasterLayerConfig:
34
+ """One mounted raster layer.
35
+
36
+ `layers` may name several indexed layers, composited in the order given —
37
+ that is how a "unified" layer over several sub-collections is built.
38
+ """
39
+
40
+ slug: str
41
+ layers: Optional[list[str]] = None
42
+ title: Optional[str] = None
43
+ # Applies to how pixels are sampled when a tile doesn't line up with the
44
+ # raster grid. Categorical rasters (classification maps) must stay `nearest`;
45
+ # continuous ones (elevation, geophysics) look far better bilinear.
46
+ resampling: str = "nearest"
47
+ colormap: Optional[dict] = None
48
+ # Look the colormap up from the index when the request doesn't supply one.
49
+ use_index_colormap: bool = True
50
+ # Forwarded to the backend — notably `allow_overscaled` and `zoom_tolerance`.
51
+ backend_options: dict = field(default_factory=dict)
52
+ optional_headers: list[OptionalHeader] = field(
53
+ default_factory=lambda: [OptionalHeader.x_assets]
54
+ )
55
+
56
+ @property
57
+ def layer_slugs(self) -> list[str]:
58
+ return self.layers or [self.slug]
59
+
60
+ def router(self, index: RasterIndex) -> APIRouter:
61
+ factory = RasterMosaicFactory(
62
+ index=index,
63
+ path_dependency=fixed_layers(*self.layer_slugs),
64
+ dataset_dependency=_dataset_params(self.resampling),
65
+ default_colormap=self.colormap,
66
+ use_index_colormap=self.use_index_colormap,
67
+ backend_options=self.backend_options,
68
+ optional_headers=self.optional_headers,
69
+ )
70
+ return factory.router
71
+
72
+
73
+ async def _empty_tile(request: Request, exc: Exception) -> Response:
74
+ """An empty, explicitly zero-length 204.
75
+
76
+ Two things have to be right here, because running off the edge of coverage
77
+ is routine and must never reach the client as an error:
78
+
79
+ - **No body.** titiler's own handler renders a JSON payload at this status,
80
+ and a 204 carrying a body is malformed.
81
+ - **An explicit `Content-Length: 0`.** Starlette omits the header entirely
82
+ for a 204, which leaves the response close-delimited; Varnish then tries
83
+ to read a body it will never get and fails the fetch with a 503.
84
+ """
85
+ return Response(status_code=204, headers={"content-length": "0"})
86
+
87
+
88
+ def install_exception_handlers(app: FastAPI) -> None:
89
+ """Map "no coverage" onto an empty tile rather than a server error.
90
+
91
+ A tile request outside a layer's rasters is *normal operation* — panning to
92
+ the edge of coverage does it constantly — so it must not surface as a 5xx or
93
+ a logged traceback. Registering these with the routes means a host
94
+ application gets the behavior by mounting the layers, without having to know
95
+ these exceptions exist.
96
+ """
97
+ for exc, status in MOSAIC_STATUS_CODES.items():
98
+ if status == 204:
99
+ app.add_exception_handler(exc, _empty_tile)
100
+ else:
101
+ add_exception_handlers(app, {exc: status})
102
+
103
+
104
+ def register_raster_layers(
105
+ app: FastAPI,
106
+ index: RasterIndex,
107
+ configs: list[RasterLayerConfig],
108
+ *,
109
+ prefix: str = "",
110
+ tags: Optional[list[str]] = None,
111
+ ) -> None:
112
+ """Mount each layer at `<prefix>/<slug>`."""
113
+ install_exception_handlers(app)
114
+ for config in configs:
115
+ app.include_router(
116
+ config.router(index),
117
+ prefix=f"{prefix}/{config.slug}",
118
+ tags=tags or ["Rasters"],
119
+ )
120
+
121
+
122
+ def _dataset_params(resampling: str) -> type[DatasetParams]:
123
+ """A `DatasetParams` whose resampling default matches the layer's data.
124
+
125
+ The `resampling` query parameter still overrides it; this only changes what a
126
+ plain tile request gets.
127
+ """
128
+
129
+ @dataclass
130
+ class LayerDatasetParams(DatasetParams):
131
+ resampling_method: Annotated[
132
+ RIOResampling,
133
+ Query(
134
+ alias="resampling",
135
+ description=f"RasterIO resampling algorithm. Defaults to `{resampling}`.",
136
+ ),
137
+ ] = resampling
138
+
139
+ return LayerDatasetParams
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "macrostrat.raster_layers"
3
+ version = "0.1.0"
4
+ description = "Serve indexed cloud-optimized rasters as mosaicked tile layers"
5
+ authors = [{ name = "Daven Quinn", email = "dev@davenquinn.com" }]
6
+ requires-python = ">=3.11,<4"
7
+ readme = "README.md"
8
+ classifiers = [
9
+ "Programming Language :: Python :: 3",
10
+ "Programming Language :: Python :: 3.11",
11
+ "Programming Language :: Python :: 3.12",
12
+ "Programming Language :: Python :: 3.13",
13
+ ]
14
+ dependencies = [
15
+ "macrostrat.raster_index>=0.1.0,<1",
16
+ "macrostrat.utils>=1.3.3,<2",
17
+ "titiler.core>=1,<2",
18
+ "titiler.mosaic>=1,<2",
19
+ "rio-tiler>=8,<9",
20
+ "fastapi>=0.111,<0.140",
21
+ "attrs>=23.1",
22
+ "pydantic>=2.7,<3",
23
+ ]
24
+
25
+ [project.urls]
26
+ Repository = "https://github.com/UW-Macrostrat/python-libraries"
27
+ Documentation = "https://github.com/UW-Macrostrat/python-libraries/tree/main/raster-layers#readme"
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "macrostrat.raster_index",
32
+ "macrostrat.utils",
33
+ "pytest>=7.2,<10",
34
+ "httpx>=0.27",
35
+ "pillow>=10.0",
36
+ "mapbox-vector-tile>=2.1.0,<3",
37
+ ]
38
+
39
+ [tool.uv]
40
+ default-groups = "all"
41
+
42
+ # In-repo dependencies, so this package locks and builds on its own — which is
43
+ # what `mono publish` does before releasing it. Note that uv propagates these
44
+ # local paths into anything that depends on this package *by path*: consumers
45
+ # should install from PyPI, not from a sibling checkout, or they inherit
46
+ # unreleased versions of everything below.
47
+ [tool.uv.sources]
48
+ "macrostrat.raster_index" = { path = "../raster-index", editable = true }
49
+ "macrostrat.utils" = { path = "../utils", editable = true }
50
+
51
+ [tool.uv.build-backend]
52
+ module-name = ["macrostrat"]
53
+ module-root = ""
54
+ namespace = true
55
+
56
+ [build-system]
57
+ requires = ["uv_build>=0.9.21,<0.12.0"]
58
+ build-backend = "uv_build"