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,320 @@
1
+ """
2
+ Test support: a moto S3 server holding real ebooklet remotes and a real catalogue (a per-key
3
+ RemoteConnGroup, format 2, like the live commons catalogue), and a real MongoDB with auth.
4
+
5
+ - MongoDB: ENVLIB_API_TEST_MONGO_URI must name an auth-enabled server, as a user that can create
6
+ users and roles (e.g. the root user of
7
+ `docker run -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=... mongo:9.0.8`).
8
+ Each test gets its own database. The refresher connects to it as a user with the production role
9
+ in mongo/refresher-role.json, the same file the deployment's init script reads. Without the URI
10
+ the MongoDB tests skip locally and fail under CI.
11
+ - S3: one moto server per session with a public-read bucket (envlib member buckets are public),
12
+ and a fresh key prefix per test. Pushes authenticate; the refresher reads anonymously over HTTP
13
+ through each remote's db_url, as in production.
14
+ - s3func's lock waits `settle_delay` (1 s) between two listings, because real S3 listings are only
15
+ eventually consistent. moto is strongly consistent, so the tests cap s3func's lock sleeps at
16
+ 10 ms. Without this every push costs a second.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import pathlib
22
+ import socket
23
+ import uuid
24
+
25
+ import boto3
26
+ import ebooklet
27
+ import pymongo
28
+ import pytest
29
+ import s3func.locking
30
+ from moto.server import ThreadedMotoServer
31
+
32
+ from envlib_api.config import Config
33
+
34
+ ROLE_FILE = pathlib.Path(__file__).resolve().parents[2] / 'mongo' / 'refresher-role.json'
35
+ BUCKET = 'envlib-api-test'
36
+ MONGO_ENV = 'ENVLIB_API_TEST_MONGO_URI'
37
+
38
+
39
+ def free_port():
40
+ s = socket.socket()
41
+ s.bind(('127.0.0.1', 0))
42
+ port = s.getsockname()[1]
43
+ s.close()
44
+ return port
45
+
46
+
47
+ def s3_client(url):
48
+ return boto3.client(
49
+ 's3', endpoint_url=url, aws_access_key_id='test', aws_secret_access_key='test', region_name='us-east-1'
50
+ )
51
+
52
+
53
+ def public_bucket(b3, name=None):
54
+ """
55
+ Create a public-read bucket on the moto server and return its name (a fresh one by default).
56
+
57
+ Every test world gets its own bucket (code review edr-api-code-4). moto's list_object_versions
58
+ deep-copies every key in a bucket whatever the prefix, so worlds sharing one bucket made each
59
+ listing pay for every earlier world's objects: the whole suite peaked at 11.9 GB in one process.
60
+ """
61
+ name = name or f'envlib-api-t-{uuid.uuid4().hex[:12]}'
62
+ b3.create_bucket(Bucket=name)
63
+ b3.put_bucket_policy(
64
+ Bucket=name,
65
+ Policy=json.dumps(
66
+ {
67
+ 'Version': '2012-10-17',
68
+ 'Statement': [
69
+ {
70
+ 'Effect': 'Allow',
71
+ 'Principal': '*',
72
+ 'Action': ['s3:GetObject', 's3:HeadObject'],
73
+ 'Resource': f'arn:aws:s3:::{name}/*',
74
+ }
75
+ ],
76
+ }
77
+ ),
78
+ )
79
+ return name
80
+
81
+
82
+ def role_spec(db_name):
83
+ """The production role, for database `db_name` (the file's 'DB' placeholder replaced)."""
84
+ spec = json.loads(ROLE_FILE.read_text().replace('"DB"', json.dumps(db_name)))
85
+ return spec['role'], spec['privileges'], spec['roles']
86
+
87
+
88
+ def create_user(admin_client, db_name, user, password, *, production_role=True):
89
+ db = admin_client[db_name]
90
+ if production_role:
91
+ role, privileges, roles = role_spec(db_name)
92
+ db.command('createRole', role, privileges=privileges, roles=roles)
93
+ db.command('createUser', user, pwd=password, roles=[{'role': role, 'db': db_name}])
94
+ else:
95
+ db.command('createUser', user, pwd=password, roles=[{'role': 'readWrite', 'db': db_name}])
96
+
97
+
98
+ def user_uri(admin_uri, db_name, user, password):
99
+ host = (
100
+ admin_uri.split('@', 1)[1].split('/', 1)[0]
101
+ if '@' in admin_uri
102
+ else admin_uri.split('//', 1)[1].split('/', 1)[0]
103
+ )
104
+ return f'mongodb://{user}:{password}@{host}/{db_name}?authSource={db_name}'
105
+
106
+
107
+ class World:
108
+ """Real remotes in moto under one key prefix, plus their local files under tmp."""
109
+
110
+ def __init__(self, moto_url, tmp, b3):
111
+ self.url = moto_url
112
+ self.tmp = tmp
113
+ self.b3 = b3
114
+ self.bucket = public_bucket(b3)
115
+ self.prefix = uuid.uuid4().hex[:12]
116
+
117
+ def key(self, name):
118
+ return f'{self.prefix}/{name}'
119
+
120
+ def db_url(self, name):
121
+ return f'{self.url}/{self.bucket}/{self.key(name)}'
122
+
123
+ def conn(self, name, *, with_db_url=True):
124
+ return ebooklet.S3Connection(
125
+ access_key_id='test',
126
+ access_key='test',
127
+ db_key=self.key(name),
128
+ bucket=self.bucket,
129
+ endpoint_url=self.url,
130
+ db_url=self.db_url(name) if with_db_url else None,
131
+ )
132
+
133
+ @property
134
+ def catalogue_url(self):
135
+ return self.db_url('catalogue')
136
+
137
+ def push(self, name, set_items=None, delete=(), *, new=False):
138
+ flag = 'n' if new else 'w'
139
+ kw = {'group_bytes': None} if new else {}
140
+ with ebooklet.open_ebooklet(self.conn(name), self.tmp / f'{name}.blt', flag=flag, **kw) as eb:
141
+ for k, v in (set_items or {}).items():
142
+ eb[k] = v
143
+ for k in delete:
144
+ del eb[k]
145
+ assert eb.changes().push().updated
146
+
147
+ def member(self, name, n=3):
148
+ """A new member remote with n small values."""
149
+ self.push(name, {f'k{i}': f'{name}-{i}'.encode() * 4 for i in range(n)}, new=True)
150
+
151
+ def publish(self, entries, *, new=False, extra_meta=None, with_db_url=True):
152
+ """Upsert catalogue entries {dataset_version_id: member name}."""
153
+ flag = 'n' if new or not (self.tmp / 'catalogue.rcg').exists() else 'w'
154
+ kw = {'group_bytes': None} if flag == 'n' else {}
155
+ with ebooklet.open_rcg(self.conn('catalogue'), self.tmp / 'catalogue.rcg', flag=flag, **kw) as rcg:
156
+ for dvid, name in entries.items():
157
+ meta = {'dataset_id': 'd' + dvid[1:], 'dataset_version_id': dvid, **(extra_meta or {})}
158
+ rcg.add(self.conn(name, with_db_url=with_db_url), key=dvid, user_meta=meta)
159
+ assert rcg.changes().push().updated
160
+
161
+ def deregister(self, *dvids):
162
+ with ebooklet.open_rcg(self.conn('catalogue'), self.tmp / 'catalogue.rcg', flag='w') as rcg:
163
+ for dvid in dvids:
164
+ del rcg[dvid]
165
+ assert rcg.changes().push().updated
166
+
167
+ def objects(self, name):
168
+ """Every object of one remote: its db object and its value objects."""
169
+ out = []
170
+ for page in self.b3.get_paginator('list_objects_v2').paginate(Bucket=self.bucket, Prefix=self.key(name)):
171
+ out += [
172
+ o['Key']
173
+ for o in page.get('Contents', [])
174
+ if o['Key'] == self.key(name) or o['Key'].startswith(self.key(name) + '/')
175
+ ]
176
+ return out
177
+
178
+ def copy_remote(self, src, dst):
179
+ """A server-side copy of a remote, so the copy has the same uuid and timestamp."""
180
+ for k in self.objects(src):
181
+ self.b3.copy_object(
182
+ Bucket=self.bucket,
183
+ Key=self.key(dst) + k[len(self.key(src)) :],
184
+ CopySource={'Bucket': self.bucket, 'Key': k},
185
+ MetadataDirective='COPY',
186
+ )
187
+
188
+ def delete_remote_objects(self, name):
189
+ for k in self.objects(name):
190
+ self.b3.delete_object(Bucket=self.bucket, Key=k)
191
+
192
+ def save_db_object(self, name):
193
+ obj = self.b3.get_object(Bucket=self.bucket, Key=self.key(name))
194
+ return obj['Body'].read(), obj['Metadata']
195
+
196
+ def restore_db_object(self, name, saved):
197
+ body, meta = saved
198
+ self.b3.put_object(Bucket=self.bucket, Key=self.key(name), Body=body, Metadata=meta)
199
+
200
+ def remote_keys(self, name):
201
+ with ebooklet.open_ebooklet(self.conn(name), self.tmp / f'{name}.read.blt', flag='r') as eb:
202
+ return set(eb.keys())
203
+
204
+
205
+ def config_for(world, **kw):
206
+ base = dict(mongo_uri='unused-in-process', catalogue_url=world.catalogue_url, read_timeout=5, retries=0)
207
+ return Config(**{**base, **kw})
208
+
209
+
210
+ # ── fixtures (imported by conftest.py) ─────────────────────────────────────────────────────────
211
+
212
+
213
+ @pytest.fixture(autouse=True)
214
+ def fast_lock_settle(monkeypatch):
215
+ real = s3func.locking.sleep
216
+ monkeypatch.setattr(s3func.locking, 'sleep', lambda s: real(min(s, 0.01)))
217
+
218
+
219
+ @pytest.fixture(scope='session')
220
+ def moto_url():
221
+ port = free_port()
222
+ server = ThreadedMotoServer(ip_address='127.0.0.1', port=port, verbose=False)
223
+ server.start()
224
+ url = f'http://127.0.0.1:{port}'
225
+ public_bucket(s3_client(url), BUCKET) # the default bucket; each world makes its own (public_bucket)
226
+ yield url
227
+ server.stop()
228
+
229
+
230
+ @pytest.fixture
231
+ def world(moto_url, tmp_path):
232
+ return World(moto_url, tmp_path, s3_client(moto_url))
233
+
234
+
235
+ @pytest.fixture(scope='session')
236
+ def mongo_admin_uri():
237
+ uri = os.environ.get(MONGO_ENV)
238
+ if not uri:
239
+ if os.environ.get('CI'):
240
+ pytest.fail(f'{MONGO_ENV} is not set under CI: the MongoDB tests must run there.')
241
+ pytest.skip(f'{MONGO_ENV} is not set (an auth-enabled MongoDB, as a user that can create users).')
242
+ return uri
243
+
244
+
245
+ @pytest.fixture(scope='session')
246
+ def mongo_admin(mongo_admin_uri):
247
+ client = pymongo.MongoClient(mongo_admin_uri, tz_aware=True, serverSelectionTimeoutMS=5000)
248
+ client.admin.command('ping')
249
+ yield client
250
+ client.close()
251
+
252
+
253
+ def _scoped_db(mongo_admin, mongo_admin_uri, production_role):
254
+ name = f'envlib_api_test_{uuid.uuid4().hex[:10]}'
255
+ password = uuid.uuid4().hex
256
+ create_user(mongo_admin, name, 'refresher', password, production_role=production_role)
257
+ client = pymongo.MongoClient(user_uri(mongo_admin_uri, name, 'refresher', password), tz_aware=True)
258
+ return name, client, user_uri(mongo_admin_uri, name, 'refresher', password)
259
+
260
+
261
+ def _drop(mongo_admin, name, client):
262
+ client.close()
263
+ mongo_admin.drop_database(name)
264
+ mongo_admin[name].command('dropAllUsersFromDatabase')
265
+ mongo_admin[name].command('dropAllRolesFromDatabase')
266
+
267
+
268
+ @pytest.fixture
269
+ def db_and_uri(mongo_admin, mongo_admin_uri):
270
+ """A fresh database, reached as the refresher user with the production role."""
271
+ name, client, uri = _scoped_db(mongo_admin, mongo_admin_uri, production_role=True)
272
+ yield client[name], uri
273
+ _drop(mongo_admin, name, client)
274
+
275
+
276
+ @pytest.fixture
277
+ def db(db_and_uri):
278
+ return db_and_uri[0]
279
+
280
+
281
+ @pytest.fixture
282
+ def readwrite_db(mongo_admin, mongo_admin_uri):
283
+ """A fresh database, reached as a user with plain readWrite (the role the review found too weak)."""
284
+ name, client, _ = _scoped_db(mongo_admin, mongo_admin_uri, production_role=False)
285
+ yield client[name]
286
+ _drop(mongo_admin, name, client)
287
+
288
+
289
+ # ── crash injection ────────────────────────────────────────────────────────────────────────────
290
+
291
+
292
+ class Crash(Exception):
293
+ """Raised by CrashAfter right after the write it wraps."""
294
+
295
+
296
+ class CrashAfter:
297
+ """A pymongo Database proxy: the first `collection.method(...)` call runs, then raises Crash."""
298
+
299
+ def __init__(self, db, collection, method):
300
+ self._db, self._collection, self._method = db, collection, method
301
+
302
+ def __getitem__(self, name):
303
+ coll = self._db[name]
304
+ return _CrashCollection(coll, self._method) if name == self._collection else coll
305
+
306
+
307
+ class _CrashCollection:
308
+ def __init__(self, coll, method):
309
+ self._coll, self._method = coll, method
310
+
311
+ def __getattr__(self, name):
312
+ attr = getattr(self._coll, name)
313
+ if name != self._method:
314
+ return attr
315
+
316
+ def crash_after(*args, **kwargs):
317
+ attr(*args, **kwargs)
318
+ raise Crash(f'after {self._coll.name}.{name}')
319
+
320
+ return crash_after
@@ -0,0 +1,325 @@
1
+ """
2
+ Alerting, the retire guards, re-points and listing isolation. Most cases here come from code review
3
+ `edr-worker-code-2` (planning/edr-worker-code-2-review-synthesis.md). They run several cycles,
4
+ because the defects showed only from the second cycle on.
5
+ """
6
+
7
+ import datetime
8
+
9
+ import ebooklet
10
+ import pytest
11
+ from ebooklet.mongo import DATASETS, ENTRIES
12
+
13
+ from envlib_api import mirror
14
+ from envlib_api.cli import status_rows
15
+ from envlib_api.tests.test_refresher import A, B, C, D, make, mirrored_keys, store, two
16
+
17
+ E = 'e' * 24
18
+
19
+
20
+ # ── dedup: alerted once until the condition clears (finding 1) ─────────────────────────────────
21
+
22
+
23
+ def test_a_blocked_retire_alerts_once_and_again_only_after_it_cleared(world, db, tmp_path):
24
+ two(world)
25
+ r, rec = make(world, db, tmp_path)
26
+ r.cycle()
27
+ world.deregister(A, B) # empty catalogue: blocked on every cycle
28
+ for _ in range(4):
29
+ assert r.cycle()['blocked']
30
+ assert len(rec.alerts) == 1, f'one blocked condition alerted {len(rec.alerts)} times'
31
+ world.publish({A: 'm1', B: 'm2'})
32
+ assert r.cycle()['blocked'] is None
33
+ world.deregister(A, B)
34
+ r.cycle()
35
+ assert len(rec.alerts) == 2, 'a new blocked episode alerts again'
36
+
37
+
38
+ def test_a_value_failure_alerts_once_across_cycles(world, db, tmp_path):
39
+ two(world)
40
+ r, rec = make(world, db, tmp_path, value_failure_alert_cycles=2)
41
+ r.cycle()
42
+ world.publish({A: 'm1'}, with_db_url=False)
43
+ for _ in range(5):
44
+ assert A in r.cycle()['value_failures']
45
+ assert len(rec.alerts) == 1, f'one unusable value alerted {len(rec.alerts)} times'
46
+
47
+
48
+ def test_the_value_failure_count_restarts_after_the_entry_is_listed(world, db, tmp_path):
49
+ two(world)
50
+ r, rec = make(world, db, tmp_path, value_failure_alert_cycles=2)
51
+ r.cycle()
52
+ world.publish({A: 'm1'}, with_db_url=False)
53
+ r.cycle() # 1 failure
54
+ world.publish({A: 'm1'}, extra_meta={'fixed': 1})
55
+ assert A in r.cycle()['listed']
56
+ world.publish({A: 'm1'}, with_db_url=False)
57
+ r.cycle() # 1 failure again, not 2
58
+ assert rec.alerts == [], 'the count must restart once the entry was listed'
59
+
60
+
61
+ # ── what "ok" means (finding 2) ────────────────────────────────────────────────────────────────
62
+
63
+
64
+ def test_every_member_missing_is_an_error_check_in_and_leaves_the_heartbeat(world, db, tmp_path):
65
+ two(world)
66
+ r, rec = make(world, db, tmp_path)
67
+ r.cycle()
68
+ (tmp_path / 'heartbeat').unlink()
69
+ world.delete_remote_objects('m1')
70
+ world.delete_remote_objects('m2')
71
+ for _ in range(2):
72
+ s = r.cycle()
73
+ assert not s['ok'] and s['failed'] == 0
74
+ assert rec.checkins == ['ok', 'error', 'error']
75
+ assert not (tmp_path / 'heartbeat').exists(), 'a missing remote is not progress'
76
+
77
+
78
+ def test_a_sync_that_raises_every_cycle_is_an_error_check_in(world, db, tmp_path, monkeypatch):
79
+ two(world)
80
+ r, rec = make(world, db, tmp_path)
81
+ r.cycle()
82
+
83
+ def broken(*args, **kwargs):
84
+ raise RuntimeError('simulated: a bug in sync')
85
+
86
+ monkeypatch.setattr(mirror, 'sync', broken)
87
+ for _ in range(3):
88
+ assert not r.cycle()['ok']
89
+ assert rec.checkins == ['ok', 'error', 'error', 'error'] and len(rec.reports) == 1
90
+
91
+
92
+ # ── retires (findings 3 and 4) ─────────────────────────────────────────────────────────────────
93
+
94
+
95
+ def test_every_retire_alerts(world, db, tmp_path):
96
+ two(world)
97
+ r, rec = make(world, db, tmp_path)
98
+ r.cycle()
99
+ world.deregister(A)
100
+ assert r.cycle()['retired'] == [A]
101
+ world.deregister(B)
102
+ world.member('m3')
103
+ world.publish({C: 'm3'})
104
+ assert r.cycle()['retired'] == [B]
105
+ assert len(rec.alerts) == 2 and all('retired' in a for a in rec.alerts)
106
+
107
+
108
+ def test_the_cap_allows_exactly_max_retires(world, db, tmp_path):
109
+ for name in ('m1', 'm2', 'm3'):
110
+ world.member(name, n=1)
111
+ world.publish({A: 'm1', B: 'm2', C: 'm3'})
112
+ r, _ = make(world, db, tmp_path)
113
+ r.cycle()
114
+ world.deregister(B, C) # exactly the cap of 2
115
+ assert r.cycle()['retired'] == [B, C]
116
+
117
+
118
+ def _four(world, r):
119
+ for name in ('m1', 'm2', 'm3', 'm4', 'm5'):
120
+ world.member(name, n=1)
121
+ world.publish({A: 'm1', B: 'm2', C: 'm3', D: 'm4', E: 'm5'})
122
+ r.cycle()
123
+
124
+
125
+ def test_allow_retires_is_consumed_by_one_retire_pass(world, db, tmp_path):
126
+ r, _ = make(world, db, tmp_path)
127
+ _four(world, r)
128
+ world.deregister(B, C, D)
129
+ assert r.cycle()['blocked']
130
+ mirror.allow_retires(db)
131
+ assert r.cycle()['retired'] == [B, C, D]
132
+ world.member('m6', n=1)
133
+ world.member('m7', n=1)
134
+ world.member('m8', n=1)
135
+ world.publish({B: 'm6', C: 'm7', D: 'm8'})
136
+ r.cycle()
137
+ world.deregister(B, C, D)
138
+ s = r.cycle()
139
+ assert s['retired'] == [] and '3 retires' in s['blocked'], 'a second bulk removal needs a second allow'
140
+
141
+
142
+ def test_allow_retires_expires(world, db, tmp_path):
143
+ r, _ = make(world, db, tmp_path)
144
+ _four(world, r)
145
+ mirror.allow_retires(db)
146
+ past = datetime.datetime.now(datetime.UTC) - datetime.timedelta(seconds=1)
147
+ db[mirror.STATE].update_one({'_id': mirror.STATE_ID}, {'$set': {'allow_bulk_retire_until': past}})
148
+ world.deregister(B, C, D)
149
+ assert r.cycle()['retired'] == []
150
+
151
+
152
+ def test_allow_retires_lifts_the_empty_guard_once(world, db, tmp_path):
153
+ two(world)
154
+ r, _ = make(world, db, tmp_path)
155
+ r.cycle()
156
+ world.deregister(A, B)
157
+ assert 'empty' in r.cycle()['blocked']
158
+ mirror.allow_retires(db)
159
+ assert r.cycle()['retired'] == [A, B]
160
+
161
+
162
+ def test_allow_retires_refuses_without_a_mirrored_catalogue(db):
163
+ with pytest.raises(ValueError, match='not applied'):
164
+ mirror.allow_retires(db)
165
+
166
+
167
+ def test_non_hex_catalogue_keys_are_never_mirrored(world, db, tmp_path):
168
+ world.member('m1')
169
+ world.member('m2')
170
+ world.publish({A: 'm1'})
171
+ with ebooklet.open_rcg(world.conn('catalogue'), world.tmp / 'catalogue.rcg', flag='w') as rcg:
172
+ rcg.add(
173
+ world.conn('m2'), key='not-a-version', user_meta={'dataset_id': 'x', 'dataset_version_id': 'not-a-version'}
174
+ )
175
+ assert rcg.changes().push().updated
176
+ r, _ = make(world, db, tmp_path)
177
+ s = r.cycle()
178
+ assert s['listed'] == [A] and db[DATASETS].find_one({'_id': 'not-a-version'}) is None
179
+
180
+
181
+ # ── re-points (finding 5) ──────────────────────────────────────────────────────────────────────
182
+
183
+
184
+ def test_a_repoint_to_a_remote_that_does_not_answer_keeps_serving_the_old_one(world, db, tmp_path):
185
+ world.member('m1')
186
+ world.publish({A: 'm1'})
187
+ r, rec = make(world, db, tmp_path)
188
+ r.cycle()
189
+ applied = db[DATASETS].find_one({'_id': A})['applied']
190
+ world.copy_remote('m1', 'moved') # the publisher HEADs the member, so it exists at publish time...
191
+ world.publish({A: 'moved'})
192
+ world.delete_remote_objects('moved') # ...and is gone when the refresher looks
193
+ for _ in range(2):
194
+ s = r.cycle()
195
+ assert s['repoint_failed'] == [A] and s['repointed'] == []
196
+ assert s['refreshed'][A] is not None and s['refreshed'][A]['status'] == 'nochange', 'the old remote is polled'
197
+ doc = db[DATASETS].find_one({'_id': A})
198
+ assert doc['applied'] == applied and doc['db_url'] == world.db_url('m1')
199
+ assert db[mirror.CATALOGUE].find_one({'_id': A})['remote_conn']['db_url'] == world.db_url('m1')
200
+ assert store(db, world, A, 'm1').get('k1') == b'm1-1' * 4, 'still served from the old remote'
201
+ assert sum('not re-pointing' in a for a in rec.alerts) == 1
202
+ world.copy_remote('m1', 'moved') # the new remote appears: the next cycle follows it
203
+ assert r.cycle()['repointed'] == [A]
204
+ assert db[DATASETS].find_one({'_id': A})['db_url'] == world.db_url('moved')
205
+
206
+
207
+ def test_a_repoint_whose_refresh_fails_restores_the_old_applied_pair(world, db, tmp_path):
208
+ world.member('m1')
209
+ world.publish({A: 'm1'})
210
+ new = world.db_url('moved')
211
+
212
+ def connect(url):
213
+ if url == new:
214
+ raise OSError('simulated: the new host refuses the refresh')
215
+ return ebooklet.S3Connection(db_url=url, read_timeout=5, retries=0)
216
+
217
+ r, _ = make(world, db, tmp_path, connect=connect)
218
+ r.cycle()
219
+ applied = db[DATASETS].find_one({'_id': A})['applied']
220
+ world.copy_remote('m1', 'moved')
221
+ world.publish({A: 'moved'})
222
+ r.probe = lambda url: True # the probe passes, then the refresh itself fails
223
+ s = r.cycle()
224
+ assert s['repoint_failed'] == [A] and s['repointed'] == []
225
+ doc = db[DATASETS].find_one({'_id': A})
226
+ assert doc['applied'] == applied and doc['db_url'] == world.db_url('m1')
227
+ assert store(db, world, A, 'm1').get('k1') == b'm1-1' * 4
228
+
229
+
230
+ def test_a_recreated_catalogue_does_not_repoint_until_acknowledged(world, db, tmp_path):
231
+ two(world)
232
+ r, _ = make(world, db, tmp_path)
233
+ r.cycle()
234
+ world.copy_remote('m1', 'moved')
235
+ world.delete_remote_objects('catalogue')
236
+ world.publish({A: 'moved'}, new=True) # recreated, B dropped, A moved
237
+ s = r.cycle()
238
+ assert 'recreated' in s['blocked'] and s['repoint_failed'] == [A]
239
+ assert db[DATASETS].find_one({'_id': A})['db_url'] == world.db_url('m1')
240
+ mirror.allow_retires(db)
241
+ s = r.cycle()
242
+ assert s['retired'] == [B] and s['repointed'] == [A]
243
+
244
+
245
+ # ── listing isolation (finding 6) ──────────────────────────────────────────────────────────────
246
+
247
+
248
+ def test_one_value_mongodb_refuses_does_not_stop_the_other_listings(world, db, tmp_path):
249
+ world.member('m1')
250
+ world.publish({A: 'm1'})
251
+ r, _ = make(world, db, tmp_path)
252
+ r.cycle()
253
+ world.member('m3')
254
+ world.publish({A: 'm1', C: 'm3'}, extra_meta={'big': 2**63}) # A: an int BSON cannot hold
255
+ world.publish({C: 'm3'}, extra_meta={'note': 'fine'})
256
+ s = r.cycle()
257
+ assert C in s['listed'] and A in s['value_failures']
258
+ assert mirrored_keys(db, C) == world.remote_keys('m3')
259
+
260
+
261
+ # ── stale_get and interleaved results are not listed ───────────────────────────────────────────
262
+
263
+
264
+ def test_a_new_entry_whose_refresh_is_inconclusive_is_not_listed(world, db, tmp_path):
265
+ world.member('m1')
266
+ world.publish({A: 'm1'})
267
+ r, _ = make(world, db, tmp_path)
268
+ assert r.refresh_one(mirror.CATALOGUE_ID, world.catalogue_url)['status'] == 'applied'
269
+ for status in ('stale_get', 'interleaved'):
270
+
271
+ def inconclusive(dvid, url, status=status):
272
+ return {'status': status, 'upserted': 0, 'removed': 0, 'unmanifested': 0, 'applied': None}
273
+
274
+ out = mirror.sync(db, True, inconclusive, r._reader(world.catalogue_url), max_retires=2)
275
+ assert out['listed'] == [] and db[mirror.CATALOGUE].find_one({'_id': A}) is None
276
+
277
+
278
+ # ── polling order ──────────────────────────────────────────────────────────────────────────────
279
+
280
+
281
+ def test_polling_starts_with_the_oldest_check(db):
282
+ now = datetime.datetime.now(datetime.UTC)
283
+ for dvid, age in ((A, 10), (B, 500), (C, None)):
284
+ doc = {'_id': dvid, 'db_url': 'u', 'rev': 1, 'missing': False}
285
+ if age is not None:
286
+ doc['checked_at'] = now - datetime.timedelta(seconds=age)
287
+ db[DATASETS].insert_one(doc)
288
+ order = [d for d, _ in mirror.poll_order(db, {A: 'ua', B: 'ub', C: 'uc', D: 'ud'})]
289
+ assert order[:2] == sorted([C, D]) and order[2:] == [B, A], order
290
+
291
+
292
+ def test_status_rows_include_catalogue_entries_never_mirrored(db):
293
+ db[ENTRIES].insert_one(
294
+ {'_id': f'catalogue|{A}', 'd': 'catalogue', 'k': A, 'ts': 1, 'g': None, 'n': None, 'o': 0, 'l': 1, 'u': 'u'}
295
+ )
296
+ rows = {r['id']: r['flags'] for r in status_rows(db, poll_seconds=60)}
297
+ assert rows == {A: ['never mirrored']}
298
+
299
+
300
+ @pytest.mark.parametrize('state', [{'missing': True}, {'applying': True}, {'applied': None}])
301
+ def test_allow_retires_refuses_while_the_catalogue_mirror_is_not_applied(world, db, tmp_path, state):
302
+ two(world)
303
+ r, _ = make(world, db, tmp_path)
304
+ r.cycle()
305
+ db[DATASETS].update_one({'_id': mirror.CATALOGUE_ID}, {'$set': state})
306
+ with pytest.raises(ValueError, match='not applied'):
307
+ mirror.allow_retires(db)
308
+
309
+
310
+ def test_a_cycle_polls_the_oldest_check_first(world, db, tmp_path):
311
+ two(world)
312
+ r, _ = make(world, db, tmp_path)
313
+ r.cycle()
314
+ old = datetime.datetime.now(datetime.UTC) - datetime.timedelta(hours=1)
315
+ db[DATASETS].update_one({'_id': B}, {'$set': {'checked_at': old}}) # B is the oldest, though it sorts last
316
+ order = []
317
+ orig = r.refresh_one
318
+
319
+ def spy(dvid, url, **kw):
320
+ order.append(dvid)
321
+ return orig(dvid, url, **kw)
322
+
323
+ r.refresh_one = spy
324
+ r.cycle()
325
+ assert order == [mirror.CATALOGUE_ID, B, A], order