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/api/grid.py ADDED
@@ -0,0 +1,317 @@
1
+ """
2
+ Grid collections: which axes a grid has, the cell nearest a point, the cells of a bbox, and `z`.
3
+
4
+ The rules (plan 4 and its review, edr-api-plan-4):
5
+ - The x and y coordinates are the ones cfdb records as `Axis.x` / `Axis.y`. A vertical axis is the
6
+ coordinate whose attrs say `axis: Z` (CF; cfdb records no axis for it). The axes need not be
7
+ regular: the live SST centres are float32 values whose spacing varies by 3e-4. They are
8
+ increasing: cfdb sorts a coordinate ascending when it is created.
9
+ - **The CRS.** A geographic grid is served only on WGS 84, where its coordinates are CRS84 lon/lat
10
+ as they stand. Any other geographic CRS (a rotated pole, another datum) is not served (Mike,
11
+ 2026-11-25, code review edr-api-code-4): treating it as CRS84 would serve the wrong cells. A
12
+ projected grid is reached through pyproj, from CRS84 (lon/lat order).
13
+ - **The nearest cell** on an axis is found on the stored centres: `searchsorted` on the midpoints
14
+ between neighbours, so nothing depends on a step. A point more than half the edge spacing beyond
15
+ an outer centre is outside, with a tolerance of 0.1% of that spacing: float32 noise puts SST's
16
+ outer cell edges 4.5e-6 deg inside the round numbers 120 and -60 (Mike, 2026-11-25). On a
17
+ midpoint the lower cell wins.
18
+ - A geographic grid's longitudes are wrapped onto the window centred on the axis, so -179 reaches
19
+ SST's 181.
20
+ - **The hull of a bbox** is the smallest index rectangle holding every cell whose centre is inside
21
+ it, unmasked (Mike, 2026-11-25). A centre is inside when s <= lat <= n and
22
+ ((lon - w) mod 360) <= the bbox's width east of w, which covers west > east across 180, 0-360
23
+ input and SST's longitudes past 180 with one rule (Mike, D2).
24
+ - **z** matches a level after rounding both to the coordinate's stored precision: the live 1.0 m
25
+ soil level is stored as 0.9999999999999999.
26
+
27
+ Every index returned is a plain `int`: cfdb reads a numpy-integer slice bound as "the whole axis".
28
+ """
29
+
30
+ import functools
31
+ import re
32
+
33
+ import numpy as np
34
+ import pyproj
35
+ from cfdb.data_models import Axis
36
+
37
+ from envlib_api.api.errors import ApiError
38
+
39
+ CRS84 = 'OGC:CRS84'
40
+ _WGS84 = pyproj.CRS('EPSG:4326')
41
+ _DEFAULT_Z_DECIMALS = 9
42
+ EDGE_TOLERANCE = 0.001 # of the edge spacing, beyond the half-cell edge
43
+ _NUMBER = re.compile(r'[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?') # finite, ASCII, no '_'
44
+
45
+
46
+ def _not_served(problem):
47
+ return ApiError(404, 'NotServed', f'This collection does not follow the grid-dataset conventions: {problem}.')
48
+
49
+
50
+ @functools.lru_cache(maxsize=32)
51
+ def _transformer(wkt, inverse):
52
+ """
53
+ CRS84 -> the grid's CRS (or back). Keyed by WKT: immutable input, no dataset state (Mike, D3).
54
+
55
+ pyproj's Transformer builds its PROJ object per thread on first use, so sharing one is safe, but a
56
+ `from_crs` transformer repeats PROJ's operation search in every new thread: 16 ms on the WRF CRS,
57
+ whose datum is undefined, and the thread pool replaces idle threads. So the search runs once here.
58
+ When PROJ resolved a single operation, the transformer cached is `from_pipeline` of it, which a new
59
+ thread rebuilds in 0.2 ms, with identical results (0.0 difference over 100,000 points, measured
60
+ 2026-11-25 on the producer's WRF CRS). When PROJ keeps several candidate operations (its
61
+ `definition` is then "unavailable until proj_trans is called"; EPSG:27200 or 27700, for example),
62
+ `from_pipeline` refuses it, and the `from_crs` transformer is cached as it is: correct, but it
63
+ pays the search again in each new thread (code review edr-api-code-4).
64
+ """
65
+ crs = pyproj.CRS.from_wkt(wkt)
66
+ searched = (
67
+ pyproj.Transformer.from_crs(crs, CRS84, always_xy=True)
68
+ if inverse
69
+ else pyproj.Transformer.from_crs(CRS84, crs, always_xy=True)
70
+ )
71
+ try:
72
+ return pyproj.Transformer.from_pipeline(searched.definition)
73
+ except pyproj.exceptions.ProjError:
74
+ return searched
75
+
76
+
77
+ class Grid:
78
+ """A grid dataset's axes and served variables, read once per request."""
79
+
80
+ def __init__(self, ds, attrs):
81
+ crs = ds.crs
82
+ if crs is None:
83
+ raise _not_served('no CRS')
84
+ self.crs = crs
85
+ self.wkt = crs.to_wkt()
86
+ self.geographic = bool(crs.is_geographic)
87
+ if self.geographic and not crs.equals(_WGS84, ignore_axis_order=True):
88
+ raise _not_served(f'a geographic CRS other than WGS 84 ({crs.name}); it would be read as CRS84')
89
+ coords = ds.coord_names
90
+ xs = [n for n in coords if ds[n].axis == Axis('x')]
91
+ ys = [n for n in coords if ds[n].axis == Axis('y')]
92
+ if len(xs) != 1 or len(ys) != 1:
93
+ raise _not_served(f'x coordinates {xs}, y coordinates {ys}')
94
+ if 'time' not in coords or ds['time'].axis != Axis('t'):
95
+ raise _not_served('no time coordinate')
96
+ self.x_name, self.y_name = xs[0], ys[0]
97
+ zs = [n for n in coords if str(attrs[n].get('axis', '')).upper() == 'Z']
98
+ if len(zs) > 1:
99
+ raise _not_served(f'vertical coordinates {zs}')
100
+ self.z_name = zs[0] if zs else None
101
+ dims_flat = ('time', self.y_name, self.x_name)
102
+ dims_z = ('time', self.z_name, self.y_name, self.x_name) if self.z_name else None
103
+ flat = [n for n in ds.data_var_names if ds[n].coord_names == dims_flat]
104
+ deep = [n for n in ds.data_var_names if dims_z and ds[n].coord_names == dims_z]
105
+ if flat and deep:
106
+ raise _not_served(f'variables both with ({deep}) and without ({flat}) the vertical axis')
107
+ self.var_names = deep or flat
108
+ if not self.var_names:
109
+ raise _not_served('no (time, [z,] y, x) variable')
110
+ self.dims = dims_z if deep else dims_flat
111
+ if not deep:
112
+ self.z_name = None # a vertical coordinate no served variable uses is not an axis of the data
113
+ self.x = np.asarray(ds[self.x_name].data, dtype='float64')
114
+ self.y = np.asarray(ds[self.y_name].data, dtype='float64')
115
+ for name, a in ((self.x_name, self.x), (self.y_name, self.y)):
116
+ if len(a) < 2:
117
+ raise _not_served(f'{name} has {len(a)} value; a grid axis needs at least 2')
118
+ if not _strictly_increasing(a):
119
+ raise _not_served(f'{name} is not strictly increasing')
120
+ if self.z_name:
121
+ self.z = np.asarray(ds[self.z_name].data, dtype='float64')
122
+ if not _strictly_increasing(self.z):
123
+ raise _not_served(f'{self.z_name} is not strictly increasing')
124
+ p = ds[self.z_name].dtype.precision
125
+ self.z_decimals = _DEFAULT_Z_DECIMALS if p is None else int(p)
126
+ self.z_attrs = attrs[self.z_name]
127
+ else:
128
+ self.z = None
129
+ self.z_decimals = None
130
+ self.z_attrs = {}
131
+
132
+ # -- the nearest cell ------------------------------------------------------------------------
133
+
134
+ def to_native(self, lon, lat):
135
+ """(x, y) of a CRS84 point in the grid's own coordinates; non-finite if it has none."""
136
+ if self.geographic:
137
+ return _wrap(lon, self.x), lat
138
+ x, y = _transformer(self.wkt, False).transform(lon, lat)
139
+ return float(x), float(y)
140
+
141
+ def nearest(self, lon, lat):
142
+ """(i, j) = (y index, x index) of the cell nearest the CRS84 point, or None outside the grid."""
143
+ x, y = self.to_native(lon, lat)
144
+ j = nearest_index(self.x, x) # a non-finite projection is outside: every comparison is False
145
+ i = nearest_index(self.y, y)
146
+ if i is None or j is None:
147
+ return None
148
+ return i, j
149
+
150
+ def lonlat(self, xs, ys):
151
+ """CRS84 lon/lat of native points (arrays of equal shape), lon in [-180, 180)."""
152
+ if self.geographic:
153
+ lon, lat = np.asarray(xs, dtype='float64'), np.asarray(ys, dtype='float64')
154
+ else:
155
+ lon, lat = _transformer(self.wkt, True).transform(np.asarray(xs, 'float64'), np.asarray(ys, 'float64'))
156
+ return normalise_lon(np.asarray(lon)), np.asarray(lat)
157
+
158
+ # -- the hull of a bbox ----------------------------------------------------------------------
159
+
160
+ def hull(self, bbox):
161
+ """((i0, i1), (j0, j1)), half-open index ranges of the smallest rectangle holding every cell
162
+ whose centre is inside `bbox` (w, s, e, n), or None if no centre is inside."""
163
+ w, s, e, n = bbox
164
+ width = east_width(w, e)
165
+ if self.geographic:
166
+ rows = (self.y >= s) & (self.y <= n)
167
+ cols = lon_inside(self.x, w, width)
168
+ else:
169
+ xx, yy = np.meshgrid(self.x, self.y)
170
+ lon, lat = self.lonlat(xx, yy)
171
+ inside = (lat >= s) & (lat <= n) & lon_inside(lon, w, width)
172
+ rows = inside.any(axis=1)
173
+ cols = inside.any(axis=0)
174
+ if not rows.any() or not cols.any():
175
+ return None
176
+ ri, ci = np.nonzero(rows)[0], np.nonzero(cols)[0]
177
+ return (int(ri[0]), int(ri[-1]) + 1), (int(ci[0]), int(ci[-1]) + 1)
178
+
179
+ # -- z ---------------------------------------------------------------------------------------
180
+
181
+ def z_range(self, spec):
182
+ """The half-open index range of the levels `spec` selects (all levels for None)."""
183
+ nz = len(self.z)
184
+ if spec is None:
185
+ return 0, nz
186
+ levels = np.round(self.z, self.z_decimals)
187
+ if spec[0] == 'level':
188
+ hit = np.nonzero(levels == round(spec[1], self.z_decimals))[0]
189
+ else:
190
+ _, lo, hi = spec
191
+ ok = np.ones(nz, dtype=bool)
192
+ if lo is not None:
193
+ ok &= levels >= round(lo, self.z_decimals)
194
+ if hi is not None:
195
+ ok &= levels <= round(hi, self.z_decimals)
196
+ hit = np.nonzero(ok)[0]
197
+ if not len(hit):
198
+ return 0, 0
199
+ return int(hit[0]), int(hit[-1]) + 1 # the levels are monotonic, so the hits are contiguous
200
+
201
+ def z_text(self, values):
202
+ """Level values as text at the stored precision ('1' for the stored 0.9999999999999999)."""
203
+ return [_decimal_text(v, self.z_decimals) for v in values]
204
+
205
+ def z_values(self, values):
206
+ """Level values rounded to the stored precision, for numeric output."""
207
+ return [float(v) for v in np.round(np.asarray(values, dtype='float64'), self.z_decimals)]
208
+
209
+
210
+ def _strictly_increasing(a):
211
+ return bool(np.all(np.diff(a) > 0))
212
+
213
+
214
+ def nearest_index(c, v):
215
+ """
216
+ Index of the centre nearest `v` on a strictly increasing axis (2 or more centres), or None when
217
+ `v` is more than half the edge spacing beyond an outer centre, give or take EDGE_TOLERANCE of that
218
+ spacing. On a midpoint the lower index wins. A non-finite `v` is None.
219
+ """
220
+ lo = c[0] - (c[1] - c[0]) * (0.5 + EDGE_TOLERANCE)
221
+ hi = c[-1] + (c[-1] - c[-2]) * (0.5 + EDGE_TOLERANCE)
222
+ if not (lo <= v <= hi):
223
+ return None
224
+ mids = (c[:-1] + c[1:]) / 2
225
+ return int(np.searchsorted(mids, v, side='left'))
226
+
227
+
228
+ def _wrap(lon, axis):
229
+ """`lon` moved by a multiple of 360 into the window centred on a longitude axis."""
230
+ mid = (float(axis[0]) + float(axis[-1])) / 2
231
+ return mid + ((lon - mid + 180.0) % 360.0) - 180.0
232
+
233
+
234
+ def normalise_lon(lon):
235
+ """Longitudes in [-180, 180)."""
236
+ return ((np.asarray(lon, dtype='float64') + 180.0) % 360.0) - 180.0
237
+
238
+
239
+ def east_width(w, e):
240
+ """The bbox's extent east of `w`, in degrees: e - w, plus 360 when it crosses 180 (w > e)."""
241
+ return e - w if w <= e else e - w + 360.0
242
+
243
+
244
+ def lon_inside(lon, w, width):
245
+ """Whether each longitude lies within `width` degrees east of `w`, in any convention."""
246
+ return ((np.asarray(lon, dtype='float64') - w) % 360.0) <= width
247
+
248
+
249
+ def parse_bbox(text):
250
+ """(w, s, e, n) from 'w,s,e,n' in CRS84, or a 400."""
251
+ try:
252
+ vals = [_strict_float(p) for p in text.split(',')]
253
+ except ValueError as err:
254
+ raise ApiError(400, 'InvalidParameterValue', 'bbox must be four numbers: w,s,e,n.') from err
255
+ if len(vals) != 4:
256
+ raise ApiError(400, 'InvalidParameterValue', 'bbox must be four numbers: w,s,e,n (no vertical bounds).')
257
+ w, s, e, n = vals
258
+ if not all(np.isfinite(v) for v in vals):
259
+ raise ApiError(400, 'InvalidParameterValue', 'bbox values must be finite.')
260
+ if not (-90 <= s <= n <= 90):
261
+ raise ApiError(400, 'InvalidParameterValue', 'bbox latitudes must satisfy -90 <= s <= n <= 90.')
262
+ if abs(w) > 360 or abs(e) > 360:
263
+ raise ApiError(400, 'InvalidParameterValue', 'bbox longitudes must be within -360..360.')
264
+ if east_width(w, e) > 360:
265
+ raise ApiError(400, 'InvalidParameterValue', 'bbox spans more than 360 degrees of longitude.')
266
+ return w, s, e, n
267
+
268
+
269
+ def check_lon(point):
270
+ """A position's longitude must be within -360..360 (any convention) and the POINT 2-D; its
271
+ latitude is checked by `stations.check_point`."""
272
+ if point.has_z:
273
+ raise ApiError(400, 'InvalidParameterValue', 'coords: give a 2-D POINT(lon lat); use z for a level.')
274
+ if abs(point.x) > 360:
275
+ raise ApiError(400, 'InvalidParameterValue', 'coords: the POINT longitude must be within -360..360.')
276
+ return point
277
+
278
+
279
+ def _strict_float(text):
280
+ """float(text) for a plain decimal number only: Python's float() also takes '1_0' and non-ASCII
281
+ digits (code review edr-api-code-4)."""
282
+ if not _NUMBER.fullmatch(text.strip()):
283
+ raise ValueError(text)
284
+ return float(text)
285
+
286
+
287
+ def _number(text, what):
288
+ try:
289
+ v = _strict_float(text)
290
+ except ValueError as err:
291
+ raise ApiError(400, 'InvalidParameterValue', f'z: {what} {text!r} is not a number.') from err
292
+ if not np.isfinite(v): # '1e999'
293
+ raise ApiError(400, 'InvalidParameterValue', f'z: {what} must be finite.')
294
+ return v
295
+
296
+
297
+ def parse_z(text):
298
+ """None, ('level', v) or ('interval', lo or None, hi or None)."""
299
+ if text is None:
300
+ return None
301
+ text = text.strip()
302
+ if ',' in text or text.upper().startswith('R'):
303
+ raise ApiError(400, 'InvalidParameterValue', 'z: a list or a recurring interval is not supported.')
304
+ if '/' in text:
305
+ parts = text.split('/')
306
+ if len(parts) != 2:
307
+ raise ApiError(400, 'InvalidParameterValue', 'z: an interval has exactly one "/".')
308
+ lo, hi = (None if p.strip() in ('..', '') else _number(p.strip(), 'bound') for p in parts)
309
+ if lo is not None and hi is not None and hi < lo:
310
+ raise ApiError(400, 'InvalidParameterValue', 'z: the interval ends below where it starts.')
311
+ return ('interval', lo, hi)
312
+ return ('level', _number(text, 'level'))
313
+
314
+
315
+ def _decimal_text(v, decimals):
316
+ s = f'{float(np.round(v, decimals)):.{decimals}f}'
317
+ return s.rstrip('0').rstrip('.') if '.' in s else s
@@ -0,0 +1,71 @@
1
+ """
2
+ Explicit query-parameter validation. FastAPI would ignore an unknown parameter, let a repeated one
3
+ win silently, and answer 422 for a missing one (plan review edr-api-plan-3). Here an unknown, repeated
4
+ or missing parameter answers 400 (OGC API - Common Part 1, Requirement 2).
5
+ """
6
+
7
+ from envlib_api.api.errors import ApiError
8
+
9
+ FORMATS = {
10
+ 'coveragejson': 'CoverageJSON',
11
+ 'covjson': 'CoverageJSON',
12
+ 'csv': 'CSV',
13
+ 'geojson': 'GeoJSON',
14
+ 'json': 'JSON',
15
+ }
16
+ META = {'f'}
17
+ LOCATIONS = {'f', 'crs'}
18
+ DATA = {'f', 'crs', 'datetime', 'parameter-name'}
19
+ AREA = DATA | {'coords'}
20
+ RADIUS = DATA | {'coords', 'within', 'within-units'}
21
+ POSITION = DATA | {'coords', 'z'}
22
+ CUBE = DATA | {'bbox', 'z'}
23
+ CRS_OK = {'CRS84', 'OGC:CRS84', 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'}
24
+ NATIVE = 'native'
25
+ _UNSUPPORTED = {'resolution-x', 'resolution-y', 'resolution-z'}
26
+
27
+
28
+ def validate(request, allowed, required=(), crs_ok=CRS_OK):
29
+ """The query parameters as a dict, or a 400."""
30
+ seen = {}
31
+ for key, value in request.query_params.multi_items():
32
+ if key in _UNSUPPORTED and key not in allowed:
33
+ raise ApiError(400, 'InvalidParameter', f'{key} is not supported: data are returned at native resolution.')
34
+ if key not in allowed:
35
+ raise ApiError(
36
+ 400, 'InvalidParameter', f'Unknown query parameter {key!r}; this resource takes {sorted(allowed)}.'
37
+ )
38
+ if key in seen:
39
+ raise ApiError(400, 'InvalidParameter', f'Query parameter {key!r} is given more than once.')
40
+ seen[key] = value
41
+ missing = [k for k in required if not seen.get(k)]
42
+ if missing:
43
+ raise ApiError(400, 'MissingParameterValue', f'Missing required query parameter(s) {missing}.')
44
+ crs = seen.get('crs')
45
+ if crs is not None and crs not in crs_ok:
46
+ raise ApiError(400, 'InvalidParameterValue', f'crs: this query supports {sorted(crs_ok)}.')
47
+ return seen
48
+
49
+
50
+ def output_format(params, allowed, default):
51
+ value = params.get('f')
52
+ if value is None:
53
+ return default
54
+ fmt = FORMATS.get(value.strip().lower())
55
+ if fmt not in allowed:
56
+ raise ApiError(400, 'InvalidParameterValue', f'f={value!r} is not offered here; choose one of {list(allowed)}.')
57
+ return fmt
58
+
59
+
60
+ def parameter_names(params, available):
61
+ """The requested parameters, in the order given, or every one the collection serves."""
62
+ value = params.get('parameter-name')
63
+ if value is None:
64
+ return list(available)
65
+ names = list(dict.fromkeys(n.strip() for n in value.split(',') if n.strip()))
66
+ unknown = [n for n in names if n not in available]
67
+ if unknown or not names:
68
+ raise ApiError(
69
+ 400, 'InvalidParameterValue', f'Unknown parameter-name {unknown}; this collection has {list(available)}.'
70
+ )
71
+ return names
envlib_api/api/read.py ADDED
@@ -0,0 +1,65 @@
1
+ """
2
+ Reading a request's data: every attr first, then the data keys in one batched fetch, then the
3
+ per-station reads from the store's memo.
4
+
5
+ Attrs are read before anything else because cfdb loads them lazily, as store keys. An attr read
6
+ after `store.verify()` could come from a later commit than the data (plan review edr-api-plan-3).
7
+ """
8
+
9
+ import numpy as np
10
+
11
+
12
+ def snapshot_attrs(ds):
13
+ """Every attr the response needs: {'': dataset attrs, var: attrs} for all coordinates and variables."""
14
+ out = {'': ds.attrs.data}
15
+ for name in (*ds.coord_names, *ds.data_var_names):
16
+ out[name] = ds[name].attrs.data
17
+ return out
18
+
19
+
20
+ def read_values(attempt, keys, positions, a, b):
21
+ """
22
+ {var: float array (len(positions), b - a)} for the stations at `positions` (dataset order) and
23
+ the time range [a, b). One `load_items` fetches every chunk of `keys`, so the reads below come
24
+ from the memo: two MongoDB round trips per request instead of two per station and variable.
25
+ """
26
+ store, ds = attempt.store, attempt.ds
27
+ store.load_items([k for ks in keys.values() for k in ks])
28
+ attempt.check_deadline()
29
+ out = {}
30
+ for name in keys:
31
+ dv = ds[name]
32
+ arr = np.empty((len(positions), b - a), dtype=dv.dtype.dtype_decoded)
33
+ for j, i in enumerate(positions):
34
+ row = dv[int(i), int(a) : int(b)].data
35
+ if row.shape != (1, b - a):
36
+ raise AssertionError(f'{name}[{i}, {a}:{b}] read shape {row.shape}, expected {(1, b - a)}')
37
+ arr[j] = row[0]
38
+ out[name] = arr
39
+ return out
40
+
41
+
42
+ def read_grid(attempt, keys, sels):
43
+ """
44
+ {var: float array} for {var: selection}, each selection a tuple of half-open (start, stop)
45
+ ranges in the variable's dimension order. One `load_items` fetches every chunk of `keys`, then
46
+ each variable is one read from the memo, its shape asserted.
47
+
48
+ Every bound must be a plain `int`: cfdb reads a numpy-integer slice bound as "no bound", so the
49
+ read would fetch the whole axis after the caps had passed (plan review edr-api-plan-4).
50
+ """
51
+ for name, sel in sels.items():
52
+ for lo, hi in sel:
53
+ if type(lo) is not int or type(hi) is not int:
54
+ raise AssertionError(f'{name}: selection bounds {(lo, hi)!r} are not plain ints')
55
+ store, ds = attempt.store, attempt.ds
56
+ store.load_items([k for ks in keys.values() for k in ks])
57
+ attempt.check_deadline()
58
+ out = {}
59
+ for name, sel in sels.items():
60
+ arr = ds[name][tuple(slice(lo, hi) for lo, hi in sel)].data
61
+ want = tuple(hi - lo for lo, hi in sel)
62
+ if arr.shape != want:
63
+ raise AssertionError(f'{name}{sel} read shape {arr.shape}, expected {want}')
64
+ out[name] = arr
65
+ return out
@@ -0,0 +1,191 @@
1
+ """
2
+ Which version a collection serves, and the per-request loop that opens it consistently.
3
+
4
+ A collection is a `dataset_id`. It serves the version with the greatest `user_meta.created_at`
5
+ (envlib's rule, `envlib.catalogue._latest_per_dataset`); a tie goes to the greater
6
+ `dataset_version_id`. envlib breaks a tie by catalogue order instead, so the two can differ when two
7
+ versions were registered within one second (none live; plan 5 settles it with envlib's public
8
+ function).
9
+
10
+ `run()` is the only way a route reads a dataset. Each attempt re-resolves the `dataset_id`, builds a
11
+ new MongoStore and cfdb dataset, runs the route's work, and calls `store.verify()` before ANY answer
12
+ the work produced, errors included. The rules (plan review edr-api-plan-3):
13
+
14
+ - `StaleIndexError` with a commit applied since the store was built (a refused build, a failed
15
+ verify(), or an entry read across an apply): retry with a new store after `retry_wait_ms`, up to
16
+ `retry_attempts`, then 503.
17
+ - `StaleIndexError` with nothing applied since (a chunk fetch found the remote ahead of the
18
+ mirror): 503 at once. Only the refresher's next poll clears it, so a retry would only repeat it.
19
+ - `RemoteMissingError`: re-resolve. No version left -> 404; another version is now the latest ->
20
+ retry; the same version -> 503 (its remote was missing at the last poll).
21
+ - `RemoteIntegrityError`, or chunk bytes that do not decode -> 500, logged at ERROR.
22
+ """
23
+
24
+ import datetime
25
+ import logging
26
+ import time
27
+
28
+ import cfdb
29
+ import urllib3
30
+ from ebooklet.errors import RemoteIntegrityError, RemoteMissingError, StaleIndexError
31
+ from ebooklet.mongo import MongoStore
32
+ from pymongo.errors import PyMongoError
33
+
34
+ from envlib_api.api.errors import ApiError, NoContent
35
+ from envlib_api.mirror import CATALOGUE
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ _MIN_TIME = datetime.datetime.min.replace(tzinfo=datetime.UTC)
40
+ _SERVED_TYPES = ('ts_ortho', 'grid')
41
+
42
+
43
+ def created_at(doc):
44
+ """
45
+ `user_meta.created_at` as an aware datetime, parsed as envlib parses it. A missing value is the
46
+ minimum, as in envlib. An unparsable one is the minimum too, with a warning, so one bad catalogue
47
+ entry cannot fail every listing (envlib's own parser would raise; code review edr-api-code-3).
48
+ """
49
+ value = (doc.get('user_meta') or {}).get('created_at')
50
+ if value is None:
51
+ return _MIN_TIME
52
+ try:
53
+ dt = datetime.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
54
+ except (ValueError, TypeError):
55
+ logger.warning(f'{doc.get("_id")}: unparsable user_meta.created_at {value!r}; treated as the oldest version.')
56
+ return _MIN_TIME
57
+ return dt if dt.tzinfo is not None else dt.replace(tzinfo=datetime.UTC)
58
+
59
+
60
+ def _latest(docs):
61
+ return max(docs, key=lambda d: (created_at(d), d['_id']))
62
+
63
+
64
+ def latest_by_dataset(db, dataset_id=None):
65
+ """{dataset_id: the catalogue document of its served version}, for served dataset types only."""
66
+ query = {} if dataset_id is None else {'dataset_id': dataset_id}
67
+ groups = {}
68
+ for doc in db[CATALOGUE].find(query):
69
+ groups.setdefault(doc['dataset_id'], []).append(doc)
70
+ out = {}
71
+ for did, docs in groups.items():
72
+ doc = _latest(docs)
73
+ if (doc.get('user_meta') or {}).get('dataset_type') in _SERVED_TYPES:
74
+ out[did] = doc
75
+ return out
76
+
77
+
78
+ def latest(db, dataset_id):
79
+ return latest_by_dataset(db, dataset_id).get(dataset_id)
80
+
81
+
82
+ class Attempt:
83
+ """What one attempt's work receives: the catalogue document, the store and the open dataset."""
84
+
85
+ def __init__(self, doc, store, ds, deadline, cfg):
86
+ self.doc = doc
87
+ self.store = store
88
+ self.ds = ds
89
+ self.deadline = deadline
90
+ self.cfg = cfg
91
+
92
+ def check_deadline(self):
93
+ if time.monotonic() > self.deadline:
94
+ raise deadline_error(self.cfg)
95
+
96
+
97
+ def deadline_error(cfg):
98
+ return ApiError(
99
+ 503,
100
+ 'Deadline',
101
+ 'The request ran past its deadline; retry later.',
102
+ headers={'Retry-After': str(cfg.retry_after_seconds)},
103
+ )
104
+
105
+
106
+ def unavailable(cfg, description):
107
+ return ApiError(503, 'Unavailable', description, headers={'Retry-After': str(cfg.retry_after_seconds)})
108
+
109
+
110
+ def _not_found(dataset_id):
111
+ return ApiError(404, 'NotFound', f'No collection {dataset_id!r}.')
112
+
113
+
114
+ def run(cfg, db, session, dataset_id, work):
115
+ """
116
+ Answer one request for `dataset_id` with `work(attempt)` (see the module docstring). `work`
117
+ must read every attr it needs before it returns or raises, and must not touch the store after.
118
+
119
+ The deadline is checked between attempts and after the batched fetch. It cannot interrupt a
120
+ fetch in progress: one B2 read is bounded by `read_timeout` x (`retries` + 1) plus s3func's
121
+ backoff, so a request can overrun the deadline by that much.
122
+
123
+ A MongoDB error anywhere answers 503, including one raised inside the handlers below, which
124
+ their sibling `except` clauses would not catch (code review edr-api-code-3).
125
+ """
126
+ try:
127
+ return _run(cfg, db, session, dataset_id, work)
128
+ except PyMongoError as err:
129
+ logger.error(f'{dataset_id}: MongoDB failed: {err}')
130
+ raise unavailable(cfg, 'The database is unavailable.') from err
131
+
132
+
133
+ def _run(cfg, db, session, dataset_id, work):
134
+ deadline = time.monotonic() + cfg.request_deadline_seconds
135
+ for attempt_no in range(1, cfg.retry_attempts + 1):
136
+ if attempt_no > 1:
137
+ time.sleep(cfg.retry_wait_ms / 1000)
138
+ if time.monotonic() > deadline:
139
+ raise deadline_error(cfg)
140
+ doc = latest(db, dataset_id)
141
+ if doc is None:
142
+ raise _not_found(dataset_id)
143
+ dvid = doc['_id']
144
+ store = None
145
+ try:
146
+ store = MongoStore(db, dvid, http_session=session)
147
+ with cfdb.open_store_dataset(store) as ds:
148
+ try:
149
+ result = work(Attempt(doc, store, ds, deadline, cfg))
150
+ except (ApiError, NoContent):
151
+ store.verify() # an answer computed from the store is an answer too
152
+ raise
153
+ store.verify()
154
+ return result
155
+ except StaleIndexError as err:
156
+ if store is not None and not _applied_since(store):
157
+ logger.warning(f'{dvid}: the remote is ahead of the mirror ({err}); 503 until the next refresh.')
158
+ raise unavailable(cfg, 'The dataset changed upstream and the mirror has not caught up yet.') from err
159
+ logger.info(f'{dvid}: a refresh overlapped the request (attempt {attempt_no}); retrying.')
160
+ continue
161
+ except RemoteMissingError as err:
162
+ now = latest(db, dataset_id)
163
+ if now is None:
164
+ raise _not_found(dataset_id) from err
165
+ if now['_id'] != dvid:
166
+ logger.info(f'{dataset_id}: version {dvid} left the catalogue mid-request; retrying on {now["_id"]}.')
167
+ continue
168
+ logger.warning(f'{dvid}: its remote was missing at the last poll ({err}).')
169
+ raise unavailable(cfg, 'The dataset remote is unavailable.') from err
170
+ except RemoteIntegrityError as err:
171
+ logger.error(f'{dvid}: integrity fault: {err}')
172
+ raise ApiError(500, 'IntegrityError', 'The dataset remote contradicts its own index.') from err
173
+ except urllib3.exceptions.HTTPError as err:
174
+ logger.error(f'{dvid}: a B2 fetch failed: {err}')
175
+ raise ApiError(502, 'UpstreamError', 'Fetching the dataset from its remote failed.') from err
176
+ except (ApiError, NoContent, PyMongoError):
177
+ raise
178
+ except Exception as err:
179
+ ## Chunk bytes that do not decode (zstd, a short chunk) land here: an integrity fault.
180
+ logger.error(f'{dvid}: reading failed: {type(err).__name__}: {err}')
181
+ raise ApiError(500, 'ReadError', 'The dataset could not be read.') from err
182
+ raise unavailable(cfg, 'A refresh kept overlapping the request.')
183
+
184
+
185
+ def _applied_since(store):
186
+ """True if a commit was applied (or began) since `store` was built."""
187
+ try:
188
+ store.verify()
189
+ except StaleIndexError:
190
+ return True
191
+ return False
@@ -0,0 +1,35 @@
1
+ """`envlib-api-server`: run the API under uvicorn (one worker; scale with replicas)."""
2
+
3
+ import logging
4
+ import os
5
+ import sys
6
+
7
+ import sentry_sdk
8
+ import uvicorn
9
+
10
+ from envlib_api import __version__, config
11
+ from envlib_api.api.app import create_app
12
+
13
+ logger = logging.getLogger('envlib_api')
14
+
15
+
16
+ def main():
17
+ cfg = config.load()
18
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s', stream=sys.stdout)
19
+ if cfg.sentry_dsn:
20
+ sentry_sdk.init(dsn=cfg.sentry_dsn, environment=cfg.sentry_environment, release=f'envlib-api@{__version__}')
21
+ else:
22
+ logger.warning('No [sentry] dsn: error reporting is OFF.')
23
+ app = create_app(cfg)
24
+ uvicorn.run(
25
+ app,
26
+ host=os.environ.get('ENVLIB_API_HOST', '0.0.0.0'),
27
+ port=int(os.environ.get('ENVLIB_API_PORT', '8000')),
28
+ workers=1,
29
+ log_level='info',
30
+ proxy_headers=True,
31
+ )
32
+
33
+
34
+ if __name__ == '__main__':
35
+ main()