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
@@ -0,0 +1,307 @@
1
+ """
2
+ Test support for the API: real ts_ortho datasets built and published by envlib-ingest-base's
3
+ `build_and_publish` (the real producer) into moto, mirrored by the real Refresher into an
4
+ auth-enabled MongoDB, and read by the app as the `api` user under the production role
5
+ (mongo/api-role.json).
6
+
7
+ Datasets (all hourly, from 2020-01-01T00, chunk (1, 24), so windows cross chunk boundaries):
8
+ - `sf`: streamflow, per-key, 5 stations. B is all-NaN over steps [30, 60). C is at lon -176.5
9
+ (the Chathams). D sits exactly on POLY_EDGE's boundary.
10
+ - `gh`: gage height with `quality_code`, grouped, 3 stations, and a time axis prepended by 30
11
+ steps through cfdb after the build, so its origin is negative.
12
+ - `pv1` / `pv2`: precipitation versions 1 and 2 of one dataset_id, published at distinct `created_at` stamps (a controlled clock).
13
+ Then v1 is re-published, so its catalogue entry is the newest by `ts` but not by `created_at`.
14
+ """
15
+
16
+ import itertools
17
+ import json
18
+ import pathlib
19
+ import uuid
20
+
21
+ import cfdb
22
+ import ebooklet
23
+ import envlib
24
+ import envlib.catalogue
25
+ import numpy as np
26
+ import pymongo
27
+ import pytest
28
+ import s3func.locking
29
+ from envlib_ingest_base.tsortho import build_and_publish
30
+
31
+ from envlib_api.config import Config
32
+ from envlib_api.refresher import Refresher
33
+ from envlib_api.tests.support import create_user, public_bucket, s3_client, user_uri
34
+
35
+ API_ROLE_FILE = pathlib.Path(__file__).resolve().parents[2] / 'mongo' / 'api-role.json'
36
+ T0 = np.datetime64('2020-01-01T00', 'h')
37
+ HOUR = np.timedelta64(1, 'h')
38
+ N_STEPS = 100
39
+ TIMES = np.arange(T0, T0 + HOUR * N_STEPS, HOUR)
40
+ POLY_EDGE = 'POLYGON((171 -45,173 -45,173 -44,171 -44,171 -45))' # D (172.0, -44.0) is on its edge
41
+ STATIONS = {
42
+ 'A': {'lon': 172.5, 'lat': -43.5, 'name': 'Alpha'},
43
+ 'B': {'lon': 171.9, 'lat': -43.1, 'name': 'Bravo'},
44
+ 'C': {'lon': -176.5, 'lat': -44.0, 'name': 'Chatham'},
45
+ 'D': {'lon': 172.0, 'lat': -44.0, 'name': 'Delta, "upper"\nreach'}, # CSV must quote a comma, a quote and a newline
46
+ 'E': {'lon': 172.2, 'lat': -44.6, 'name': 'Echo'},
47
+ }
48
+ ENC_SF = {'variable': 'streamflow', 'units': 'm^3/s', 'precision': 4, 'min_value': -1, 'max_value': 100000}
49
+ ENC_GH = {'variable': 'gage_height', 'units': 'm', 'precision': 3, 'min_value': -6, 'max_value': 100}
50
+ ENC_PV = {'variable': 'precipitation', 'units': 'mm', 'precision': 1, 'min_value': -1, 'max_value': 1000}
51
+ QC = {'quality_code': {'units': '1', 'precision': 0, 'min_value': 0, 'max_value': 1000}}
52
+
53
+
54
+ def api_role_spec(db_name):
55
+ spec = json.loads(API_ROLE_FILE.read_text().replace('"DB"', json.dumps(db_name)))
56
+ return spec['role'], spec['privileges'], spec['roles']
57
+
58
+
59
+ def create_api_user(admin_client, db_name, password, *, privileges=None):
60
+ role, privs, roles = api_role_spec(db_name)
61
+ admin_client[db_name].command('createRole', role, privileges=privileges or privs, roles=roles)
62
+ admin_client[db_name].command('createUser', 'api', pwd=password, roles=[{'role': role, 'db': db_name}])
63
+
64
+
65
+ def meta(variable, statistic='mean', version='1', processing_level='raw'):
66
+ return envlib.Metadata(
67
+ feature='waterway' if variable != 'precipitation' else 'atmosphere',
68
+ variable=variable,
69
+ method='sensor_recording',
70
+ product_code=None,
71
+ processing_level=processing_level,
72
+ owner='ecan',
73
+ aggregation_statistic=statistic,
74
+ frequency_interval='1h',
75
+ utc_offset='+00:00',
76
+ spatial_resolution='point',
77
+ version=version,
78
+ license='CC-BY-4.0',
79
+ attribution='Environment Canterbury',
80
+ )
81
+
82
+
83
+ def _series(refs, rng, precision, low=0.0, high=50.0, nan_rows=None, qc=False):
84
+ out = {}
85
+ for ref in refs:
86
+ vals = np.round(rng.uniform(low, high, N_STEPS), precision)
87
+ if nan_rows and ref in nan_rows:
88
+ a, b = nan_rows[ref]
89
+ vals[a:b] = np.nan
90
+ if qc:
91
+ out[ref] = (TIMES, vals, {'quality_code': rng.integers(0, 600, N_STEPS).astype('float64')})
92
+ else:
93
+ out[ref] = (TIMES, vals)
94
+ return out
95
+
96
+
97
+ class ApiWorld:
98
+ """The published datasets and the inputs they were built from."""
99
+
100
+ def __init__(self, moto_url, tmp):
101
+ self.url = moto_url
102
+ self.tmp = tmp
103
+ self.bucket = public_bucket(s3_client(moto_url)) # a bucket per world (support.public_bucket)
104
+ self.prefix = uuid.uuid4().hex[:12]
105
+ self.inputs = {} # name -> {ref: (times, values[, extras])}
106
+ self.dvid = {}
107
+ self.dataset_id = {}
108
+
109
+ def conn(self, name):
110
+ return ebooklet.S3Connection(
111
+ access_key_id='test',
112
+ access_key='test',
113
+ db_key=f'{self.prefix}/{name}',
114
+ bucket=self.bucket,
115
+ endpoint_url=self.url,
116
+ db_url=f'{self.url}/{self.bucket}/{self.prefix}/{name}',
117
+ )
118
+
119
+ @property
120
+ def rcg(self):
121
+ return self.conn('catalogue')
122
+
123
+ def catalogue(self):
124
+ return envlib.Catalogue(remotes=[self.rcg], cache=self.tmp / 'catcache')
125
+
126
+ def publish(self, name, md, stations, series, enc, **kw):
127
+ res = build_and_publish(
128
+ self.catalogue(),
129
+ self.tmp / f'{name}.cfdb',
130
+ self.conn(name),
131
+ self.rcg,
132
+ md,
133
+ stations,
134
+ series,
135
+ chunk_shape=(1, 24),
136
+ **enc,
137
+ **kw,
138
+ )
139
+ self.inputs[name] = series
140
+ self.dvid[name] = res['dataset_version_id']
141
+ self.dataset_id[name] = res['dataset_id']
142
+ return res
143
+
144
+ def direct(self, name):
145
+ """A direct read of the remote, as envlib's DatasetRef.open() does (the oracle)."""
146
+ conn = ebooklet.S3Connection(db_url=self.conn(name).db_url)
147
+ return cfdb.open_edataset(conn, self.tmp / f'direct-{name}-{uuid.uuid4().hex[:6]}.cfdb', flag='r')
148
+
149
+
150
+ def build_world(moto_url, tmp):
151
+ """
152
+ envlib stamps `created_at` to the second, so two publishes in one second tie. Instead of sleeping,
153
+ the build runs on a clock that advances one minute per stamp.
154
+ """
155
+ ticks = itertools.count()
156
+ real_now = envlib.catalogue._utc_now_iso
157
+
158
+ def stamp():
159
+ n = next(ticks)
160
+ return f'2026-01-01T{n // 60:02d}:{n % 60:02d}:00Z'
161
+
162
+ envlib.catalogue._utc_now_iso = stamp
163
+ try:
164
+ return _build_world(moto_url, tmp)
165
+ finally:
166
+ envlib.catalogue._utc_now_iso = real_now
167
+
168
+
169
+ def _build_world(moto_url, tmp):
170
+ w = ApiWorld(moto_url, tmp)
171
+ with ebooklet.open_rcg(w.rcg, tmp / 'cat.rcg', flag='n', group_bytes=None) as r:
172
+ r.changes().push()
173
+ rng = np.random.default_rng(42)
174
+ w.publish(
175
+ 'sf',
176
+ meta('streamflow'),
177
+ STATIONS,
178
+ _series(STATIONS, rng, 4, nan_rows={'B': (30, 60)}),
179
+ ENC_SF,
180
+ group_bytes=None,
181
+ )
182
+ ## gh: grouped, with quality_code; then 30 steps prepended through cfdb (a negative time origin).
183
+ gh_st = {k: STATIONS[k] for k in ('A', 'B', 'D')}
184
+ gh_series = _series(gh_st, rng, 3, low=-2.0, high=8.0, qc=True)
185
+ w.publish('gh', meta('gage_height'), gh_st, gh_series, {**ENC_GH, 'ancillary': QC}, group_bytes=4096)
186
+ with cfdb.open_edataset(w.conn('gh'), tmp / 'gh.cfdb', flag='w') as ds:
187
+ ds['time'].prepend(np.arange(T0 - HOUR * 30, T0, HOUR))
188
+ early = np.round(rng.uniform(-2.0, 8.0, (3, 30)), 3)
189
+ ds['gage_height'][:, 0:30] = early
190
+ assert ds['time'].origin == -30
191
+ ds.push()
192
+ w.gh_early = early
193
+ w.catalogue().publish(str(tmp / 'gh.cfdb'), w.conn('gh'), w.rcg)
194
+ ## pv1 / pv2: two versions of one dataset_id, then v1 re-published (newest ts, older created_at).
195
+ pv_st = {k: STATIONS[k] for k in ('A', 'E')}
196
+ w.publish('pv1', meta('precipitation', 'sum', version='1'), pv_st, _series(pv_st, rng, 1), ENC_PV, group_bytes=None)
197
+ w.publish('pv2', meta('precipitation', 'sum', version='2'), pv_st, _series(pv_st, rng, 1), ENC_PV, group_bytes=None)
198
+ ## One more step, so the entry's time range (and therefore the entry) changes on re-publish:
199
+ ## envlib skips an upsert whose user_meta is unchanged.
200
+ with cfdb.open_edataset(w.conn('pv1'), tmp / 'pv1.cfdb', flag='w') as ds:
201
+ ds['time'].append(np.array([T0 + HOUR * N_STEPS]))
202
+ ds['precipitation'][0, N_STEPS : N_STEPS + 1] = np.array([[7.5]])
203
+ ext = np.arange(T0, T0 + HOUR * (N_STEPS + 1), HOUR)
204
+ w.inputs['pv1'] = {
205
+ 'A': (ext, np.append(w.inputs['pv1']['A'][1], 7.5)),
206
+ 'E': (ext, np.append(w.inputs['pv1']['E'][1], np.nan)),
207
+ }
208
+ w.catalogue().publish(str(tmp / 'pv1.cfdb'), w.conn('pv1'), w.rcg)
209
+ assert w.dataset_id['pv1'] == w.dataset_id['pv2'] and w.dvid['pv1'] != w.dvid['pv2']
210
+ return w
211
+
212
+
213
+ def refresher_config(world):
214
+ return Config(mongo_uri='unused-in-process', catalogue_url=world.rcg.db_url, read_timeout=5, retries=0)
215
+
216
+
217
+ def api_config(**kw):
218
+ base = dict(mongo_uri='unused-in-process', retry_wait_ms=10, api_read_timeout=5, api_retries=0)
219
+ return Config(**{**base, **kw})
220
+
221
+
222
+ def make_dbs(mongo_admin, mongo_admin_uri):
223
+ """A fresh database with a `refresher` user (production role) and an `api` user (API role)."""
224
+ name = f'envlib_api_t_{uuid.uuid4().hex[:10]}'
225
+ rpw, apw = uuid.uuid4().hex, uuid.uuid4().hex
226
+ create_user(mongo_admin, name, 'refresher', rpw)
227
+ create_api_user(mongo_admin, name, apw)
228
+ rc = pymongo.MongoClient(user_uri(mongo_admin_uri, name, 'refresher', rpw), tz_aware=True)
229
+ ac = pymongo.MongoClient(user_uri(mongo_admin_uri, name, 'api', apw), tz_aware=True)
230
+ return name, rc, ac
231
+
232
+
233
+ def drop_dbs(mongo_admin, name, *clients):
234
+ for c in clients:
235
+ c.close()
236
+ mongo_admin.drop_database(name)
237
+ mongo_admin[name].command('dropAllUsersFromDatabase')
238
+ mongo_admin[name].command('dropAllRolesFromDatabase')
239
+
240
+
241
+ def refresh_into(world, rdb):
242
+ r = Refresher(refresher_config(world), rdb)
243
+ r.start()
244
+ res = r.cycle()
245
+ assert res['ok'] and not res['failed'], res
246
+ return res
247
+
248
+
249
+ class Mirror:
250
+ """A world mirrored into one database: `rdb` as the refresher, `adb` as the API, `admin` as root."""
251
+
252
+ def __init__(self, world, name, rdb, adb, admin):
253
+ self.world = world
254
+ self.name = name
255
+ self.rdb = rdb
256
+ self.adb = adb
257
+ self.admin = admin
258
+
259
+
260
+ @pytest.fixture(scope='session')
261
+ def api_world(moto_url, tmp_path_factory):
262
+ real = s3func.locking.sleep
263
+ s3func.locking.sleep = lambda s: real(min(s, 0.01))
264
+ try:
265
+ yield build_world(moto_url, tmp_path_factory.mktemp('apiworld'))
266
+ finally:
267
+ s3func.locking.sleep = real
268
+
269
+
270
+ @pytest.fixture(scope='session')
271
+ def mirror(api_world, mongo_admin, mongo_admin_uri):
272
+ """The world mirrored once, shared by the read-only tests."""
273
+ name, rc, ac = make_dbs(mongo_admin, mongo_admin_uri)
274
+ refresh_into(api_world, rc[name])
275
+ yield Mirror(api_world, name, rc[name], ac[name], mongo_admin[name])
276
+ drop_dbs(mongo_admin, name, rc, ac)
277
+
278
+
279
+ @pytest.fixture
280
+ def fresh_mirror(api_world, mongo_admin, mongo_admin_uri):
281
+ """The world mirrored into a database of its own, for tests that change MongoDB."""
282
+ name, rc, ac = make_dbs(mongo_admin, mongo_admin_uri)
283
+ refresh_into(api_world, rc[name])
284
+ yield Mirror(api_world, name, rc[name], ac[name], mongo_admin[name])
285
+ drop_dbs(mongo_admin, name, rc, ac)
286
+
287
+
288
+ @pytest.fixture
289
+ def small_mirror(moto_url, tmp_path, mongo_admin, mongo_admin_uri):
290
+ """
291
+ One small per-key dataset in a world of its own (its remote is changed by the test), mirrored
292
+ into a database of its own.
293
+ """
294
+ real = s3func.locking.sleep
295
+ s3func.locking.sleep = lambda s: real(min(s, 0.01))
296
+ w = ApiWorld(moto_url, tmp_path)
297
+ with ebooklet.open_rcg(w.rcg, tmp_path / 'cat.rcg', flag='n', group_bytes=None) as r:
298
+ r.changes().push()
299
+ st = {k: STATIONS[k] for k in ('A', 'B')}
300
+ w.publish('sf', meta('streamflow'), st, _series(st, np.random.default_rng(7), 4), ENC_SF, group_bytes=None)
301
+ name, rc, ac = make_dbs(mongo_admin, mongo_admin_uri)
302
+ refresh_into(w, rc[name])
303
+ try:
304
+ yield Mirror(w, name, rc[name], ac[name], mongo_admin[name])
305
+ finally:
306
+ s3func.locking.sleep = real
307
+ drop_dbs(mongo_admin, name, rc, ac)
@@ -0,0 +1,12 @@
1
+ from envlib_api.tests.api_support import api_world, fresh_mirror, mirror, small_mirror # noqa: F401,E402 (fixtures)
2
+ from envlib_api.tests.grid_support import grid_mirror, grid_world # noqa: F401 (fixtures)
3
+ from envlib_api.tests.support import ( # noqa: F401 (fixtures)
4
+ db,
5
+ db_and_uri,
6
+ fast_lock_settle,
7
+ mongo_admin,
8
+ mongo_admin_uri,
9
+ moto_url,
10
+ readwrite_db,
11
+ world,
12
+ )
@@ -0,0 +1,217 @@
1
+ """
2
+ Test support for grid collections: real grid datasets, each built by its real producer, published into
3
+ moto with envlib, mirrored by the real Refresher into the auth-enabled MongoDB, and read by the app as
4
+ the `api` user (plan 4, Step 4).
5
+
6
+ - `wrf`: hourly 2 m temperature. `cfdb_ingest.wrf_synthetic.write_wrfout` writes a Lambert wrfout
7
+ (MAP_PROJ 1, live d03's truelats and stand_lon, 30 x 40 cells at 3 km) straddling the antimeridian,
8
+ and `WrfIngest.convert` converts it, a later band first and an earlier one by `extend`, so the time
9
+ origin is negative as on the live grids. The synthetic T2 gradient (0.001 K per cell, stored at
10
+ 0.01 K) leaves 90 % of x-neighbours identical (plan review edr-api-plan-4), so a fixture-side
11
+ transform adds a steeper gradient before conversion.
12
+ - `soil`: 6-hourly SMOIS and DZS through `WrfIngest`. Its depth comes out as live does:
13
+ 0.1, 0.4, 0.9999999999999999, 2.0.
14
+ - `static`: one HGT frame through `valid_time`, as the live altitude grid: one chunk for the map.
15
+ - `sst`: built through cfdb as `envlib-ingest-esa-sst`'s `build_sst_cfdb.py` does it, from float32
16
+ centres (so the spacing is irregular, as live) crossing 180, daily, two variables at precision 2.
17
+
18
+ `GridWorld.wrfouts` keeps the wrfout paths: their XLAT/XLONG is the cell oracle.
19
+ """
20
+
21
+ import pathlib
22
+ import warnings
23
+
24
+ import cfdb
25
+ import ebooklet
26
+ import envlib
27
+ import h5py
28
+ import numpy as np
29
+ import pytest
30
+ import s3func.locking
31
+ from cfdb import dtypes
32
+ from cfdb_ingest import WrfIngest
33
+ from cfdb_ingest import wrf_synthetic as syn
34
+
35
+ from envlib_api.tests.api_support import ApiWorld, drop_dbs, make_dbs, refresh_into
36
+
37
+ PROJ = dict(dx=3000.0, truelat1=-39.619, truelat2=-39.619, stdlon=-129.917)
38
+ NY, NX = 30, 40
39
+ LAT0, LON0 = -38.9, 179.3 # the south-west cell centre: the grid straddles 180 (Fable: 715 of 1,200 cells east)
40
+ SST_LAT = (np.arange(-41.975, -38.0, 0.05)).astype('float32').astype('float64') # 80 centres, float32 noise
41
+ SST_LON = (np.arange(178.025, 182.0, 0.05)).astype('float32').astype('float64') # 80 centres across 180
42
+ SST_DAYS = np.arange(np.datetime64('2026-01-01'), np.datetime64('2026-01-11'))
43
+
44
+
45
+ def grid_meta(variable, statistic='point', frequency='1h', feature='atmosphere', owner='uc', resolution='3km'):
46
+ return envlib.Metadata(
47
+ feature=feature,
48
+ variable=variable,
49
+ method='simulation',
50
+ product_code='wrf-test' if owner == 'uc' else 'sst-test',
51
+ processing_level='quality_controlled',
52
+ owner=owner,
53
+ aggregation_statistic=statistic,
54
+ frequency_interval=frequency,
55
+ utc_offset='+00:00',
56
+ spatial_resolution=resolution,
57
+ version='1',
58
+ license='CC-BY-4.0',
59
+ attribution='Synthetic test grid',
60
+ )
61
+
62
+
63
+ def _steeper_t2(h5):
64
+ jj, ii = np.meshgrid(np.arange(NY), np.arange(NX), indexing='ij')
65
+ h5['T2'][...] = (h5['T2'][...] + 0.37 * ii + 0.11 * jj).astype('float32')
66
+
67
+
68
+ def _soil(seed):
69
+ def add(h5):
70
+ n = h5['Times'].shape[0]
71
+ rng = np.random.default_rng(seed)
72
+ h5.create_dataset('SMOIS', data=rng.uniform(0.1, 0.45, (n, 4, NY, NX)).astype('float32'))
73
+ h5.create_dataset('DZS', data=np.broadcast_to(np.array([0.1, 0.3, 0.6, 1.0], 'float32'), (n, 4)).copy())
74
+
75
+ return add
76
+
77
+
78
+ def _hgt(h5):
79
+ n = h5['Times'].shape[0]
80
+ jj, ii = np.meshgrid(np.arange(NY), np.arange(NX), indexing='ij')
81
+ hgt = (ii * 17.3 + jj * 5.1 + 3.0 * np.sin(ii * jj)).astype('float32')
82
+ h5.create_dataset('HGT', data=np.broadcast_to(hgt, (n, NY, NX)).copy())
83
+
84
+
85
+ class GridWorld(ApiWorld):
86
+ def __init__(self, moto_url, tmp):
87
+ super().__init__(moto_url, tmp)
88
+ self.wrfouts = {}
89
+
90
+ def wrfout(self, name, start, n, transform, hour_step=1):
91
+ p = syn.write_wrfout(
92
+ self.tmp / f'wrfout_d03_{name}',
93
+ start,
94
+ n,
95
+ NY,
96
+ NX,
97
+ hour_step=hour_step,
98
+ map_proj=1,
99
+ projection=PROJ,
100
+ lat0=LAT0,
101
+ lon0=LON0,
102
+ variables=('T2',),
103
+ )
104
+ with h5py.File(p, 'r+') as h5:
105
+ transform(h5)
106
+ self.wrfouts[name] = p
107
+ return p
108
+
109
+ def publish_file(self, name, path, md):
110
+ with cfdb.open_dataset(path, flag='w') as ds:
111
+ ds.attrs.update(md.to_dict())
112
+ res = self.catalogue().publish(str(path), self.conn(name), self.rcg)
113
+ self.dvid[name] = res['dataset_version_id']
114
+ self.dataset_id[name] = res['dataset_id']
115
+ return res
116
+
117
+
118
+ def _convert(paths, out, **kw):
119
+ with warnings.catch_warnings():
120
+ warnings.simplefilter('ignore') # cfdb-ingest's notes on the synthetic files' missing winds
121
+ for p in paths:
122
+ WrfIngest(p).convert(out, **kw)
123
+
124
+
125
+ def build_sst(path):
126
+ """As build_sst_cfdb.py: lat/lon templates, a daily time axis, the CRS, int-packed float32 variables."""
127
+ sst_dt = dtypes.dtype('float32', precision=2, min_value=270.0, max_value=320.0)
128
+ ice_dt = dtypes.dtype('float32', precision=2, min_value=0.0, max_value=1.0)
129
+ coords = ('time', 'latitude', 'longitude')
130
+ rng = np.random.default_rng(11)
131
+ with cfdb.open_dataset(path, flag='n') as ds:
132
+ ds.create.coord.lat(data=SST_LAT)
133
+ ds.create.coord.lon(data=SST_LON)
134
+ ds.create.coord.time(data=SST_DAYS, step=1)
135
+ ds.create.crs.from_user_input(4326, x_coord='longitude', y_coord='latitude')
136
+ sst = ds.create.data_var.generic('temperature', coords, dtype=sst_dt, chunk_shape=(4, 6, 6))
137
+ sst.attrs.update({'units': 'K', 'standard_name': 'sea_water_temperature'})
138
+ ice = ds.create.data_var.generic('sea_ice_fraction', coords, dtype=ice_dt, chunk_shape=(4, 6, 6))
139
+ ice.attrs.update({'units': '1', 'standard_name': 'sea_ice_area_fraction'})
140
+ nt, ny, nx = len(SST_DAYS), len(SST_LAT), len(SST_LON)
141
+ jj, ii = np.meshgrid(np.arange(ny), np.arange(nx), indexing='ij')
142
+ base = 285.0 + 0.07 * ii - 0.05 * jj
143
+ for t0 in range(0, nt, 4): # chunk by chunk along time, as the producer writes windows
144
+ t1 = min(t0 + 4, nt)
145
+ vals = base[None] + rng.normal(0, 0.3, (t1 - t0, ny, nx))
146
+ vals[:, :5, :7] = np.nan # "land"
147
+ sst[t0:t1] = np.round(vals, 2)
148
+ ice[t0:t1] = np.round(rng.uniform(0, 1, (t1 - t0, ny, nx)), 2)
149
+
150
+
151
+ def build_grid_world(moto_url, tmp):
152
+ w = GridWorld(moto_url, tmp)
153
+ with ebooklet.open_rcg(w.rcg, tmp / 'cat.rcg', flag='n', group_bytes=None) as r:
154
+ r.changes().push()
155
+ # wrf: the later band first, then an earlier one prepended by extend (a negative time origin)
156
+ later = w.wrfout('wrf_b', '2026-01-02T00', 12, _steeper_t2)
157
+ earlier = w.wrfout('wrf_a', '2026-01-01T12', 12, _steeper_t2)
158
+ kw = dict(variables=['T2'], names={'T2': 'temperature'}, chunk_shape=(6, 8, 8), squeeze_height=True, extend=True)
159
+ _convert([later, earlier], tmp / 'wrf.cfdb', **kw)
160
+ w.publish_file('wrf', tmp / 'wrf.cfdb', grid_meta('temperature'))
161
+ # soil: 6-hourly frames, 4 per file, the later file first
162
+ s_late = w.wrfout('soil_b', '2026-01-02T00', 4, _soil(2), hour_step=6)
163
+ s_early = w.wrfout('soil_a', '2026-01-01T00', 4, _soil(1), hour_step=6)
164
+ kw = dict(
165
+ variables=['SMOIS'],
166
+ names={'SMOIS': 'volumetric_water_content'},
167
+ chunk_shape=(3, 1, 8, 8),
168
+ extend=True,
169
+ frame_step_minutes=360,
170
+ )
171
+ _convert([s_late, s_early], tmp / 'soil.cfdb', **kw)
172
+ w.publish_file('soil', tmp / 'soil.cfdb', grid_meta('volumetric_water_content', frequency='6h', feature='soil'))
173
+ # static: one HGT frame stored at a fixed time
174
+ st = w.wrfout('static', '2026-01-01T00', 1, _hgt)
175
+ kw = dict(
176
+ variables=['HGT'],
177
+ names={'HGT': 'altitude'},
178
+ chunk_shape=(1, NY, NX),
179
+ squeeze_height=True,
180
+ valid_time='1980-01-01T00:00',
181
+ start_date='2026-01-01T00:00',
182
+ end_date='2026-01-01T00:00',
183
+ )
184
+ _convert([st], tmp / 'static.cfdb', **kw)
185
+ w.publish_file('static', tmp / 'static.cfdb', grid_meta('altitude', frequency=None, feature='land'))
186
+ # sst: cfdb-built, as the SST producer
187
+ build_sst(tmp / 'sst.cfdb')
188
+ md = grid_meta('temperature', statistic='mean', frequency='day', feature='ocean', owner='esa', resolution='0.05deg')
189
+ w.publish_file('sst', tmp / 'sst.cfdb', md)
190
+ return w
191
+
192
+
193
+ @pytest.fixture(scope='session')
194
+ def grid_world(moto_url, tmp_path_factory):
195
+ real = s3func.locking.sleep
196
+ s3func.locking.sleep = lambda s: real(min(s, 0.01)) # as api_world: the lock settle, not the test's subject
197
+ try:
198
+ yield build_grid_world(moto_url, pathlib.Path(tmp_path_factory.mktemp('gridworld')))
199
+ finally:
200
+ s3func.locking.sleep = real
201
+
202
+
203
+ class GridMirror:
204
+ def __init__(self, world, name, rdb, adb, admin):
205
+ self.world = world
206
+ self.name = name
207
+ self.rdb = rdb
208
+ self.adb = adb
209
+ self.admin = admin
210
+
211
+
212
+ @pytest.fixture(scope='session')
213
+ def grid_mirror(grid_world, mongo_admin, mongo_admin_uri):
214
+ name, rc, ac = make_dbs(mongo_admin, mongo_admin_uri)
215
+ refresh_into(grid_world, rc[name])
216
+ yield GridMirror(grid_world, name, rc[name], ac[name], mongo_admin[name])
217
+ drop_dbs(mongo_admin, name, rc, ac)
@@ -0,0 +1,12 @@
1
+ # Vendored schemas (test-only)
2
+
3
+ The API tests validate responses against these. Both are fetched verbatim and pinned to a commit:
4
+ OGC has no EDR 1.2 tag, and `schemas.opengis.net/ogcapi/edr/1.2/` returned 404 (plan review
5
+ `edr-api-plan-3`).
6
+
7
+ | Directory | Source | Commit | Fetched |
8
+ |---|---|---|---|
9
+ | `coveragejson/coveragejson.json` | `opengeospatial/CoverageJSON`, `standard/schema/build/2020-12/coveragejson.json` (the bundled JSON Schema 2020-12) | `4ae86873f12e990a5aab6d7dd2ad19063ee347c8` | 2026-11-24 |
10
+ | `edr/schemas/` | `opengeospatial/ogcapi-environmental-data-retrieval`, `core/standard/openapi/oas31/schemas/` (EDR 1.2, OpenAPI 3.1) | `3e0a0016c53816008c56eed7b0ceacfdcba48ac5` | 2026-11-24 |
11
+
12
+ To refresh, fetch the same paths at a newer commit and update this table.