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/mirror.py ADDED
@@ -0,0 +1,353 @@
1
+ """
2
+ The catalogue mirror: keeps MongoDB's set of mirrored datasets equal to the envlib catalogue's.
3
+
4
+ The catalogue is an ebooklet RemoteConnGroup (RCG). The refresher mirrors it with
5
+ `ebooklet.mongo.refresh()` under the dataset id CATALOGUE_ID, exactly like a dataset. Then
6
+ sync() compares it with what MongoDB mirrors:
7
+
8
+ - **Membership** is the set of 24-hex keys in the catalogue's mirrored index. It needs no values, so
9
+ a value that cannot be read never makes an entry look removed.
10
+ - **A removed key** is retired, but only when every guard passes: this cycle's catalogue refresh
11
+ succeeded, the catalogue is non-empty, its uuid is the acknowledged one (a recreated catalogue
12
+ is held for a person to check), and no more than `max_retires` are due at once.
13
+ `envlib-api allow-retires` acknowledges the current uuid and allows one retire pass past the cap
14
+ and the empty guard, within an hour. The caller alerts on every retire.
15
+ - A retire deletes the catalogue document, TOMBSTONES the `datasets` document (`rev` bumped,
16
+ `applied` cleared, `missing` and `retired` set), and deletes the dataset's entries.
17
+ - The `datasets` document is never deleted. A recreated document would restart `rev`, which is
18
+ the ABA that plan review `edr-worker-plan-2` found (ebooklet 0.13.1's incarnation token also
19
+ catches it).
20
+ - Leftover entries of retired datasets are deleted on every cycle, so a crash mid-retire
21
+ converges.
22
+ - **A new key, or a key whose entry changed** (its index timestamp differs from the catalogue
23
+ document's):
24
+ 1. read its value;
25
+ 2. clear `retired` if it was retired. If its `db_url` changed (a re-point), first check that the
26
+ new remote answers and that the catalogue's uuid is acknowledged; otherwise keep serving and
27
+ polling the old remote. Then clear `applied`, so the refresh re-diffs in place and bumps `rev`;
28
+ if that refresh fails before its claim, the old `applied` pair is put back;
29
+ 3. refresh the member;
30
+ 4. only then upsert its catalogue document.
31
+
32
+ So a document is never listed before its mirror exists, unless the remote is missing.
33
+ - **A value that fails** (an unreadable value, an undecodable one, one with no `db_url`, or one
34
+ MongoDB refuses to store) keeps its existing document and is retried next cycle. It is counted,
35
+ so the caller can alert, and it never stops the other keys.
36
+
37
+ Single writer: exactly one refresher may run (see ebooklet's docs/ops.md). Nothing here guards
38
+ against a second one.
39
+ """
40
+
41
+ import datetime
42
+ import logging
43
+ import re
44
+
45
+ import orjson
46
+ import urllib3
47
+ from bson.errors import BSONError
48
+ from ebooklet.errors import RemoteIntegrityError, RemoteMissingError, StaleIndexError
49
+ from ebooklet.mongo import DATASETS, ENTRIES, MongoStore
50
+ from pymongo.errors import CollectionInvalid, PyMongoError
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+ CATALOGUE_ID = 'catalogue' # the RCG's dataset id in `datasets` and `entries` (not 24 hex: no clash)
55
+ CATALOGUE = 'catalogue' # the collection of catalogue entries, one per dataset_version_id
56
+ STATE = 'state' # the refresher's own small state (the acknowledged catalogue uuid)
57
+ STATE_ID = 'refresher'
58
+ HEX24 = re.compile(r'[0-9a-f]{24}')
59
+ BULK_RETIRE_WINDOW = datetime.timedelta(hours=1)
60
+
61
+ _REMOTE_CONN_FIELDS = ('db_url', 'db_key', 'bucket', 'endpoint_url') # never credentials
62
+
63
+ CATALOGUE_VALIDATOR = {
64
+ '$jsonSchema': {
65
+ 'bsonType': 'object',
66
+ 'required': ['_id', 'dataset_id', 'ts', 'user_meta', 'remote_conn'],
67
+ 'properties': {
68
+ '_id': {'bsonType': 'string', 'pattern': '^[0-9a-f]{24}$'},
69
+ 'dataset_id': {'bsonType': 'string'},
70
+ 'ts': {'bsonType': ['int', 'long']},
71
+ 'user_meta': {'bsonType': 'object'},
72
+ 'remote_conn': {
73
+ 'bsonType': 'object',
74
+ 'required': ['db_url'],
75
+ 'properties': {'db_url': {'bsonType': 'string'}},
76
+ },
77
+ 'type': {'bsonType': ['string', 'null']},
78
+ },
79
+ }
80
+ }
81
+ STATE_VALIDATOR = {
82
+ '$jsonSchema': {
83
+ 'bsonType': 'object',
84
+ 'properties': {
85
+ 'catalogue_uuid': {'bsonType': ['string', 'null']},
86
+ 'allow_bulk_retire_until': {'bsonType': ['date', 'null']},
87
+ },
88
+ }
89
+ }
90
+
91
+
92
+ def ensure_catalogue_schema(db):
93
+ """Create (or update the validators of) the `catalogue` and `state` collections. Idempotent."""
94
+ for name, validator in ((CATALOGUE, CATALOGUE_VALIDATOR), (STATE, STATE_VALIDATOR)):
95
+ try:
96
+ db.create_collection(
97
+ name, validator=validator, storageEngine={'wiredTiger': {'configString': 'block_compressor=zstd'}}
98
+ )
99
+ except CollectionInvalid:
100
+ db.command('collMod', name, validator=validator, validationLevel='strict')
101
+ db[CATALOGUE].create_index([('dataset_id', 1)], name='dataset_id_1')
102
+
103
+
104
+ def membership(db):
105
+ """
106
+ ({dataset_version_id: index ts}, catalogue uuid) from the mirrored catalogue index, or
107
+ (None, None) while that mirror is not complete (never applied, mid-apply, or missing).
108
+ """
109
+ doc = db[DATASETS].find_one({'_id': CATALOGUE_ID})
110
+ if doc is None or doc.get('applied') is None or doc.get('applying') or doc.get('missing'):
111
+ return None, None
112
+ keys = {
113
+ e['k']: e['ts'] for e in db[ENTRIES].find({'d': CATALOGUE_ID}, {'k': 1, 'ts': 1}) if HEX24.fullmatch(e['k'])
114
+ }
115
+ return keys, doc['uuid']
116
+
117
+
118
+ def current(db):
119
+ """Every dataset the mirror holds: non-retired `datasets` documents, plus catalogue documents."""
120
+ held = {d['_id'] for d in db[DATASETS].find({'retired': {'$ne': True}}, {'_id': 1})}
121
+ held.discard(CATALOGUE_ID)
122
+ return held | {d['_id'] for d in db[CATALOGUE].find({}, {'_id': 1})}
123
+
124
+
125
+ def members(db):
126
+ """{dataset_version_id: db_url} of every listed catalogue document: the datasets to poll."""
127
+ return {d['_id']: d['remote_conn']['db_url'] for d in db[CATALOGUE].find({}, {'remote_conn.db_url': 1})}
128
+
129
+
130
+ def parse_entry(key, raw):
131
+ """A catalogue document from one RCG value. Raises ValueError on anything unusable."""
132
+ if raw is None:
133
+ raise ValueError('the entry has no value')
134
+ try:
135
+ entry = orjson.loads(raw)
136
+ except orjson.JSONDecodeError as err:
137
+ raise ValueError(f'the value is not JSON ({err})') from err
138
+ um = entry.get('user_meta') if isinstance(entry, dict) else None
139
+ rc = entry.get('remote_conn') if isinstance(entry, dict) else None
140
+ if not isinstance(um, dict) or not isinstance(rc, dict):
141
+ raise ValueError('the value has no user_meta or remote_conn object')
142
+ url = rc.get('db_url')
143
+ if not isinstance(url, str) or not url.startswith(('https://', 'http://')):
144
+ raise ValueError(f'the value has no usable db_url ({url!r})')
145
+ if um.get('dataset_version_id') != key:
146
+ raise ValueError(f"user_meta.dataset_version_id {um.get('dataset_version_id')!r} differs from the key")
147
+ if not isinstance(um.get('dataset_id'), str):
148
+ raise ValueError('user_meta has no dataset_id')
149
+ return {
150
+ '_id': key,
151
+ 'dataset_id': um['dataset_id'],
152
+ 'user_meta': um,
153
+ 'remote_conn': {f: rc.get(f) for f in _REMOTE_CONN_FIELDS},
154
+ 'type': entry.get('type'),
155
+ }
156
+
157
+
158
+ def retire(db, dvid):
159
+ """Retire one dataset: catalogue document, then the `datasets` tombstone, then its entries."""
160
+ db[CATALOGUE].delete_one({'_id': dvid})
161
+ db[DATASETS].update_one(
162
+ {'_id': dvid},
163
+ {'$inc': {'rev': 1}, '$set': {'applied': None, 'missing': True, 'retired': True, 'applying': False}},
164
+ )
165
+ db[ENTRIES].delete_many({'d': dvid})
166
+
167
+
168
+ def reap_retired_entries(db):
169
+ """Delete entries left behind by a retire that crashed after its tombstone. Returns the count."""
170
+ retired = {d['_id'] for d in db[DATASETS].find({'retired': True}, {'_id': 1})}
171
+ if not retired:
172
+ return 0
173
+ n = 0
174
+ for d in retired & set(db[ENTRIES].distinct('d')):
175
+ n += db[ENTRIES].delete_many({'d': d}).deleted_count
176
+ return n
177
+
178
+
179
+ def allow_retires(db):
180
+ """
181
+ What `envlib-api allow-retires` does, after a person has checked a blocked retire. It
182
+ acknowledges the current catalogue uuid, and allows ONE retire pass that ignores the cap and the
183
+ empty-catalogue guard. That pass must happen within the next hour; the first retire consumes it.
184
+ It refuses while the catalogue mirror is not applied (there is nothing checked to acknowledge).
185
+ """
186
+ cat = db[DATASETS].find_one({'_id': CATALOGUE_ID}, {'uuid': 1, 'applied': 1, 'applying': 1, 'missing': 1})
187
+ if cat is None or cat.get('applied') is None or cat.get('applying') or cat.get('missing'):
188
+ raise ValueError('the catalogue mirror is not applied, so there is no catalogue to acknowledge')
189
+ until = datetime.datetime.now(datetime.UTC) + BULK_RETIRE_WINDOW
190
+ db[STATE].update_one(
191
+ {'_id': STATE_ID},
192
+ {'$set': {'catalogue_uuid': cat['uuid'], 'allow_bulk_retire_until': until}},
193
+ upsert=True,
194
+ )
195
+ return cat['uuid'], until
196
+
197
+
198
+ def poll_order(db, listed):
199
+ """
200
+ The listed datasets ({dvid: db_url}) ordered by their last successful check, oldest (or never)
201
+ first. A cycle cut short by a stalled host, and the restart that follows, then reach next the
202
+ datasets the previous cycle did not.
203
+ """
204
+ checked = {
205
+ d['_id']: d.get('checked_at') for d in db[DATASETS].find({'_id': {'$in': list(listed)}}, {'checked_at': 1})
206
+ }
207
+ epoch = datetime.datetime.min.replace(tzinfo=datetime.UTC)
208
+
209
+ def when(dvid):
210
+ c = checked.get(dvid)
211
+ return epoch if c is None else c.replace(tzinfo=datetime.UTC)
212
+
213
+ return sorted(listed.items(), key=lambda item: (when(item[0]), item[0]))
214
+
215
+
216
+ def empty_sync_result():
217
+ return {
218
+ 'retired': [],
219
+ 'listed': [],
220
+ 'repointed': [],
221
+ 'repoint_failed': {},
222
+ 'refreshed': {},
223
+ 'value_failures': {},
224
+ 'adopted': None,
225
+ 'blocked': None,
226
+ }
227
+
228
+
229
+ _VALUE_ERRORS = (
230
+ ValueError,
231
+ StaleIndexError,
232
+ RemoteIntegrityError,
233
+ RemoteMissingError,
234
+ urllib3.exceptions.HTTPError,
235
+ OSError,
236
+ )
237
+ _LISTING_ERRORS = (PyMongoError, BSONError, OverflowError, ValueError, TypeError)
238
+
239
+
240
+ def sync(db, catalogue_ok, refresh_member, reader, *, max_retires, probe=None):
241
+ """
242
+ Bring the mirror's set of datasets in line with the catalogue (the module docstring has the
243
+ rules). `refresh_member(dvid, db_url)` refreshes one dataset and returns refresh()'s dict, or
244
+ None if it failed (the caller logs and reports that). `reader` is an ebooklet.mongo
245
+ object_reader on the catalogue's db_url. `probe(db_url) -> bool` checks a new remote before a
246
+ re-point (default: always True).
247
+
248
+ Returns empty_sync_result()'s keys: 'retired', 'listed', 'repointed', 'repoint_failed'
249
+ ({dvid: why}), 'refreshed' ({dvid: result or None}), 'value_failures' ({dvid: why}), 'adopted'
250
+ ((old, new) uuid or None) and 'blocked' (why nothing was retired or listed, or None).
251
+ """
252
+ out = empty_sync_result()
253
+ keys, uuid = membership(db)
254
+ if keys is None:
255
+ out['blocked'] = 'the catalogue mirror is not applied (never refreshed, mid-apply, or missing)'
256
+ return out
257
+
258
+ state = db[STATE].find_one({'_id': STATE_ID}) or {}
259
+ acked = state.get('catalogue_uuid')
260
+ if acked is None: # the first complete catalogue mirror is acknowledged as it is
261
+ db[STATE].update_one({'_id': STATE_ID}, {'$set': {'catalogue_uuid': uuid}}, upsert=True)
262
+ acked = uuid
263
+
264
+ removed = sorted(current(db) - set(keys))
265
+ if removed:
266
+ until = state.get('allow_bulk_retire_until')
267
+ allowed = until is not None and until.replace(tzinfo=datetime.UTC) > datetime.datetime.now(datetime.UTC)
268
+ why = None
269
+ if not catalogue_ok:
270
+ why = "this cycle's catalogue refresh failed"
271
+ elif not keys and not allowed:
272
+ why = 'the catalogue is empty'
273
+ elif uuid != acked:
274
+ why = f'the catalogue was recreated (uuid {acked} -> {uuid})'
275
+ elif len(removed) > max_retires and not allowed:
276
+ why = f'{len(removed)} retires are due at once (the cap is {max_retires})'
277
+ if why:
278
+ out['blocked'] = (
279
+ f'not retiring {removed[:5]}{" ..." if len(removed) > 5 else ""}: {why}. Check the catalogue, '
280
+ 'then run `envlib-api allow-retires` if the removal is intended.'
281
+ )
282
+ else:
283
+ for dvid in removed:
284
+ retire(db, dvid)
285
+ out['retired'] = removed
286
+ if allowed: # allow-retires is single-use: this pass consumed it
287
+ db[STATE].update_one({'_id': STATE_ID}, {'$set': {'allow_bulk_retire_until': None}})
288
+ elif uuid != acked and catalogue_ok:
289
+ ## A recreated catalogue that still lists everything mirrored: nothing would be lost, so adopt it
290
+ ## (the caller alerts).
291
+ db[STATE].update_one({'_id': STATE_ID}, {'$set': {'catalogue_uuid': uuid}})
292
+ out['adopted'] = (acked, uuid)
293
+ acked = uuid
294
+ reap_retired_entries(db)
295
+
296
+ listed = {d['_id']: d for d in db[CATALOGUE].find({}, {'ts': 1})}
297
+ todo = [k for k in sorted(keys) if k not in listed or listed[k]['ts'] != keys[k]]
298
+ if not todo:
299
+ return out
300
+ store = MongoStore(db, CATALOGUE_ID, reader) # membership() saw it applied; one writer, so it still is
301
+ docs = {}
302
+ for k in todo:
303
+ try:
304
+ docs[k] = parse_entry(k, store.get(k))
305
+ except _VALUE_ERRORS as err:
306
+ out['value_failures'][k] = f'{type(err).__name__}: {err}'
307
+ try:
308
+ store.verify() # the values and the membership come from one applied commit
309
+ except StaleIndexError:
310
+ out['blocked'] = 'the catalogue changed while its values were read; the next cycle redoes it'
311
+ return out
312
+
313
+ for k, doc in docs.items():
314
+ try:
315
+ _list_one(db, k, doc, keys[k], uuid == acked, refresh_member, probe, out)
316
+ except _LISTING_ERRORS as err:
317
+ out['value_failures'][k] = f'listing failed: {type(err).__name__}: {err}'
318
+ return out
319
+
320
+
321
+ def _list_one(db, k, doc, ts, uuid_acked, refresh_member, probe, out):
322
+ """Mirror one new or changed catalogue entry, then list it (sync's per-key step)."""
323
+ url = doc['remote_conn']['db_url']
324
+ ds = db[DATASETS].find_one({'_id': k}, {'db_url': 1, 'retired': 1, 'applied': 1, 'rev': 1})
325
+ restore = None
326
+ if ds is not None and ds.get('retired'):
327
+ db[DATASETS].update_one({'_id': k}, {'$set': {'retired': False}})
328
+ elif ds is not None and ds.get('db_url') != url:
329
+ if not uuid_acked:
330
+ out['repoint_failed'][k] = 'the catalogue was recreated and is not acknowledged yet'
331
+ return
332
+ if probe is not None and not probe(url):
333
+ out['repoint_failed'][k] = f'the new remote {url} does not answer'
334
+ return
335
+ ## Re-point in place: with `applied` cleared the refresh re-diffs (rewriting nothing when only
336
+ ## the URL moved), records the new db_url and bumps rev. If it fails before its claim, the old
337
+ ## applied pair is put back, so the dataset keeps serving from the old remote.
338
+ restore = (ds.get('applied'), ds.get('rev'))
339
+ db[DATASETS].update_one({'_id': k}, {'$set': {'applied': None}})
340
+ out['repointed'].append(k)
341
+ res = refresh_member(k, url)
342
+ out['refreshed'][k] = res
343
+ if res is None and restore is not None:
344
+ db[DATASETS].update_one(
345
+ {'_id': k, 'rev': restore[1], 'applied': None, 'applying': {'$ne': True}},
346
+ {'$set': {'applied': restore[0]}},
347
+ )
348
+ out['repointed'].remove(k)
349
+ out['repoint_failed'][k] = f'the refresh from the new remote {url} failed'
350
+ return
351
+ if res is not None and res['status'] in ('applied', 'nochange', 'missing'):
352
+ db[CATALOGUE].replace_one({'_id': k}, {**doc, 'ts': ts}, upsert=True)
353
+ out['listed'].append(k)
@@ -0,0 +1,265 @@
1
+ """
2
+ The refresher: one long-running process that keeps MongoDB's mirror of the envlib catalogue and of
3
+ every catalogued dataset's index up to date (`ebooklet.mongo.refresh`). The API (plan 3) reads only
4
+ MongoDB.
5
+
6
+ Each cycle, every `poll_seconds`:
7
+ 1. refresh the catalogue (an ebooklet RemoteConnGroup), like any dataset;
8
+ 2. sync the set of mirrored datasets with it (mirror.sync: guarded retires, new and changed
9
+ entries);
10
+ 3. refresh every listed dataset not already refreshed in step 2, oldest check first;
11
+ 4. send a Sentry cron check-in: "ok" when the catalogue refresh and the sync succeeded and at
12
+ least one dataset refreshed to `applied` or `nochange`, "error" otherwise. A missed check-in
13
+ alerts too, so a dead worker is noticed.
14
+
15
+ Every refresh is isolated: a failure is logged, reported to Sentry once per (dataset, error type)
16
+ until it clears, and the loop moves on. Every other alert is also sent once until its condition
17
+ clears, except retires and catalogue adoptions, which alert every time. The heartbeat file
18
+ (healthcheck.py) is touched only by a dataset refresh that ended `applied` or `nochange`.
19
+
20
+ EXACTLY ONE refresher may run: two diverge MongoDB for good (ebooklet docs/ops.md). The defences are
21
+ Swarm's `replicas: 1` with stop-first updates, a fast exit on SIGTERM (Shutdown, below), and pinning
22
+ to MongoDB's node. There is no lock, so never run a second one by hand. The bound on shutdown is a
23
+ watchdog in cli.py: a refresh can hold the exit (a thread-pool join on a stalled read), so the
24
+ process force-exits EXIT_WATCHDOG_SECONDS after SIGTERM, well inside Swarm's 60 s.
25
+ """
26
+
27
+ import collections
28
+ import logging
29
+ import pathlib
30
+ import threading
31
+ import time
32
+
33
+ import ebooklet
34
+ import s3func
35
+ import sentry_sdk
36
+ from ebooklet.mongo import ensure_schema, object_reader, refresh
37
+ from sentry_sdk.crons import capture_checkin
38
+
39
+ from envlib_api import healthcheck, mirror
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+
44
+ GOOD_STATUSES = ('applied', 'nochange') # a refresh that did its job
45
+ ALERT_STATUSES = ('missing', 'stale_get', 'interleaved') # alerted once each, until they clear
46
+
47
+
48
+ class Shutdown(BaseException):
49
+ """
50
+ Raised by the SIGTERM handler wherever the main thread is, a blocked HTTP read included. It
51
+ abandons the refresh in flight, which is safe: a refresh interrupted at any point is redone by
52
+ the next poll. It is a BaseException, so the per-refresh `except Exception` never swallows it.
53
+ """
54
+
55
+
56
+ class Refresher:
57
+ """
58
+ One refresher. `connect(db_url)` builds the ebooklet connection a refresh uses, and
59
+ `reader(db_url)` the object reader for the catalogue's values; both default to the public HTTP
60
+ path with the configured timeouts. `report(err)`, `alert(message)` and `checkin(status)` default
61
+ to Sentry; tests replace them.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ cfg,
67
+ db,
68
+ *,
69
+ connect=None,
70
+ reader=None,
71
+ report=None,
72
+ alert=None,
73
+ checkin=None,
74
+ heartbeat_path=healthcheck.HEARTBEAT_PATH,
75
+ ):
76
+ self.cfg = cfg
77
+ self.db = db
78
+ self.stop = threading.Event()
79
+ self._http = s3func.HttpSession(read_timeout=cfg.read_timeout, max_attempts=cfg.retries, stream=False)
80
+ self._connect = connect or (
81
+ lambda url: ebooklet.S3Connection(db_url=url, read_timeout=cfg.read_timeout, retries=cfg.retries)
82
+ )
83
+ self._reader = reader or (lambda url: object_reader(url, http_session=self._http))
84
+ self._report = report or _sentry_report
85
+ self._alert = alert or _sentry_alert
86
+ self._checkin = checkin or (lambda status: _sentry_checkin(cfg, status))
87
+ self._heartbeat = pathlib.Path(heartbeat_path)
88
+ self._reported = set() # alert keys already sent to Sentry, until their condition clears
89
+ self._value_failures = collections.Counter() # catalogue key -> consecutive failed reads
90
+
91
+ # ── one refresh ───────────────────────────────────────────────────────────────────────────
92
+
93
+ def refresh_one(self, dvid, db_url, *, heartbeat=True):
94
+ """
95
+ refresh() one dataset. Returns its result dict, or None if it raised (logged, reported).
96
+ An `applied` or `nochange` result touches the heartbeat, except for the catalogue's own refresh
97
+ (heartbeat=False): a worker whose every dataset fails, or is missing, must turn unhealthy even
98
+ while the catalogue is fine.
99
+ """
100
+ try:
101
+ res = refresh(self.db, dvid, self._connect(db_url))
102
+ except Exception as err:
103
+ logger.error(f'{dvid}: refresh failed: {type(err).__name__}: {err}')
104
+ self._once(('refresh', dvid, type(err).__name__), lambda err=err: self._report(err))
105
+ return None
106
+ status = res['status']
107
+ still = {status} if status in ALERT_STATUSES else set()
108
+ if res['unmanifested']:
109
+ still.add('unmanifested')
110
+ self._clear(lambda k: k[:2] == ('refresh', dvid) and k[2] not in still)
111
+ if heartbeat and status in GOOD_STATUSES:
112
+ self._heartbeat.touch()
113
+ if status != 'nochange':
114
+ logger.info(f"{dvid}: {status} (upserted {res['upserted']}, removed {res['removed']})")
115
+ if status in ALERT_STATUSES:
116
+ self._once(
117
+ ('refresh', dvid, status), lambda: self._alert(f'{dvid}: refresh returned {status!r} ({db_url})')
118
+ )
119
+ if res['unmanifested']:
120
+ self._once(
121
+ ('refresh', dvid, 'unmanifested'),
122
+ lambda: self._alert(f"{dvid}: {res['unmanifested']} index entries name a group not in the manifest"),
123
+ )
124
+ return res
125
+
126
+ def probe(self, db_url):
127
+ """True if the remote at db_url answers its db-object HEAD (used before a re-point)."""
128
+ try:
129
+ return bool(self._connect(db_url).open('r').initialized)
130
+ except Exception as err:
131
+ logger.warning(f'probe of {db_url} failed: {type(err).__name__}: {err}')
132
+ return False
133
+
134
+ def _once(self, key, send):
135
+ """Send an alert or report once; it is sent again only after its condition has cleared."""
136
+ if key not in self._reported:
137
+ self._reported.add(key)
138
+ send()
139
+
140
+ def _clear(self, predicate):
141
+ cleared = {k for k in self._reported if predicate(k)}
142
+ if cleared:
143
+ logger.info(f'recovered: {sorted(cleared)}')
144
+ self._reported -= cleared
145
+
146
+ # ── one cycle ─────────────────────────────────────────────────────────────────────────────
147
+
148
+ def cycle(self):
149
+ """One poll of the catalogue and every dataset. Returns a summary dict."""
150
+ t0 = time.monotonic()
151
+ cat = self.refresh_one(mirror.CATALOGUE_ID, self.cfg.catalogue_url, heartbeat=False)
152
+ catalogue_ok = cat is not None and cat['status'] in GOOD_STATUSES
153
+ sync_ok = True
154
+ try:
155
+ out = mirror.sync(
156
+ self.db,
157
+ catalogue_ok,
158
+ self.refresh_one,
159
+ self._reader(self.cfg.catalogue_url),
160
+ max_retires=self.cfg.max_retires_per_cycle,
161
+ probe=self.probe,
162
+ )
163
+ except Exception as err:
164
+ sync_ok = False
165
+ logger.error(f'catalogue sync failed: {type(err).__name__}: {err}')
166
+ self._once(('sync-error', type(err).__name__), lambda err=err: self._report(err))
167
+ out = mirror.empty_sync_result()
168
+ else:
169
+ self._clear(lambda k: k[0] == 'sync-error')
170
+ self._handle_sync(out)
171
+ results = dict(out['refreshed'])
172
+ for dvid, url in mirror.poll_order(self.db, mirror.members(self.db)):
173
+ if dvid not in results:
174
+ results[dvid] = self.refresh_one(dvid, url)
175
+ n_good = sum(r is not None and r['status'] in GOOD_STATUSES for r in results.values())
176
+ ok = catalogue_ok and sync_ok and n_good > 0
177
+ self._checkin('ok' if ok else 'error')
178
+ summary = {
179
+ 'ok': ok,
180
+ 'datasets': len(results),
181
+ 'failed': sum(r is None for r in results.values()),
182
+ 'changed': sorted(k for k, r in results.items() if r is not None and r['status'] != 'nochange'),
183
+ 'retired': out['retired'],
184
+ 'listed': out['listed'],
185
+ 'repointed': out['repointed'],
186
+ 'repoint_failed': sorted(out['repoint_failed']),
187
+ 'value_failures': sorted(out['value_failures']),
188
+ 'adopted': out['adopted'],
189
+ 'blocked': out['blocked'],
190
+ 'refreshed': results,
191
+ 'seconds': round(time.monotonic() - t0, 2),
192
+ }
193
+ level = logging.INFO if ok and not summary['failed'] else logging.WARNING
194
+ logger.log(level, f"cycle: { {k: v for k, v in summary.items() if k != 'refreshed'} }")
195
+ return summary
196
+
197
+ def _handle_sync(self, out):
198
+ if out['blocked']:
199
+ logger.error(out['blocked'])
200
+ self._once(('blocked',), lambda: self._alert(out['blocked']))
201
+ else:
202
+ self._clear(lambda k: k == ('blocked',))
203
+ if out['retired']: # every retire is an event an operator should see, so it is not deduplicated
204
+ msg = f"retired (gone from the catalogue): {out['retired']}"
205
+ logger.warning(msg)
206
+ self._alert(msg)
207
+ if out['adopted']:
208
+ msg = f"adopted a recreated catalogue (uuid {out['adopted'][0]} -> {out['adopted'][1]}); nothing was lost"
209
+ logger.warning(msg)
210
+ self._alert(msg)
211
+ for k in out['listed']:
212
+ self._value_failures.pop(k, None)
213
+ self._clear(lambda key, k=k: key in (('value', k), ('repoint', k)))
214
+ for k, why in out['repoint_failed'].items():
215
+ logger.warning(f'{k}: not re-pointing: {why}; the old remote is still served and polled')
216
+ self._once(('repoint', k), lambda k=k, why=why: self._alert(f'{k}: not re-pointing: {why}'))
217
+ for k, why in out['value_failures'].items():
218
+ self._value_failures[k] += 1
219
+ n = self._value_failures[k]
220
+ logger.warning(f'{k}: catalogue value unusable ({why}); the existing document is kept ({n} cycles)')
221
+ if n >= self.cfg.value_failure_alert_cycles:
222
+ self._once(
223
+ ('value', k),
224
+ lambda k=k, why=why, n=n: self._alert(f'{k}: catalogue value unusable for {n}+ cycles: {why}'),
225
+ )
226
+
227
+ # ── the loop ──────────────────────────────────────────────────────────────────────────────
228
+
229
+ def start(self):
230
+ ensure_schema(self.db, self.cfg.chunk_ttl_seconds)
231
+ mirror.ensure_catalogue_schema(self.db)
232
+
233
+ def run(self):
234
+ """Cycle until `stop` is set. The sleep is stop.wait(), so a SIGTERM ends it at once."""
235
+ self.start()
236
+ logger.info(f'refresher started: every {self.cfg.poll_seconds} s, catalogue {self.cfg.catalogue_url}')
237
+ while not self.stop.is_set():
238
+ t0 = time.monotonic()
239
+ self.cycle()
240
+ self.stop.wait(max(0.0, self.cfg.poll_seconds - (time.monotonic() - t0)))
241
+
242
+
243
+ # ── Sentry (the defaults; tests replace them) ─────────────────────────────────────────────────
244
+
245
+
246
+ def _sentry_report(err):
247
+ sentry_sdk.capture_exception(err)
248
+
249
+
250
+ def _sentry_alert(message):
251
+ sentry_sdk.capture_message(message, level='error')
252
+
253
+
254
+ def _sentry_checkin(cfg, status):
255
+ capture_checkin(
256
+ monitor_slug=cfg.monitor_slug,
257
+ status=status,
258
+ monitor_config={
259
+ 'schedule': {'type': 'interval', 'value': max(1, round(cfg.poll_seconds / 60)), 'unit': 'minute'},
260
+ 'checkin_margin': 5, # minutes late before a missed check-in alerts
261
+ 'failure_issue_threshold': 3, # three error check-ins in a row open an issue
262
+ 'recovery_threshold': 1,
263
+ 'timezone': 'UTC',
264
+ },
265
+ )
File without changes