envlib-api 0.3.0__py3-none-any.whl

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.
Files changed (116) hide show
  1. envlib_api/__init__.py +3 -0
  2. envlib_api/__main__.py +3 -0
  3. envlib_api/api/__init__.py +7 -0
  4. envlib_api/api/app.py +435 -0
  5. envlib_api/api/compress.py +52 -0
  6. envlib_api/api/cost.py +107 -0
  7. envlib_api/api/edr.py +343 -0
  8. envlib_api/api/encode.py +285 -0
  9. envlib_api/api/errors.py +23 -0
  10. envlib_api/api/grid.py +317 -0
  11. envlib_api/api/params.py +71 -0
  12. envlib_api/api/read.py +65 -0
  13. envlib_api/api/resolve.py +191 -0
  14. envlib_api/api/server.py +35 -0
  15. envlib_api/api/stations.py +96 -0
  16. envlib_api/api/timesel.py +97 -0
  17. envlib_api/cli.py +179 -0
  18. envlib_api/config.py +158 -0
  19. envlib_api/healthcheck.py +38 -0
  20. envlib_api/mirror.py +353 -0
  21. envlib_api/refresher.py +265 -0
  22. envlib_api/tests/__init__.py +0 -0
  23. envlib_api/tests/api_support.py +307 -0
  24. envlib_api/tests/conftest.py +12 -0
  25. envlib_api/tests/grid_support.py +217 -0
  26. envlib_api/tests/schemas/README.md +12 -0
  27. envlib_api/tests/schemas/coveragejson/coveragejson.json +1794 -0
  28. envlib_api/tests/schemas/edr/schemas/collections/DataQuery.yaml +38 -0
  29. envlib_api/tests/schemas/edr/schemas/collections/areaDataQuery.yaml +10 -0
  30. envlib_api/tests/schemas/edr/schemas/collections/areaLink.yaml +9 -0
  31. envlib_api/tests/schemas/edr/schemas/collections/collection.yaml +137 -0
  32. envlib_api/tests/schemas/edr/schemas/collections/collections.yaml +26 -0
  33. envlib_api/tests/schemas/edr/schemas/collections/corridorDataQuery.yaml +29 -0
  34. envlib_api/tests/schemas/edr/schemas/collections/corridorLink.yaml +9 -0
  35. envlib_api/tests/schemas/edr/schemas/collections/crsObject.yaml +15 -0
  36. envlib_api/tests/schemas/edr/schemas/collections/cubeDataQuery.yaml +20 -0
  37. envlib_api/tests/schemas/edr/schemas/collections/cubeLink.yaml +9 -0
  38. envlib_api/tests/schemas/edr/schemas/collections/extent.yaml +311 -0
  39. envlib_api/tests/schemas/edr/schemas/collections/instancesDataQuery.yaml +21 -0
  40. envlib_api/tests/schemas/edr/schemas/collections/instancesLink.yaml +9 -0
  41. envlib_api/tests/schemas/edr/schemas/collections/itemsDataQuery.yaml +21 -0
  42. envlib_api/tests/schemas/edr/schemas/collections/itemsLink.yaml +9 -0
  43. envlib_api/tests/schemas/edr/schemas/collections/locationsDataQuery.yaml +10 -0
  44. envlib_api/tests/schemas/edr/schemas/collections/locationsLink.yaml +9 -0
  45. envlib_api/tests/schemas/edr/schemas/collections/observedPropertyCollection.yaml +51 -0
  46. envlib_api/tests/schemas/edr/schemas/collections/parameterNames.yaml +70 -0
  47. envlib_api/tests/schemas/edr/schemas/collections/positionDataQuery.yaml +12 -0
  48. envlib_api/tests/schemas/edr/schemas/collections/positionLink.yaml +9 -0
  49. envlib_api/tests/schemas/edr/schemas/collections/radiusDataQuery.yaml +18 -0
  50. envlib_api/tests/schemas/edr/schemas/collections/radiusLink.yaml +9 -0
  51. envlib_api/tests/schemas/edr/schemas/collections/trajectoryDataQuery.yaml +10 -0
  52. envlib_api/tests/schemas/edr/schemas/collections/trajectoryLink.yaml +9 -0
  53. envlib_api/tests/schemas/edr/schemas/collections/units.yaml +42 -0
  54. envlib_api/tests/schemas/edr/schemas/core/confClasses.yaml +8 -0
  55. envlib_api/tests/schemas/edr/schemas/core/exception.yaml +8 -0
  56. envlib_api/tests/schemas/edr/schemas/core/landingPage.yaml +76 -0
  57. envlib_api/tests/schemas/edr/schemas/core/link.yaml +31 -0
  58. envlib_api/tests/schemas/edr/schemas/covjson/anyAxis.yaml +11 -0
  59. envlib_api/tests/schemas/edr/schemas/covjson/coverage.yaml +14 -0
  60. envlib_api/tests/schemas/edr/schemas/covjson/coverageBase.yaml +68 -0
  61. envlib_api/tests/schemas/edr/schemas/covjson/coverageCollection.yaml +58 -0
  62. envlib_api/tests/schemas/edr/schemas/covjson/coverageJSON.yaml +46 -0
  63. envlib_api/tests/schemas/edr/schemas/covjson/covjsonI18n.yaml +9 -0
  64. envlib_api/tests/schemas/edr/schemas/covjson/covjsonObservedProperty.yaml +29 -0
  65. envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameter.yaml +32 -0
  66. envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameterGroup.yaml +31 -0
  67. envlib_api/tests/schemas/edr/schemas/covjson/covjsonUnit.yaml +31 -0
  68. envlib_api/tests/schemas/edr/schemas/covjson/domain.yaml +7 -0
  69. envlib_api/tests/schemas/edr/schemas/covjson/domainBase.yaml +337 -0
  70. envlib_api/tests/schemas/edr/schemas/covjson/ndArray.yaml +88 -0
  71. envlib_api/tests/schemas/edr/schemas/covjson/numericAxis.yaml +11 -0
  72. envlib_api/tests/schemas/edr/schemas/covjson/numericRegularlySpacedAxis.yaml +17 -0
  73. envlib_api/tests/schemas/edr/schemas/covjson/numericSingleValueAxis.yaml +9 -0
  74. envlib_api/tests/schemas/edr/schemas/covjson/numericValuesAxis.yaml +14 -0
  75. envlib_api/tests/schemas/edr/schemas/covjson/polygonValuesAxis.yaml +29 -0
  76. envlib_api/tests/schemas/edr/schemas/covjson/primitiveValuesAxis.yaml +22 -0
  77. envlib_api/tests/schemas/edr/schemas/covjson/referenceSystem.yaml +48 -0
  78. envlib_api/tests/schemas/edr/schemas/covjson/referenceSystemConnection.yaml +16 -0
  79. envlib_api/tests/schemas/edr/schemas/covjson/stringSingleValueAxis.yaml +9 -0
  80. envlib_api/tests/schemas/edr/schemas/covjson/stringValuesAxis.yaml +14 -0
  81. envlib_api/tests/schemas/edr/schemas/covjson/targetConcept.yaml +13 -0
  82. envlib_api/tests/schemas/edr/schemas/covjson/tiledNdArray.yaml +50 -0
  83. envlib_api/tests/schemas/edr/schemas/covjson/tupleValuesAxis.yaml +24 -0
  84. envlib_api/tests/schemas/edr/schemas/covjson/valuesAxis.yaml +27 -0
  85. envlib_api/tests/schemas/edr/schemas/covjson/valuesAxisBase.yaml +24 -0
  86. envlib_api/tests/schemas/edr/schemas/edr-geojson/edrFeatureCollectionGeoJSON.yaml +32 -0
  87. envlib_api/tests/schemas/edr/schemas/edr-geojson/edrProperties.yaml +49 -0
  88. envlib_api/tests/schemas/edr/schemas/edr-geojson/observedProperty.yaml +26 -0
  89. envlib_api/tests/schemas/edr/schemas/edr-geojson/parameter.yaml +28 -0
  90. envlib_api/tests/schemas/edr/schemas/edr-geojson/unit.yaml +24 -0
  91. envlib_api/tests/schemas/edr/schemas/geojson/featureGeoJSON.yaml +29 -0
  92. envlib_api/tests/schemas/edr/schemas/geojson/geometrycollectionGeoJSON.yaml +19 -0
  93. envlib_api/tests/schemas/edr/schemas/geojson/linestringGeoJSON.yaml +23 -0
  94. envlib_api/tests/schemas/edr/schemas/geojson/multilinestringGeoJSON.yaml +19 -0
  95. envlib_api/tests/schemas/edr/schemas/geojson/multipointGeoJSON.yaml +16 -0
  96. envlib_api/tests/schemas/edr/schemas/geojson/multipolygonGeoJSON.yaml +21 -0
  97. envlib_api/tests/schemas/edr/schemas/geojson/pointGeoJSON.yaml +14 -0
  98. envlib_api/tests/schemas/edr/schemas/geojson/polygonGeoJSON.yaml +19 -0
  99. envlib_api/tests/schemas/edr/schemas/i18n.yaml +4 -0
  100. envlib_api/tests/schemas/edr/schemas/numberMatched.yaml +7 -0
  101. envlib_api/tests/schemas/edr/schemas/numberReturned.yaml +12 -0
  102. envlib_api/tests/schemas/edr/schemas/parameterGroup.yaml +30 -0
  103. envlib_api/tests/schemas/edr/schemas/queries/instances.yaml +26 -0
  104. envlib_api/tests/support.py +320 -0
  105. envlib_api/tests/test_alerting_and_guards.py +325 -0
  106. envlib_api/tests/test_api.py +808 -0
  107. envlib_api/tests/test_api_review.py +428 -0
  108. envlib_api/tests/test_grid.py +1075 -0
  109. envlib_api/tests/test_ops.py +358 -0
  110. envlib_api/tests/test_refresher.py +354 -0
  111. envlib_api/tests/test_schemas.py +91 -0
  112. envlib_api-0.3.0.dist-info/METADATA +408 -0
  113. envlib_api-0.3.0.dist-info/RECORD +116 -0
  114. envlib_api-0.3.0.dist-info/WHEEL +4 -0
  115. envlib_api-0.3.0.dist-info/entry_points.txt +3 -0
  116. envlib_api-0.3.0.dist-info/licenses/LICENSE +201 -0
