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,354 @@
1
+ """
2
+ The refresher and the catalogue mirror against real remotes (moto) and a real MongoDB (with auth, as
3
+ the production role). Each test runs single cycles.
4
+ """
5
+
6
+ import ebooklet
7
+ import pytest
8
+ import s3func
9
+ from ebooklet.errors import StaleIndexError
10
+ from ebooklet.mongo import DATASETS, ENTRIES, MongoStore, object_reader
11
+
12
+ from envlib_api import mirror
13
+ from envlib_api.refresher import Refresher
14
+ from envlib_api.tests.support import Crash, CrashAfter, config_for
15
+
16
+ A, B, C, D = 'a' * 24, 'b' * 24, 'c' * 24, 'd' * 24
17
+
18
+
19
+ class Rec:
20
+ def __init__(self):
21
+ self.reports, self.alerts, self.checkins = [], [], []
22
+
23
+
24
+ def make(world, db, tmp_path, *, connect=None, **cfg):
25
+ rec = Rec()
26
+ r = Refresher(
27
+ config_for(world, **cfg),
28
+ db,
29
+ connect=connect,
30
+ report=rec.reports.append,
31
+ alert=rec.alerts.append,
32
+ checkin=rec.checkins.append,
33
+ heartbeat_path=tmp_path / 'heartbeat',
34
+ )
35
+ r.start()
36
+ return r, rec
37
+
38
+
39
+ def store(db, world, dvid, name):
40
+ return MongoStore(db, dvid, object_reader(world.db_url(name), http_session=s3func.HttpSession(stream=False)))
41
+
42
+
43
+ def mirrored_keys(db, dvid):
44
+ return {e['k'] for e in db[ENTRIES].find({'d': dvid}, {'k': 1})}
45
+
46
+
47
+ def two(world):
48
+ world.member('m1')
49
+ world.member('m2', n=5)
50
+ world.publish({A: 'm1', B: 'm2'})
51
+
52
+
53
+ @pytest.fixture(params=['token', 'no_token'])
54
+ def token(request, monkeypatch):
55
+ """
56
+ Run a test with ebooklet 0.13.1's incarnation token, and again with the store comparing `rev`
57
+ alone (as 0.13.0 did): the refresher's tombstones must prevent the ABA on their own.
58
+ """
59
+ if request.param == 'no_token':
60
+
61
+ def rev_only(self):
62
+ doc = self._db[DATASETS].find_one({'_id': self._d}, {'rev': 1})
63
+ return doc is None or doc['rev'] != self._rev
64
+
65
+ monkeypatch.setattr(MongoStore, '_changed', rev_only)
66
+ return request.param
67
+
68
+
69
+ # ── mirroring ──────────────────────────────────────────────────────────────────────────────────
70
+
71
+
72
+ def test_the_first_cycle_mirrors_the_catalogue_and_every_member(world, db, tmp_path):
73
+ two(world)
74
+ r, rec = make(world, db, tmp_path)
75
+ s = r.cycle()
76
+ assert s['ok'] and s['listed'] == [A, B] and s['failed'] == 0 and rec.checkins == ['ok']
77
+ docs = {d['_id']: d for d in db[mirror.CATALOGUE].find()}
78
+ assert set(docs) == {A, B}
79
+ assert docs[A]['remote_conn']['db_url'] == world.db_url('m1') and docs[A]['dataset_id'] == 'd' + A[1:]
80
+ assert 'access_key' not in repr(docs), 'a catalogue document must never carry credentials'
81
+ assert mirrored_keys(db, A) == world.remote_keys('m1') and mirrored_keys(db, B) == world.remote_keys('m2')
82
+ st = store(db, world, A, 'm1')
83
+ assert st.get('k1') == b'm1-1' * 4
84
+ st.verify()
85
+ assert (tmp_path / 'heartbeat').exists() and not rec.alerts and not rec.reports
86
+ s2 = r.cycle()
87
+ assert s2['ok'] and s2['changed'] == [] and s2['datasets'] == 2
88
+
89
+
90
+ def test_a_member_push_is_applied_on_the_next_cycle(world, db, tmp_path):
91
+ two(world)
92
+ r, _ = make(world, db, tmp_path)
93
+ r.cycle()
94
+ world.push('m1', {'new': b'fresh' * 4}, delete=('k0',))
95
+ s = r.cycle()
96
+ assert s['changed'] == [A]
97
+ assert mirrored_keys(db, A) == world.remote_keys('m1')
98
+ assert store(db, world, A, 'm1').get('new') == b'fresh' * 4
99
+
100
+
101
+ def test_new_and_changed_entries_are_listed_only_after_their_member_refresh(world, db, tmp_path):
102
+ world.member('m1')
103
+ world.publish({A: 'm1'})
104
+ r, _ = make(world, db, tmp_path)
105
+ r.cycle()
106
+ world.member('m2')
107
+ world.publish({A: 'm1', B: 'm2'}, extra_meta={'note': 2}) # A changed, B new
108
+ seen = {}
109
+ orig = r.refresh_one
110
+
111
+ def spy(dvid, url, **kw):
112
+ if dvid != mirror.CATALOGUE_ID:
113
+ seen.setdefault(dvid, db[mirror.CATALOGUE].find_one({'_id': dvid}))
114
+ return orig(dvid, url, **kw)
115
+
116
+ r.refresh_one = spy
117
+ s = r.cycle()
118
+ assert sorted(s['listed']) == [A, B]
119
+ assert seen[B] is None, 'a new entry was listed before its mirror existed'
120
+ assert 'note' not in seen[A]['user_meta'], 'a changed entry was updated before its member refresh'
121
+ assert db[mirror.CATALOGUE].find_one({'_id': A})['user_meta']['note'] == 2
122
+
123
+
124
+ # ── retire, re-add, re-point: the ABA on rev (plan review edr-worker-plan-2) ──────────────────────
125
+
126
+
127
+ def test_a_retire_then_re_add_never_serves_fill_to_a_store_built_before(world, db, tmp_path, token):
128
+ two(world)
129
+ r, _ = make(world, db, tmp_path)
130
+ r.cycle()
131
+ rev0 = db[DATASETS].find_one({'_id': A})['rev']
132
+ assert rev0 == 1, 'premise: a dataset applied once (the ABA case)'
133
+ st = store(db, world, A, 'm1')
134
+ world.deregister(A)
135
+ s = r.cycle()
136
+ assert s['retired'] == [A]
137
+ doc = db[DATASETS].find_one({'_id': A})
138
+ assert doc['retired'] and doc['missing'] and doc['applied'] is None and doc['rev'] == rev0 + 1
139
+ assert mirrored_keys(db, A) == set() and db[mirror.CATALOGUE].find_one({'_id': A}) is None
140
+ with pytest.raises(StaleIndexError):
141
+ st.get('k1') # no entry now: stale, never absent
142
+ world.publish({A: 'm1'})
143
+ s = r.cycle()
144
+ assert A in s['listed']
145
+ doc = db[DATASETS].find_one({'_id': A})
146
+ assert not doc['retired'] and doc['applied'] is not None and doc['rev'] > rev0 + 1, 'rev must never go back'
147
+ with pytest.raises(StaleIndexError):
148
+ st.verify()
149
+
150
+
151
+ def test_a_moved_db_url_is_repointed_in_place(world, db, tmp_path, token):
152
+ world.member('m1')
153
+ world.publish({A: 'm1'})
154
+ r, _ = make(world, db, tmp_path)
155
+ r.cycle()
156
+ rev0 = db[DATASETS].find_one({'_id': A})['rev']
157
+ st = store(db, world, A, 'm1')
158
+ world.copy_remote('m1', 'moved') # the same uuid and timestamp at a new URL
159
+ world.publish({A: 'moved'})
160
+ s = r.cycle()
161
+ assert s['repointed'] == [A] and s['retired'] == []
162
+ assert s['refreshed'][A]['status'] == 'applied' and s['refreshed'][A]['upserted'] == 0
163
+ doc = db[DATASETS].find_one({'_id': A})
164
+ assert doc['db_url'] == world.db_url('moved') and doc['rev'] > rev0 and not doc.get('retired')
165
+ assert db[mirror.CATALOGUE].find_one({'_id': A})['remote_conn']['db_url'] == world.db_url('moved')
166
+ with pytest.raises(StaleIndexError):
167
+ st.verify()
168
+
169
+
170
+ @pytest.mark.parametrize(
171
+ 'crash',
172
+ [
173
+ (mirror.CATALOGUE, 'delete_one'), # after step 1: the catalogue document is gone
174
+ (DATASETS, 'update_one'), # after step 2: the tombstone
175
+ (ENTRIES, 'delete_many'), # after step 3
176
+ ],
177
+ ids=['after-catalogue-doc', 'after-tombstone', 'after-entries'],
178
+ )
179
+ def test_a_retire_interrupted_at_any_step_converges(world, db, tmp_path, crash):
180
+ two(world)
181
+ r, _ = make(world, db, tmp_path)
182
+ r.cycle()
183
+ st = store(db, world, A, 'm1') # a request in flight across the retire
184
+ world.deregister(A)
185
+ cat = r.refresh_one(mirror.CATALOGUE_ID, world.catalogue_url)
186
+ assert cat['status'] == 'applied'
187
+ with pytest.raises(Crash):
188
+ mirror.sync(CrashAfter(db, *crash), True, r.refresh_one, object_reader(world.catalogue_url), max_retires=2)
189
+ try: # at the crash point: real bytes or stale, never fill
190
+ assert st.get('k1') == b'm1-1' * 4, 'an in-flight read returned fill mid-retire'
191
+ except StaleIndexError:
192
+ pass
193
+ s = r.cycle()
194
+ doc = db[DATASETS].find_one({'_id': A})
195
+ assert doc['retired'] and doc['missing'] and mirrored_keys(db, A) == set()
196
+ assert db[mirror.CATALOGUE].find_one({'_id': A}) is None
197
+ assert s['datasets'] == 1 and A not in s['refreshed'], 'a retired dataset is no longer polled'
198
+
199
+
200
+ # ── the retire guards ──────────────────────────────────────────────────────────────────────────
201
+
202
+
203
+ def test_an_empty_catalogue_retires_nothing(world, db, tmp_path):
204
+ two(world)
205
+ r, rec = make(world, db, tmp_path)
206
+ r.cycle()
207
+ world.deregister(A, B)
208
+ s = r.cycle()
209
+ assert s['retired'] == [] and 'empty' in s['blocked'] and len(rec.alerts) == 1
210
+ assert set(mirror.members(db)) == {A, B} and s['datasets'] == 2
211
+
212
+
213
+ def test_a_failed_catalogue_refresh_retires_nothing(world, db, tmp_path):
214
+ two(world)
215
+ r, rec = make(world, db, tmp_path)
216
+ r.cycle()
217
+ world.deregister(A)
218
+ assert r.refresh_one(mirror.CATALOGUE_ID, world.catalogue_url)['status'] == 'applied'
219
+ with pytest.raises(Crash): # a half-done retire: A's catalogue doc is gone
220
+ mirror.sync(
221
+ CrashAfter(db, mirror.CATALOGUE, 'delete_one'),
222
+ True,
223
+ r.refresh_one,
224
+ object_reader(world.catalogue_url),
225
+ max_retires=2,
226
+ )
227
+ out = mirror.sync(db, False, r.refresh_one, object_reader(world.catalogue_url), max_retires=2)
228
+ assert out['retired'] == [] and 'catalogue refresh failed' in out['blocked']
229
+ assert not db[DATASETS].find_one({'_id': A}).get('retired')
230
+
231
+
232
+ def test_a_missing_catalogue_retires_nothing_and_still_polls(world, db, tmp_path):
233
+ two(world)
234
+ r, rec = make(world, db, tmp_path)
235
+ r.cycle()
236
+ world.delete_remote_objects('catalogue')
237
+ s = r.cycle()
238
+ assert s['retired'] == [] and s['blocked'] and not s['ok'] and rec.checkins[-1] == 'error'
239
+ assert s['datasets'] == 2 and s['failed'] == 0, 'the mirrored datasets are still polled'
240
+
241
+
242
+ def test_a_recreated_catalogue_missing_an_entry_is_held_until_allowed(world, db, tmp_path):
243
+ two(world)
244
+ r, rec = make(world, db, tmp_path)
245
+ r.cycle()
246
+ world.delete_remote_objects('catalogue')
247
+ world.publish({A: 'm1'}, new=True)
248
+ s = r.cycle()
249
+ assert s['retired'] == [] and 'recreated' in s['blocked'] and rec.alerts
250
+ assert set(mirror.members(db)) == {A, B}
251
+ mirror.allow_retires(db)
252
+ assert r.cycle()['retired'] == [B]
253
+
254
+
255
+ def test_a_recreated_catalogue_listing_everything_is_adopted(world, db, tmp_path):
256
+ two(world)
257
+ r, rec = make(world, db, tmp_path)
258
+ r.cycle()
259
+ world.delete_remote_objects('catalogue')
260
+ world.publish({A: 'm1', B: 'm2'}, new=True)
261
+ s = r.cycle()
262
+ assert s['blocked'] is None and s['retired'] == [] and s['adopted'] is not None
263
+ assert len(rec.alerts) == 1 and 'adopted' in rec.alerts[0], 'an adoption alerts'
264
+ assert db[mirror.STATE].find_one()['catalogue_uuid'] == db[DATASETS].find_one({'_id': mirror.CATALOGUE_ID})['uuid']
265
+
266
+
267
+ def test_more_retires_than_the_cap_are_held_until_allowed(world, db, tmp_path):
268
+ for name in ('m1', 'm2', 'm3', 'm4'):
269
+ world.member(name, n=1)
270
+ world.publish({A: 'm1', B: 'm2', C: 'm3', D: 'm4'})
271
+ r, rec = make(world, db, tmp_path)
272
+ r.cycle()
273
+ world.deregister(B, C, D)
274
+ s = r.cycle()
275
+ assert s['retired'] == [] and '3 retires' in s['blocked'] and rec.alerts
276
+ mirror.allow_retires(db)
277
+ assert r.cycle()['retired'] == [B, C, D]
278
+ world.member('m5', n=1)
279
+ world.publish({B: 'm5'})
280
+ r.cycle()
281
+ world.deregister(B)
282
+ assert r.cycle()['retired'] == [B], 'one retire is within the cap'
283
+
284
+
285
+ # ── unreadable catalogue values ────────────────────────────────────────────────────────────────
286
+
287
+
288
+ def test_a_value_with_no_db_url_keeps_the_existing_document(world, db, tmp_path):
289
+ two(world)
290
+ r, rec = make(world, db, tmp_path, value_failure_alert_cycles=2)
291
+ r.cycle()
292
+ world.publish({A: 'm1'}, with_db_url=False)
293
+ s = r.cycle()
294
+ assert A in s['value_failures'] and A not in s['listed']
295
+ assert db[mirror.CATALOGUE].find_one({'_id': A})['remote_conn']['db_url'] == world.db_url('m1')
296
+ assert s['retired'] == [] and not rec.alerts
297
+ s = r.cycle()
298
+ assert len(rec.alerts) == 1 and 'unusable' in rec.alerts[0]
299
+ assert set(mirror.members(db)) == {A, B} and s['failed'] == 0
300
+
301
+
302
+ def test_a_value_pushed_without_its_commit_does_not_starve_the_others(world, db, tmp_path):
303
+ world.member('m1')
304
+ world.publish({A: 'm1'})
305
+ r, _ = make(world, db, tmp_path)
306
+ r.cycle()
307
+ world.member('m2')
308
+ world.publish({A: 'm1', B: 'm2'}, extra_meta={'note': 2}) # committed: A changed, B new
309
+ committed = world.save_db_object('catalogue')
310
+ world.publish({A: 'm1'}, extra_meta={'note': 3}) # A's value object overwritten...
311
+ world.restore_db_object('catalogue', committed) # ...and its commit lost
312
+ s = r.cycle()
313
+ assert A in s['value_failures']
314
+ assert B in s['listed'] and A not in s['listed']
315
+ assert 'note' not in db[mirror.CATALOGUE].find_one({'_id': A})['user_meta'], 'the old document is kept'
316
+ assert s['retired'] == [] and set(mirror.members(db)) == {A, B}
317
+
318
+
319
+ # ── isolation and liveness ─────────────────────────────────────────────────────────────────────
320
+
321
+
322
+ def test_one_failing_dataset_is_isolated_and_reported_once_until_it_recovers(world, db, tmp_path):
323
+ two(world)
324
+ broken = {world.db_url('m1')}
325
+
326
+ def connect(url):
327
+ if url in broken:
328
+ raise OSError('simulated: connection refused')
329
+ return ebooklet.S3Connection(db_url=url, read_timeout=5, retries=0)
330
+
331
+ r, rec = make(world, db, tmp_path, connect=connect)
332
+ r.cycle()
333
+ s = r.cycle()
334
+ assert s['failed'] == 1 and s['ok'] and len(rec.reports) == 1, 'reported once, not every cycle'
335
+ assert mirrored_keys(db, B) == world.remote_keys('m2')
336
+ broken.clear()
337
+ r.cycle()
338
+ broken.add(world.db_url('m1'))
339
+ r.cycle()
340
+ assert len(rec.reports) == 2, 'a failure after recovery is reported again'
341
+
342
+
343
+ def test_a_cycle_where_every_dataset_fails_is_an_error_and_leaves_the_heartbeat(world, db, tmp_path):
344
+ two(world)
345
+
346
+ def connect(url):
347
+ if url != world.catalogue_url:
348
+ raise OSError('simulated: every member host refuses')
349
+ return ebooklet.S3Connection(db_url=url, read_timeout=5, retries=0)
350
+
351
+ r, rec = make(world, db, tmp_path, connect=connect)
352
+ s = r.cycle()
353
+ assert not s['ok'] and rec.checkins == ['error']
354
+ assert not (tmp_path / 'heartbeat').exists(), 'only a successful dataset refresh touches the heartbeat'
@@ -0,0 +1,91 @@
1
+ """
2
+ The API's collection objects and CoverageJSON bodies against the published schemas (vendored and
3
+ pinned in tests/schemas/README.md). The EDR schemas are OpenAPI 3.1 YAML files that $ref each other
4
+ by relative path; they are resolved locally, never over the network.
5
+ """
6
+
7
+ import json
8
+ import pathlib
9
+
10
+ import jsonschema
11
+ import pytest
12
+ import yaml
13
+ from referencing import Registry, Resource
14
+ from referencing.jsonschema import DRAFT202012
15
+
16
+ from envlib_api.tests.api_support import POLY_EDGE
17
+ from envlib_api.tests.test_api import IDENTITY, cid, client, station_id
18
+
19
+ SCHEMAS = pathlib.Path(__file__).resolve().parent / 'schemas'
20
+ EDR = SCHEMAS / 'edr' / 'schemas'
21
+
22
+
23
+ def _retrieve(uri):
24
+ path = pathlib.Path(uri.removeprefix('file://'))
25
+ return Resource.from_contents(yaml.safe_load(path.read_text()), default_specification=DRAFT202012)
26
+
27
+
28
+ def edr_validator(rel):
29
+ path = EDR / rel
30
+ schema = yaml.safe_load(path.read_text())
31
+ schema['$id'] = path.as_uri()
32
+ registry = Registry(retrieve=_retrieve)
33
+ return jsonschema.Draft202012Validator(schema, registry=registry)
34
+
35
+
36
+ def covjson_validator():
37
+ schema = json.loads((SCHEMAS / 'coveragejson' / 'coveragejson.json').read_text())
38
+ return jsonschema.Draft202012Validator(schema)
39
+
40
+
41
+ def _errors(validator, obj):
42
+ return [f'{"/".join(map(str, e.absolute_path))}: {e.message}' for e in validator.iter_errors(obj)]
43
+
44
+
45
+ def test_the_collection_objects_validate_against_edr_1_2(mirror):
46
+ v = edr_validator('collections/collection.yaml')
47
+ cols = client(mirror).get('/collections').json()['collections']
48
+ assert cols
49
+ for col in cols:
50
+ assert _errors(v, col) == [], col['id']
51
+
52
+
53
+ def test_the_collection_validator_rejects_a_broken_collection(mirror):
54
+ """It must fail on purpose: a collection without data_queries, and one with crs objects."""
55
+ v = edr_validator('collections/collection.yaml')
56
+ col = client(mirror).get(f'/collections/{cid(mirror, "sf")}').json()
57
+ assert _errors(v, {k: x for k, x in col.items() if k != 'data_queries'})
58
+ assert _errors(v, {**col, 'crs': [{'crs': 'CRS84', 'wkt': '...'}]})
59
+
60
+
61
+ @pytest.mark.parametrize('kind', ['location', 'area'])
62
+ def test_coveragejson_bodies_validate(mirror, kind):
63
+ c = client(mirror)
64
+ if kind == 'location':
65
+ r = c.get(
66
+ f'/collections/{cid(mirror, "gh")}/locations/{station_id(mirror, "gh", "B")}',
67
+ params={'datetime': '2019-12-30T18:00Z/..'},
68
+ )
69
+ else:
70
+ r = c.get(
71
+ f'/collections/{cid(mirror, "sf")}/area',
72
+ params={'coords': POLY_EDGE, 'datetime': '2020-01-02T00:00Z/2020-01-02T10:00Z'},
73
+ )
74
+ assert r.status_code == 200
75
+ assert _errors(covjson_validator(), r.json()) == []
76
+
77
+
78
+ def test_the_coveragejson_validator_rejects_a_broken_coverage(mirror):
79
+ r = client(mirror).get(
80
+ f'/collections/{cid(mirror, "sf")}/locations/{station_id(mirror, "sf", "A")}',
81
+ params={'datetime': '2020-01-01T00:00Z/2020-01-01T03:00Z'},
82
+ headers=IDENTITY,
83
+ )
84
+ cov = r.json()
85
+ broken = json.loads(json.dumps(cov))
86
+ broken['domain']['domainType'] = 'PointSeries'
87
+ del broken['domain']['axes']['t']
88
+ assert _errors(covjson_validator(), broken)
89
+ labelled = json.loads(json.dumps(cov))
90
+ labelled['parameters']['streamflow']['observedProperty']['label'] = 'streamflow' # not an i18n object
91
+ assert _errors(covjson_validator(), labelled)