envlib_api/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """envlib-api: the envlib data API service. The refresher (`envlib_api.refresher`) and the EDR API (`envlib_api.api`)."""
2
+
3
+ __version__ = '0.3.0'
envlib_api/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from envlib_api.cli import app
2
+
3
+ app()
@@ -0,0 +1,7 @@
1
+ """
2
+ The envlib EDR API: an OGC API - Environmental Data Retrieval server for envlib's station
3
+ (`ts_ortho`) datasets, reading only MongoDB, which the refresher fills, and B2 on a chunk-cache miss.
4
+
5
+ Run it with `envlib-api-server`. The refresher's CLI (`envlib_api.cli`) never imports this package,
6
+ so the refresher process stays free of cfdb and FastAPI.
7
+ """
envlib_api/api/app.py ADDED
@@ -0,0 +1,435 @@
1
+ """
2
+ The FastAPI app. Routes are plain (sync) functions, so FastAPI runs them in its thread pool. Each
3
+ request builds its own store and cfdb dataset through `resolve.run`; the process shares only the
4
+ MongoDB client and the B2 HTTP session.
5
+ """
6
+
7
+ import logging
8
+
9
+ import numpy as np
10
+ import pymongo
11
+ import s3func
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.responses import Response
14
+ from starlette.exceptions import HTTPException as StarletteHTTPException
15
+
16
+ from envlib_api.api import compress, cost, edr, encode, grid, params, read, resolve, timesel
17
+ from envlib_api.api.errors import ApiError, NoContent
18
+ from envlib_api.api.stations import Stations, check_point, parse_wkt, within_metres
19
+
20
+ logger = logging.getLogger(__name__)
21
+ ## MongoDB server selection fails after this, not pymongo's default 30 s, so an outage answers 503
22
+ ## quickly instead of holding every thread of the pool (code review edr-api-code-3).
23
+ MONGO_TIMEOUT_MS = 5000
24
+
25
+
26
+ class CacheRefusalAlarm(logging.Filter):
27
+ """
28
+ ebooklet's MongoStore logs a refused chunk-cache insert as a WARNING and serves the bytes anyway,
29
+ so a cache that refuses every insert (a privilege, a validator) serves every read cold, silently.
30
+ This filter on ebooklet's store logger re-logs the first such warning of the process at ERROR,
31
+ which Sentry reports (plan Decision 8, code review edr-api-code-3).
32
+ """
33
+
34
+ MARKERS = ('not cached', 'chunk cache insert failed')
35
+
36
+ def __init__(self):
37
+ super().__init__()
38
+ self.fired = False
39
+
40
+ def filter(self, record):
41
+ if not self.fired and record.levelno == logging.WARNING and any(m in record.getMessage() for m in self.MARKERS):
42
+ self.fired = True
43
+ logger.error(f'The chunk cache refused an insert, so reads stay cold: {record.getMessage()}')
44
+ return True
45
+
46
+
47
+ CACHE_ALARM = CacheRefusalAlarm()
48
+ logging.getLogger('ebooklet.mongo.store').addFilter(CACHE_ALARM)
49
+
50
+
51
+ def _respond(request, body, media_type, status=200, headers=None):
52
+ coding = compress.choose(request.headers.get('accept-encoding'))
53
+ hdrs = {'Vary': 'Accept-Encoding', **(headers or {})}
54
+ if coding is not None:
55
+ body = compress.encode(body, coding)
56
+ hdrs['Content-Encoding'] = coding
57
+ return Response(content=body, status_code=status, media_type=media_type, headers=hdrs)
58
+
59
+
60
+ def _base(cfg, request):
61
+ return (cfg.public_url or str(request.base_url)).rstrip('/')
62
+
63
+
64
+ def _check_conventions(ds, attrs, names):
65
+ """The tsortho conventions the API relies on (envlib's contract guarantees only station_id)."""
66
+ problems = [v for v in edr.STATION_VARS if v not in ds.data_var_names]
67
+ problems += [f'{n}.units' for n in names if not attrs[n].get('units')]
68
+ if not names:
69
+ problems.append('no (point, time) variable')
70
+ crs = getattr(ds, 'crs', None)
71
+ if crs is None or crs.to_epsg() != 4326:
72
+ problems.append(f'crs {crs}')
73
+ if problems:
74
+ raise ApiError(
75
+ 404, 'NotServed', f'This collection does not follow the station-dataset conventions: {problems}.'
76
+ )
77
+
78
+
79
+ def _kind(attempt):
80
+ return (attempt.doc.get('user_meta') or {}).get('dataset_type')
81
+
82
+
83
+ def _require(attempt, query):
84
+ """A query the collection's dataset type does not offer answers 404, naming the ones it does."""
85
+ offered = edr.OFFERED.get(_kind(attempt), ())
86
+ if query not in offered:
87
+ raise ApiError(
88
+ 404,
89
+ 'NotFound',
90
+ f'Collection {attempt.doc["dataset_id"]!r} does not offer the {query} query; it offers {list(offered)}.',
91
+ )
92
+
93
+
94
+ class GridSelection:
95
+ """What a grid query selected: plain-int ranges per dimension, and the labels of each."""
96
+
97
+ def __init__(self, g, ranges, times, cell=None):
98
+ self.grid = g
99
+ self.ranges = ranges # {dim name: (start, stop)}, plain ints
100
+ (i0, i1), (j0, j1) = ranges[g.y_name], ranges[g.x_name]
101
+ self.ys = g.y[i0:i1]
102
+ self.xs = g.x[j0:j1]
103
+ self.zs = g.z[slice(*ranges[g.z_name])] if g.z_name else None
104
+ self.times = times
105
+ if cell is not None: # a position: the cell's indices and its centre in CRS84
106
+ self.i, self.j = cell
107
+ lon, lat = g.lonlat(np.array([self.xs[0]]), np.array([self.ys[0]]))
108
+ self.lon, self.lat = float(lon[0]), float(lat[0])
109
+
110
+ def sel(self, dims):
111
+ return tuple(self.ranges[d] for d in dims)
112
+
113
+
114
+ def _etag(attempt):
115
+ uuid_hex, ts = attempt.store.applied
116
+ return f'"{attempt.doc["_id"]}-{uuid_hex}-{ts}"'
117
+
118
+
119
+ def check_role(db):
120
+ """Log at ERROR if this user cannot fill the chunk cache: reads would then all be cold, silently."""
121
+ try:
122
+ status = db.command('connectionStatus', showPrivileges=True)['authInfo']
123
+ except pymongo.errors.PyMongoError as err:
124
+ logger.error(f'Could not read this user\'s MongoDB privileges: {err}')
125
+ return False
126
+ if not status.get('authenticatedUsers'):
127
+ logger.info('MongoDB has no authenticated user (auth is off): the role check is skipped.')
128
+ return True
129
+ actions = {}
130
+ for priv in status.get('authenticatedUserPrivileges', []):
131
+ res = priv.get('resource', {})
132
+ if res.get('db') in (db.name, '') and 'collection' in res:
133
+ actions.setdefault(res['collection'], set()).update(priv.get('actions', []))
134
+
135
+ def can(coll, action):
136
+ return action in actions.get(coll, set()) or action in actions.get('', set())
137
+
138
+ missing = [f'{a} on {c}' for c in ('datasets', 'entries', 'catalogue', 'chunks') for a in ['find'] if not can(c, a)]
139
+ if not can('chunks', 'insert'):
140
+ missing.append('insert on chunks')
141
+ if missing:
142
+ logger.error(
143
+ f'The API\'s MongoDB user lacks {missing}: without insert every read stays cold (README, "The API\'s role").'
144
+ )
145
+ return False
146
+ return True
147
+
148
+
149
+ def connect(cfg):
150
+ """The process's MongoDB database handle, with short selection and connect timeouts."""
151
+ client = pymongo.MongoClient(
152
+ cfg.mongo_uri,
153
+ tz_aware=True,
154
+ serverSelectionTimeoutMS=MONGO_TIMEOUT_MS,
155
+ connectTimeoutMS=MONGO_TIMEOUT_MS,
156
+ )
157
+ return client[cfg.database]
158
+
159
+
160
+ def create_app(cfg, db=None, session=None):
161
+ if db is None:
162
+ db = connect(cfg)
163
+ if session is None:
164
+ session = s3func.HttpSession(stream=False, read_timeout=cfg.api_read_timeout, max_attempts=cfg.api_retries)
165
+ app = FastAPI(
166
+ title='envlib EDR API',
167
+ description='OGC API - Environmental Data Retrieval for envlib datasets.',
168
+ openapi_url='/api',
169
+ docs_url=None,
170
+ redoc_url=None,
171
+ )
172
+ app.state.db = db
173
+
174
+ @app.exception_handler(ApiError)
175
+ def _api_error(request, err):
176
+ return _respond(request, encode.json_body(err.body()), encode.JSON_TYPE, status=err.status, headers=err.headers)
177
+
178
+ @app.exception_handler(StarletteHTTPException)
179
+ def _http_error(request, err):
180
+ """FastAPI's own answers (unknown route, method not allowed) in the OGC exception shape."""
181
+ code = {404: 'NotFound', 405: 'MethodNotAllowed'}.get(err.status_code, 'HTTPError')
182
+ body = encode.json_body({'code': code, 'description': str(err.detail)})
183
+ return _respond(request, body, encode.JSON_TYPE, status=err.status_code, headers=getattr(err, 'headers', None))
184
+
185
+ @app.exception_handler(Exception)
186
+ def _unexpected(request, err):
187
+ """Anything unhandled answers a JSON 500, never Starlette's plain text; the error is still logged."""
188
+ logger.error(f'Unhandled {type(err).__name__} on {request.url.path}: {err}', exc_info=err)
189
+ body = encode.json_body({'code': 'InternalError', 'description': 'The server failed to answer this request.'})
190
+ return _respond(request, body, encode.JSON_TYPE, status=500)
191
+
192
+ def _meta(request):
193
+ q = params.validate(request, params.META)
194
+ params.output_format(q, ('JSON',), 'JSON')
195
+ return q
196
+
197
+ def _run(cid, work):
198
+ return resolve.run(cfg, db, session, cid, work)
199
+
200
+ @app.get('/')
201
+ def landing(request: Request):
202
+ _meta(request)
203
+ return _respond(request, encode.json_body(edr.landing(_base(cfg, request))), encode.JSON_TYPE)
204
+
205
+ @app.get('/conformance')
206
+ def conformance(request: Request):
207
+ _meta(request)
208
+ return _respond(request, encode.json_body({'conformsTo': edr.CONFORMANCE}), encode.JSON_TYPE)
209
+
210
+ def _collection_work(base):
211
+ def work(at):
212
+ attrs = read.snapshot_attrs(at.ds)
213
+ if _kind(at) == 'grid':
214
+ return edr.grid_collection(base, at.doc, attrs, grid.Grid(at.ds, attrs)), _etag(at)
215
+ names = edr.data_var_names(at.ds)
216
+ _check_conventions(at.ds, attrs, names)
217
+ return edr.collection(base, at.doc, attrs, names), _etag(at)
218
+
219
+ return work
220
+
221
+ @app.get('/collections')
222
+ def collections(request: Request):
223
+ _meta(request)
224
+ base = _base(cfg, request)
225
+ out = []
226
+ try:
227
+ served = sorted(resolve.latest_by_dataset(db))
228
+ except pymongo.errors.PyMongoError as err:
229
+ logger.error(f'/collections: MongoDB failed: {err}')
230
+ raise resolve.unavailable(cfg, 'The database is unavailable.') from err
231
+ for cid in served:
232
+ try:
233
+ obj, _ = _run(cid, _collection_work(base))
234
+ except ApiError as err:
235
+ logger.warning(f'/collections: {cid} left out: {err}')
236
+ continue
237
+ out.append(obj)
238
+ body = {
239
+ 'links': [
240
+ {'href': f'{base}/collections', 'rel': 'self', 'type': 'application/json', 'title': 'Collections'}
241
+ ],
242
+ 'collections': out,
243
+ }
244
+ return _respond(request, encode.json_body(body), encode.JSON_TYPE)
245
+
246
+ @app.get('/collections/{cid}')
247
+ def collection(cid: str, request: Request):
248
+ _meta(request)
249
+ obj, etag = _run(cid, _collection_work(_base(cfg, request)))
250
+ return _respond(request, encode.json_body(obj), encode.JSON_TYPE, headers={'ETag': etag})
251
+
252
+ @app.get('/collections/{cid}/locations')
253
+ def locations(cid: str, request: Request):
254
+ q = params.validate(request, params.LOCATIONS)
255
+ params.output_format(q, ('GeoJSON', 'JSON'), 'GeoJSON')
256
+ base = _base(cfg, request)
257
+
258
+ def work(at):
259
+ attrs = read.snapshot_attrs(at.ds)
260
+ _require(at, 'locations')
261
+ names = edr.data_var_names(at.ds)
262
+ _check_conventions(at.ds, attrs, names)
263
+ meta = at.doc['user_meta']
264
+ interval = f'{meta.get("time_start")}/{meta.get("time_end")}'
265
+ return encode.locations_geojson(Stations.read(at.ds), base, cid, interval, names), _etag(at)
266
+
267
+ body, etag = _run(cid, work)
268
+ return _respond(request, body, encode.GEOJSON_TYPE, headers={'ETag': etag})
269
+
270
+ def _data(request, cid, q, select, query):
271
+ fmt = params.output_format(q, ('CoverageJSON', 'CSV'), 'CoverageJSON')
272
+ spec = timesel.parse(q.get('datetime'))
273
+
274
+ def work(at):
275
+ attrs = read.snapshot_attrs(at.ds)
276
+ _require(at, query)
277
+ available = edr.data_var_names(at.ds)
278
+ _check_conventions(at.ds, attrs, available)
279
+ names = params.parameter_names(q, available)
280
+ stations = Stations.read(at.ds)
281
+ positions, single = select(stations)
282
+ if not positions:
283
+ raise NoContent() # before the time axis is read: it is the largest coordinate
284
+ times = at.ds['time'].data
285
+ a, b = timesel.resolve(spec, times)
286
+ if b <= a:
287
+ raise NoContent()
288
+ sels = {name: (positions, (a, b)) for name in names}
289
+ nbytes, nvalues = cost.count(at.ds, sels)
290
+ cost.check(cfg, at, nbytes, nvalues, len(positions) * (b - a), fmt)
291
+ keys = cost.chunk_keys(at.ds, sels)
292
+ data = read.read_values(at, keys, positions, a, b)
293
+ precisions = {n: at.ds[n].dtype.precision for n in names}
294
+ return (
295
+ stations,
296
+ positions,
297
+ single,
298
+ times[a:b],
299
+ data,
300
+ precisions,
301
+ edr.covjson_parameters(attrs, names),
302
+ _etag(at),
303
+ )
304
+
305
+ try:
306
+ stations, positions, single, times, data, precisions, cparams, etag = _run(cid, work)
307
+ except NoContent:
308
+ return Response(status_code=204, headers={'Vary': 'Accept-Encoding'})
309
+ if fmt == 'CSV':
310
+ body = encode.csv_body(stations, positions, times, data, precisions)
311
+ return _respond(request, body, encode.CSV_TYPE, headers={'ETag': etag})
312
+ body = encode.coverage_json(cparams, stations, positions, times, data, precisions, single)
313
+ return _respond(request, body, encode.COVJSON_TYPE, headers={'ETag': etag})
314
+
315
+ @app.get('/collections/{cid}/locations/{loc_id}')
316
+ def location(cid: str, loc_id: str, request: Request):
317
+ q = params.validate(request, params.DATA)
318
+
319
+ def select(stations):
320
+ i = stations.by_id(loc_id)
321
+ if i is None:
322
+ raise ApiError(404, 'NotFound', f'No location {loc_id!r} in collection {cid!r}.')
323
+ return [i], True
324
+
325
+ return _data(request, cid, q, select, 'locations')
326
+
327
+ @app.get('/collections/{cid}/area')
328
+ def area(cid: str, request: Request):
329
+ q = params.validate(request, params.AREA, required=('coords',))
330
+ geom = parse_wkt(q['coords'], ('Polygon', 'MultiPolygon'))
331
+ return _data(request, cid, q, lambda stations: (stations.in_geometry(geom), False), 'area')
332
+
333
+ @app.get('/collections/{cid}/radius')
334
+ def radius(cid: str, request: Request):
335
+ q = params.validate(request, params.RADIUS, required=('coords', 'within', 'within-units'))
336
+ point = check_point(parse_wkt(q['coords'], ('Point',)))
337
+ metres = within_metres(q['within'], q['within-units'])
338
+ return _data(request, cid, q, lambda stations: (stations.within(point.x, point.y, metres), False), 'radius')
339
+
340
+ def _grid(request, cid, q, select, query):
341
+ """
342
+ A grid query. `select(g)` gives ({y: (i0, i1), x: (j0, j1)}, cell or None), or None when the
343
+ point or bbox holds no cell. The order is plan 3's: attrs, selection, counts and caps, keys,
344
+ one batched fetch, the reads; `resolve.run` then calls verify() before any answer.
345
+
346
+ A cube is CoverageJSON only (Mike, 2026-11-25): long-form CSV repeats every coordinate on every
347
+ cell's row, and grid users want arrays (CoverageJSON now, netCDF later). A position, one
348
+ cell's series, is CSV too, like a station's.
349
+ """
350
+ fmt = params.output_format(q, edr.GRID_FORMATS[query], 'CoverageJSON')
351
+ tspec = timesel.parse(q.get('datetime'))
352
+ zspec = grid.parse_z(q.get('z'))
353
+
354
+ def work(at):
355
+ attrs = read.snapshot_attrs(at.ds)
356
+ _require(at, query)
357
+ g = grid.Grid(at.ds, attrs)
358
+ names = params.parameter_names(q, g.var_names)
359
+ crs = q.get('crs')
360
+ if query == 'cube' and crs is not None:
361
+ if not g.geographic and crs in params.CRS_OK:
362
+ raise ApiError(
363
+ 400,
364
+ 'InvalidParameterValue',
365
+ 'crs: this grid is projected and is rotated against lon/lat, so a cube can only be returned '
366
+ 'in its native CRS (crs=native, or omit crs); the WKT is in the collection\'s crs_details.',
367
+ )
368
+ if g.geographic and crs == params.NATIVE:
369
+ raise ApiError(400, 'InvalidParameterValue', 'crs: this collection offers CRS84 only.')
370
+ hit = select(g)
371
+ if hit is None:
372
+ raise NoContent()
373
+ ranges, cell = hit
374
+ if g.z_name:
375
+ z0, z1 = g.z_range(zspec) # z on a grid without levels is ignored (EDR /req/edr/z-response A)
376
+ if z1 <= z0:
377
+ raise NoContent()
378
+ ranges[g.z_name] = (z0, z1)
379
+ times = at.ds['time'].data
380
+ a, b = timesel.resolve(tspec, times)
381
+ if b <= a:
382
+ raise NoContent()
383
+ ranges['time'] = (a, b)
384
+ sel = GridSelection(g, ranges, times[a:b], cell)
385
+ sels = {n: sel.sel(g.dims) for n in names}
386
+ nbytes, nvalues = cost.count(at.ds, sels)
387
+ cost.check(cfg, at, nbytes, nvalues, nvalues // len(names), fmt)
388
+ keys = cost.chunk_keys(at.ds, sels)
389
+ data = read.read_grid(at, keys, sels)
390
+ precisions = {n: at.ds[n].dtype.precision for n in names}
391
+ return g, sel, data, precisions, edr.covjson_parameters(attrs, names), _etag(at)
392
+
393
+ try:
394
+ g, sel, data, precisions, cparams, etag = _run(cid, work)
395
+ except NoContent:
396
+ return Response(status_code=204, headers={'Vary': 'Accept-Encoding'})
397
+ if fmt == 'CSV':
398
+ return _respond(
399
+ request, encode.position_csv(g, sel, data, precisions), encode.CSV_TYPE, headers={'ETag': etag}
400
+ )
401
+ if query == 'position':
402
+ body = encode.position_json(cparams, g, sel, data, precisions)
403
+ else:
404
+ body = encode.cube_json(cparams, g, sel, data, precisions)
405
+ return _respond(request, body, encode.COVJSON_TYPE, headers={'ETag': etag})
406
+
407
+ @app.get('/collections/{cid}/position')
408
+ def position(cid: str, request: Request):
409
+ q = params.validate(request, params.POSITION, required=('coords',))
410
+ point = grid.check_lon(check_point(parse_wkt(q['coords'], ('Point',))))
411
+
412
+ def select(g):
413
+ cell = g.nearest(point.x, point.y)
414
+ if cell is None:
415
+ return None
416
+ i, j = cell
417
+ return {g.y_name: (i, i + 1), g.x_name: (j, j + 1)}, cell
418
+
419
+ return _grid(request, cid, q, select, 'position')
420
+
421
+ @app.get('/collections/{cid}/cube')
422
+ def cube(cid: str, request: Request):
423
+ q = params.validate(request, params.CUBE, required=('bbox',), crs_ok=params.CRS_OK | {params.NATIVE})
424
+ bbox = grid.parse_bbox(q['bbox'])
425
+
426
+ def select(g):
427
+ h = g.hull(bbox)
428
+ if h is None:
429
+ return None
430
+ return {g.y_name: h[0], g.x_name: h[1]}, None
431
+
432
+ return _grid(request, cid, q, select, 'cube')
433
+
434
+ check_role(db)
435
+ return app
@@ -0,0 +1,52 @@
1
+ """
2
+ Response compression, negotiated from Accept-Encoding: zstd level 1, then gzip level 1, then none
3
+ (assessment §6, Mike 2026-10-07). q-values are honoured, and q=0 refuses a coding.
4
+ """
5
+
6
+ import gzip
7
+
8
+ import zstandard
9
+
10
+ PREFERENCE = ('zstd', 'gzip')
11
+
12
+
13
+ def _accepted(header):
14
+ """{coding: q} from an Accept-Encoding header; '*' stands for any coding not named."""
15
+ out = {}
16
+ for part in (header or '').split(','):
17
+ part = part.strip()
18
+ if not part:
19
+ continue
20
+ coding, _, params = part.partition(';')
21
+ q = 1.0
22
+ for p in params.split(';'):
23
+ k, _, v = p.strip().partition('=')
24
+ if k.strip().lower() == 'q':
25
+ try:
26
+ q = float(v)
27
+ except ValueError:
28
+ q = 0.0
29
+ out[coding.strip().lower()] = q
30
+ return out
31
+
32
+
33
+ def choose(header):
34
+ """The coding to use ('zstd', 'gzip' or None for identity)."""
35
+ acc = _accepted(header)
36
+ best, best_q = None, 0.0
37
+ for coding in PREFERENCE:
38
+ q = acc.get(coding, acc.get('*', 0.0))
39
+ if q > best_q:
40
+ best, best_q = coding, q
41
+ return best
42
+
43
+
44
+ def encode(body, coding):
45
+ if coding == 'zstd':
46
+ ## A compressor per call: a ZstdCompressor is not thread-safe (its compress() releases the
47
+ ## GIL), and one shared by FastAPI's thread pool segfaulted the server under concurrent zstd
48
+ ## requests (code review edr-api-code-3, Fable). Building one costs microseconds.
49
+ return zstandard.ZstdCompressor(level=1).compress(body)
50
+ if coding == 'gzip':
51
+ return gzip.compress(body, compresslevel=1)
52
+ return body
envlib_api/api/cost.py ADDED
@@ -0,0 +1,107 @@
1
+ """
2
+ A request's costs, the caps (413), and its data chunk keys.
3
+
4
+ The costs are counted from each dimension's chunk spans before any key is built (plan review
5
+ edr-api-plan-4: building every key of a whole-domain request cost 0.5 s, only to refuse it). The key
6
+ list is then built from the same spans, and it is both what the caps counted and what the read
7
+ fetches in one `store.load_items` call. "The estimate equals the keys fetched" is therefore true by
8
+ construction, and a test also checks it against the keys cfdb itself asks for.
9
+
10
+ A selection is one entry per dimension of a variable, in the variable's order: a list of positions
11
+ (the stations of a ts_ortho request) or a half-open (start, stop) range of plain ints.
12
+
13
+ cfdb names a chunk by its start: `{var}!{s0}.{s1}...`, where each start is the absolute position (the
14
+ coordinate's origin added) floored to a multiple of the chunk length. Origins go negative after a
15
+ prepend, hence the floor division.
16
+ """
17
+
18
+ import itertools
19
+ import math
20
+
21
+ from cfdb.utils import make_var_chunk_key
22
+
23
+ from envlib_api.api.errors import ApiError
24
+
25
+ SNIPPET = (
26
+ "import envlib\n"
27
+ "ref = envlib.Catalogue().query(dataset_version_id='{dataset_version_id}')[0]\n"
28
+ "with ref.open() as ds: # pulls exactly the chunks you read; or cfdb.open_edataset on the db_url\n"
29
+ " print(ds)\n"
30
+ )
31
+
32
+
33
+ def _span(entry, origin, chunk):
34
+ """The chunk starts one dimension's selection touches, ascending."""
35
+ if isinstance(entry, tuple):
36
+ lo, hi = entry
37
+ if hi <= lo:
38
+ return []
39
+ first = ((lo + origin) // chunk) * chunk
40
+ last = ((hi - 1 + origin) // chunk) * chunk
41
+ return list(range(first, last + 1, chunk))
42
+ return sorted({((i + origin) // chunk) * chunk for i in entry})
43
+
44
+
45
+ def _size(entry):
46
+ if isinstance(entry, tuple):
47
+ return max(0, entry[1] - entry[0])
48
+ return len(entry)
49
+
50
+
51
+ def spans(dv, sel):
52
+ if len(sel) != len(dv.chunk_shape):
53
+ raise AssertionError(f'a selection of {len(sel)} dimensions for a variable of {len(dv.chunk_shape)}')
54
+ return [_span(e, o, c) for e, o, c in zip(sel, dv.get_coord_origins(), dv.chunk_shape, strict=True)]
55
+
56
+
57
+ def count(ds, sels):
58
+ """(decoded bytes touched, values returned) for {var: selection}, without building a key."""
59
+ nbytes = 0
60
+ nvalues = 0
61
+ for name, sel in sels.items():
62
+ dv = ds[name]
63
+ n_chunks = math.prod(len(s) for s in spans(dv, sel))
64
+ nbytes += n_chunks * math.prod(dv.chunk_shape) * dv.dtype.dtype_decoded.itemsize
65
+ nvalues += math.prod(_size(e) for e in sel)
66
+ return nbytes, nvalues
67
+
68
+
69
+ def chunk_keys(ds, sels):
70
+ """{var: [chunk key, ...]} for {var: selection}."""
71
+ out = {}
72
+ for name, sel in sels.items():
73
+ out[name] = [make_var_chunk_key(name, starts) for starts in itertools.product(*spans(ds[name], sel))]
74
+ return out
75
+
76
+
77
+ def data_keys(ds, var_names, positions, a, b):
78
+ """{var: [chunk key, ...]} for the stations at `positions` and the time range [a, b) (ts_ortho)."""
79
+ return chunk_keys(ds, {name: (positions, (a, b)) for name in var_names})
80
+
81
+
82
+ def check(cfg, attempt, nbytes, nvalues, rows, fmt):
83
+ """Raise the 413 if the request is over any cap. Runs before any key is built or chunk read."""
84
+ over = []
85
+ if nvalues > cfg.max_values:
86
+ over.append(('values returned', nvalues, cfg.max_values))
87
+ if nbytes > cfg.max_decoded_bytes:
88
+ over.append(('decoded bytes touched', nbytes, cfg.max_decoded_bytes))
89
+ if fmt == 'CSV' and rows > cfg.max_csv_rows:
90
+ over.append(('CSV rows', rows, cfg.max_csv_rows))
91
+ if not over:
92
+ return nbytes, nvalues
93
+ ctx = {'dataset_version_id': attempt.doc['_id'], 'db_url': attempt.store.db_url}
94
+ raise ApiError(
95
+ 413,
96
+ 'RequestTooLarge',
97
+ 'The request is over the server\'s limits: '
98
+ + '; '.join(f'{what} {n:,} > {cap:,}' for what, n, cap in over)
99
+ + '. Narrow the query (a smaller area or fewer stations, parameters, levels or time steps), or read'
100
+ ' the dataset directly with envlib.',
101
+ extra={
102
+ 'limits': [{'limit': what, 'requested': n, 'max': cap} for what, n, cap in over],
103
+ 'dataset_version_id': ctx['dataset_version_id'],
104
+ 'db_url': ctx['db_url'],
105
+ 'envlib_snippet': SNIPPET.format(**ctx),
106
+ },
107
+ )