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.
- envlib_api/__init__.py +3 -0
- envlib_api/__main__.py +3 -0
- envlib_api/api/__init__.py +7 -0
- envlib_api/api/app.py +435 -0
- envlib_api/api/compress.py +52 -0
- envlib_api/api/cost.py +107 -0
- envlib_api/api/edr.py +343 -0
- envlib_api/api/encode.py +285 -0
- envlib_api/api/errors.py +23 -0
- envlib_api/api/grid.py +317 -0
- envlib_api/api/params.py +71 -0
- envlib_api/api/read.py +65 -0
- envlib_api/api/resolve.py +191 -0
- envlib_api/api/server.py +35 -0
- envlib_api/api/stations.py +96 -0
- envlib_api/api/timesel.py +97 -0
- envlib_api/cli.py +179 -0
- envlib_api/config.py +158 -0
- envlib_api/healthcheck.py +38 -0
- envlib_api/mirror.py +353 -0
- envlib_api/refresher.py +265 -0
- envlib_api/tests/__init__.py +0 -0
- envlib_api/tests/api_support.py +307 -0
- envlib_api/tests/conftest.py +12 -0
- envlib_api/tests/grid_support.py +217 -0
- envlib_api/tests/schemas/README.md +12 -0
- envlib_api/tests/schemas/coveragejson/coveragejson.json +1794 -0
- envlib_api/tests/schemas/edr/schemas/collections/DataQuery.yaml +38 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/collection.yaml +137 -0
- envlib_api/tests/schemas/edr/schemas/collections/collections.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorDataQuery.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/crsObject.yaml +15 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeDataQuery.yaml +20 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/extent.yaml +311 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/observedPropertyCollection.yaml +51 -0
- envlib_api/tests/schemas/edr/schemas/collections/parameterNames.yaml +70 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionDataQuery.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusDataQuery.yaml +18 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/units.yaml +42 -0
- envlib_api/tests/schemas/edr/schemas/core/confClasses.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/exception.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/landingPage.yaml +76 -0
- envlib_api/tests/schemas/edr/schemas/core/link.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/anyAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverage.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageBase.yaml +68 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageCollection.yaml +58 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageJSON.yaml +46 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonI18n.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonObservedProperty.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameter.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameterGroup.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonUnit.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domain.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domainBase.yaml +337 -0
- envlib_api/tests/schemas/edr/schemas/covjson/ndArray.yaml +88 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericRegularlySpacedAxis.yaml +17 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/polygonValuesAxis.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/primitiveValuesAxis.yaml +22 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystem.yaml +48 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystemConnection.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/targetConcept.yaml +13 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tiledNdArray.yaml +50 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tupleValuesAxis.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxis.yaml +27 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxisBase.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrFeatureCollectionGeoJSON.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrProperties.yaml +49 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/observedProperty.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/parameter.yaml +28 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/unit.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/geojson/featureGeoJSON.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/geojson/geometrycollectionGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/linestringGeoJSON.yaml +23 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multilinestringGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipointGeoJSON.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipolygonGeoJSON.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/geojson/pointGeoJSON.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/geojson/polygonGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/i18n.yaml +4 -0
- envlib_api/tests/schemas/edr/schemas/numberMatched.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/numberReturned.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/parameterGroup.yaml +30 -0
- envlib_api/tests/schemas/edr/schemas/queries/instances.yaml +26 -0
- envlib_api/tests/support.py +320 -0
- envlib_api/tests/test_alerting_and_guards.py +325 -0
- envlib_api/tests/test_api.py +808 -0
- envlib_api/tests/test_api_review.py +428 -0
- envlib_api/tests/test_grid.py +1075 -0
- envlib_api/tests/test_ops.py +358 -0
- envlib_api/tests/test_refresher.py +354 -0
- envlib_api/tests/test_schemas.py +91 -0
- envlib_api-0.3.0.dist-info/METADATA +408 -0
- envlib_api-0.3.0.dist-info/RECORD +116 -0
- envlib_api-0.3.0.dist-info/WHEEL +4 -0
- envlib_api-0.3.0.dist-info/entry_points.txt +3 -0
- envlib_api-0.3.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The operator side: MongoDB auth with the production role, `status`, the SIGTERM exit, and the
|
|
3
|
+
catalogue value parser.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import datetime
|
|
7
|
+
import http.server
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import signal
|
|
11
|
+
import socket
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
|
|
19
|
+
import envlib.catalogue
|
|
20
|
+
import orjson
|
|
21
|
+
import pytest
|
|
22
|
+
from ebooklet.mongo import DATASETS, ensure_schema
|
|
23
|
+
from pymongo.errors import OperationFailure
|
|
24
|
+
from typer.testing import CliRunner
|
|
25
|
+
|
|
26
|
+
from envlib_api import config, healthcheck, mirror
|
|
27
|
+
from envlib_api import refresher as refresher_mod
|
|
28
|
+
from envlib_api.cli import app, status_rows
|
|
29
|
+
from envlib_api.tests.support import free_port
|
|
30
|
+
|
|
31
|
+
A = 'a' * 24
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ── auth: the production role (plan review edr-worker-plan-2, finding 2) ──────────────────────────
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_the_production_role_runs_ensure_schema_at_every_start_and_changes_the_ttl(db):
|
|
38
|
+
for ttl in (3600, 3600, 60): # first start, a restart, a changed chunk_ttl_days
|
|
39
|
+
ensure_schema(db, ttl)
|
|
40
|
+
mirror.ensure_catalogue_schema(db)
|
|
41
|
+
assert db['chunks'].index_information()['t_ttl']['expireAfterSeconds'] == 60
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_plain_readwrite_cannot_restart_which_is_why_the_role_adds_collmod(readwrite_db):
|
|
45
|
+
ensure_schema(readwrite_db, 3600) # creating the collections needs no collMod
|
|
46
|
+
with pytest.raises(OperationFailure, match='collMod'):
|
|
47
|
+
ensure_schema(readwrite_db, 3600)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ── status ─────────────────────────────────────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _doc(_id, age_s, now, **kw):
|
|
54
|
+
return {
|
|
55
|
+
'_id': _id,
|
|
56
|
+
'db_url': 'https://x',
|
|
57
|
+
'rev': 1,
|
|
58
|
+
'missing': False,
|
|
59
|
+
'applied': {'uuid': 'u', 'ts': 1},
|
|
60
|
+
'checked_at': now - datetime.timedelta(seconds=age_s),
|
|
61
|
+
**kw,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_status_flags_stale_missing_and_unapplied_but_not_retired(db):
|
|
66
|
+
now = datetime.datetime.now(datetime.UTC)
|
|
67
|
+
db[DATASETS].insert_many(
|
|
68
|
+
[
|
|
69
|
+
_doc('fresh', 30, now),
|
|
70
|
+
_doc('stale', 500, now),
|
|
71
|
+
_doc('missing', 30, now, missing=True),
|
|
72
|
+
_doc('unapplied', 30, now, applied=None),
|
|
73
|
+
_doc('retired', 9000, now, missing=True, applied=None, retired=True),
|
|
74
|
+
]
|
|
75
|
+
)
|
|
76
|
+
flags = {r['id']: r['flags'] for r in status_rows(db, poll_seconds=60, now=now)}
|
|
77
|
+
assert flags == {
|
|
78
|
+
'fresh': [],
|
|
79
|
+
'stale': ['stale'],
|
|
80
|
+
'missing': ['missing'],
|
|
81
|
+
'unapplied': ['not applied'],
|
|
82
|
+
'retired': [],
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _toml(tmp_path, uri, **refresher):
|
|
87
|
+
lines = ['[mongo]', f'uri = "{uri}"', f'database = "{uri.rsplit("/", 1)[1].split("?")[0]}"', '[refresher]']
|
|
88
|
+
lines += [f'{k} = {v!r}'.replace("'", '"') for k, v in refresher.items()]
|
|
89
|
+
path = tmp_path / 'envlib-api.toml'
|
|
90
|
+
path.write_text('\n'.join(lines) + '\n')
|
|
91
|
+
return path
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_the_status_command_exits_nonzero_on_a_flag_and_detects_a_stuck_apply(db_and_uri, tmp_path):
|
|
95
|
+
db, uri = db_and_uri
|
|
96
|
+
now = datetime.datetime.now(datetime.UTC)
|
|
97
|
+
db[DATASETS].insert_one(_doc('ok', 10, now))
|
|
98
|
+
cfg = _toml(tmp_path, uri)
|
|
99
|
+
res = CliRunner().invoke(app, ['status', '--config', str(cfg), '--recheck-seconds', '0'])
|
|
100
|
+
assert res.exit_code == 0, res.output
|
|
101
|
+
db[DATASETS].update_one({'_id': 'ok'}, {'$set': {'applying': True}})
|
|
102
|
+
res = CliRunner().invoke(app, ['status', '--config', str(cfg), '--recheck-seconds', '0'])
|
|
103
|
+
assert res.exit_code == 1 and 'stuck applying' in res.output
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ── SIGTERM: a fast exit, even from a blocked HTTP read (finding 4) ─────────────────────────────
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class SilentServer:
|
|
110
|
+
"""Accepts connections and never answers: a stalled endpoint."""
|
|
111
|
+
|
|
112
|
+
def __init__(self):
|
|
113
|
+
self.port = free_port()
|
|
114
|
+
self.sock = socket.create_server(('127.0.0.1', self.port))
|
|
115
|
+
self.connected = threading.Event()
|
|
116
|
+
self.conns = []
|
|
117
|
+
threading.Thread(target=self._serve, daemon=True).start()
|
|
118
|
+
|
|
119
|
+
def _serve(self):
|
|
120
|
+
while True:
|
|
121
|
+
try:
|
|
122
|
+
c, _ = self.sock.accept()
|
|
123
|
+
except OSError:
|
|
124
|
+
return
|
|
125
|
+
self.conns.append(c)
|
|
126
|
+
self.connected.set()
|
|
127
|
+
|
|
128
|
+
def close(self):
|
|
129
|
+
for c in self.conns:
|
|
130
|
+
c.close()
|
|
131
|
+
self.sock.close()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _start(tmp_path, cfg_path, **extra_env):
|
|
135
|
+
env = dict(os.environ, ENVLIB_API_TOML=str(cfg_path), ENVLIB_API_HEARTBEAT=str(tmp_path / 'heartbeat'), **extra_env)
|
|
136
|
+
return subprocess.Popen(
|
|
137
|
+
[sys.executable, '-m', 'envlib_api', 'refresher'],
|
|
138
|
+
env=env,
|
|
139
|
+
stdout=subprocess.PIPE,
|
|
140
|
+
stderr=subprocess.STDOUT,
|
|
141
|
+
text=True,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _term_and_time(proc):
|
|
146
|
+
t0 = time.monotonic()
|
|
147
|
+
proc.send_signal(signal.SIGTERM)
|
|
148
|
+
out, _ = proc.communicate(timeout=15)
|
|
149
|
+
return time.monotonic() - t0, out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_sigterm_during_a_stalled_refresh_exits_at_once(db_and_uri, tmp_path):
|
|
153
|
+
_, uri = db_and_uri
|
|
154
|
+
silent = SilentServer()
|
|
155
|
+
try:
|
|
156
|
+
cfg = _toml(
|
|
157
|
+
tmp_path, uri, catalogue_url=f'http://127.0.0.1:{silent.port}/bucket/catalogue', read_timeout=20, retries=0
|
|
158
|
+
)
|
|
159
|
+
proc = _start(tmp_path, cfg)
|
|
160
|
+
assert silent.connected.wait(20), 'the refresher never reached the catalogue HEAD'
|
|
161
|
+
time.sleep(0.2) # it is now blocked reading the response
|
|
162
|
+
took, out = _term_and_time(proc)
|
|
163
|
+
finally:
|
|
164
|
+
silent.close()
|
|
165
|
+
assert proc.returncode == 0, out
|
|
166
|
+
assert took < 2, f'SIGTERM took {took:.1f} s to stop a stalled refresh (Swarm starts the next task at 60 s)'
|
|
167
|
+
assert 'stopping on a signal' in out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def test_sigterm_during_the_sleep_exits_at_once(db_and_uri, tmp_path, world):
|
|
171
|
+
_, uri = db_and_uri
|
|
172
|
+
world.member('m1', n=1)
|
|
173
|
+
world.publish({A: 'm1'})
|
|
174
|
+
cfg = _toml(tmp_path, uri, catalogue_url=world.catalogue_url, poll_seconds=150, read_timeout=5, retries=0)
|
|
175
|
+
proc = _start(tmp_path, cfg)
|
|
176
|
+
lines = []
|
|
177
|
+
deadline = time.monotonic() + 30
|
|
178
|
+
while time.monotonic() < deadline:
|
|
179
|
+
line = proc.stdout.readline()
|
|
180
|
+
lines.append(line)
|
|
181
|
+
if 'cycle:' in line:
|
|
182
|
+
break
|
|
183
|
+
assert any('cycle:' in x for x in lines), ''.join(lines)
|
|
184
|
+
took, out = _term_and_time(proc)
|
|
185
|
+
assert proc.returncode == 0, ''.join(lines) + out
|
|
186
|
+
assert took < 2, f'SIGTERM took {took:.1f} s during the sleep'
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ── the catalogue value parser ─────────────────────────────────────────────────────────────────
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _value(**over):
|
|
193
|
+
entry = {
|
|
194
|
+
'entry_version': 1,
|
|
195
|
+
'type': 'EVariableLengthValue',
|
|
196
|
+
'timestamp': 1,
|
|
197
|
+
'user_meta': {'dataset_id': 'd' * 24, 'dataset_version_id': A},
|
|
198
|
+
'remote_conn': {'db_url': 'https://b2.example/x', 'db_key': 'x', 'bucket': 'b', 'endpoint_url': None},
|
|
199
|
+
}
|
|
200
|
+
entry.update(over)
|
|
201
|
+
return orjson.dumps(entry)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_parse_entry_keeps_only_the_connection_fields_never_credentials():
|
|
205
|
+
raw = orjson.loads(_value())
|
|
206
|
+
raw['remote_conn']['access_key'] = 'SECRET'
|
|
207
|
+
doc = mirror.parse_entry(A, orjson.dumps(raw))
|
|
208
|
+
assert doc['remote_conn'] == {'db_url': 'https://b2.example/x', 'db_key': 'x', 'bucket': 'b', 'endpoint_url': None}
|
|
209
|
+
assert doc['dataset_id'] == 'd' * 24 and doc['_id'] == A
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@pytest.mark.parametrize(
|
|
213
|
+
'raw',
|
|
214
|
+
[
|
|
215
|
+
None,
|
|
216
|
+
b'not json',
|
|
217
|
+
orjson.dumps([1, 2]),
|
|
218
|
+
_value(remote_conn={'db_url': None}),
|
|
219
|
+
_value(remote_conn={'db_url': 's3://bucket/key'}),
|
|
220
|
+
_value(user_meta={'dataset_id': 'd' * 24, 'dataset_version_id': 'e' * 24}),
|
|
221
|
+
_value(user_meta={'dataset_version_id': A}),
|
|
222
|
+
],
|
|
223
|
+
ids=['none', 'not-json', 'not-an-object', 'no-db-url', 'not-http', 'key-mismatch', 'no-dataset-id'],
|
|
224
|
+
)
|
|
225
|
+
def test_parse_entry_refuses_unusable_values(raw):
|
|
226
|
+
with pytest.raises(ValueError):
|
|
227
|
+
mirror.parse_entry(A, raw)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# ── the watchdog: a stalled catalogue VALUE read (code review edr-worker-code-2, finding 9) ─────────
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class StallingProxy:
|
|
234
|
+
"""Forwards HTTP to moto, except GETs of catalogue values (`…/catalogue/<24 hex>`), which hang."""
|
|
235
|
+
|
|
236
|
+
def __init__(self, upstream):
|
|
237
|
+
self.upstream = upstream
|
|
238
|
+
self.stalled = threading.Event()
|
|
239
|
+
proxy = self
|
|
240
|
+
|
|
241
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
242
|
+
def log_message(self, *args):
|
|
243
|
+
pass
|
|
244
|
+
|
|
245
|
+
def _forward(self, method):
|
|
246
|
+
if method == 'GET' and VALUE_PATH.search(self.path):
|
|
247
|
+
proxy.stalled.set()
|
|
248
|
+
time.sleep(120) # a stalled read: never answers within the test
|
|
249
|
+
return
|
|
250
|
+
headers = {k: v for k, v in self.headers.items() if k.lower() in ('range',)}
|
|
251
|
+
req = urllib.request.Request(proxy.upstream + self.path, method=method, headers=headers)
|
|
252
|
+
try:
|
|
253
|
+
resp = urllib.request.urlopen(req, timeout=10)
|
|
254
|
+
except urllib.error.HTTPError as err:
|
|
255
|
+
resp = err
|
|
256
|
+
body = resp.read()
|
|
257
|
+
self.send_response(resp.status if hasattr(resp, 'status') else resp.code)
|
|
258
|
+
for k, v in resp.headers.items():
|
|
259
|
+
if k.lower() not in ('transfer-encoding', 'connection', 'content-length'):
|
|
260
|
+
self.send_header(k, v)
|
|
261
|
+
self.send_header(
|
|
262
|
+
'Content-Length', str(len(body) if method == 'GET' else resp.headers.get('Content-Length', 0))
|
|
263
|
+
)
|
|
264
|
+
self.end_headers()
|
|
265
|
+
if method == 'GET':
|
|
266
|
+
self.wfile.write(body)
|
|
267
|
+
|
|
268
|
+
def do_GET(self):
|
|
269
|
+
self._forward('GET')
|
|
270
|
+
|
|
271
|
+
def do_HEAD(self):
|
|
272
|
+
self._forward('HEAD')
|
|
273
|
+
|
|
274
|
+
self.server = http.server.ThreadingHTTPServer(('127.0.0.1', free_port()), Handler)
|
|
275
|
+
self.server.daemon_threads = True
|
|
276
|
+
self.url = f'http://127.0.0.1:{self.server.server_address[1]}'
|
|
277
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
278
|
+
|
|
279
|
+
def close(self):
|
|
280
|
+
self.server.shutdown()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
VALUE_PATH = re.compile(r'/catalogue/[0-9a-f]{24}(\?|$)')
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def test_sigterm_during_a_stalled_catalogue_value_read_exits_by_the_watchdog(db_and_uri, tmp_path, world):
|
|
287
|
+
_, uri = db_and_uri
|
|
288
|
+
world.member('m1', n=1)
|
|
289
|
+
world.publish({A: 'm1'})
|
|
290
|
+
proxy = StallingProxy(world.url)
|
|
291
|
+
try:
|
|
292
|
+
cat_url = world.catalogue_url.replace(world.url, proxy.url)
|
|
293
|
+
cfg = _toml(tmp_path, uri, catalogue_url=cat_url, read_timeout=20, retries=2)
|
|
294
|
+
proc = _start(tmp_path, cfg, ENVLIB_API_EXIT_WATCHDOG='2')
|
|
295
|
+
assert proxy.stalled.wait(30), 'the refresher never read a catalogue value'
|
|
296
|
+
time.sleep(0.2)
|
|
297
|
+
took, out = _term_and_time(proc)
|
|
298
|
+
finally:
|
|
299
|
+
proxy.close()
|
|
300
|
+
assert proc.returncode == 0, out
|
|
301
|
+
assert took < 4, f'the exit took {took:.1f} s: the watchdog (2 s here, 10 s in production) did not fire'
|
|
302
|
+
assert 'forcing the exit' in out
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# ── healthcheck, config, and the Sentry calls ──────────────────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def test_the_healthcheck_fails_on_an_old_or_missing_heartbeat(tmp_path):
|
|
309
|
+
hb = tmp_path / 'hb'
|
|
310
|
+
assert healthcheck.main(str(hb)) == 1, 'a missing heartbeat is unhealthy'
|
|
311
|
+
hb.touch()
|
|
312
|
+
assert healthcheck.main(str(hb)) == 0
|
|
313
|
+
old = time.time() - healthcheck.MAX_AGE_SECONDS - 1
|
|
314
|
+
os.utime(hb, (old, old))
|
|
315
|
+
assert healthcheck.main(str(hb)) == 1
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _write(tmp_path, text):
|
|
319
|
+
path = tmp_path / 'c.toml'
|
|
320
|
+
path.write_text(text)
|
|
321
|
+
return path
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def test_config_defaults_and_refusals(tmp_path):
|
|
325
|
+
cfg = config.load(_write(tmp_path, '[mongo]\nuri = "mongodb://x"\n'))
|
|
326
|
+
assert cfg.poll_seconds == 60 and cfg.read_timeout == 20 and cfg.retries == 2 and cfg.database == 'envlib_api'
|
|
327
|
+
assert cfg.catalogue_url == config.PUBLIC_RCG_URL and cfg.chunk_ttl_seconds == 7 * 86400
|
|
328
|
+
for bad, match in (
|
|
329
|
+
('[refresher]\npoll_seconds = 60\n', 'uri is required'),
|
|
330
|
+
('[mongo]\nuri = "m"\n[refresher]\npoll_secs = 60\n', 'unknown'),
|
|
331
|
+
('[mongo]\nuri = "m"\n[refresher]\nmongo_uri = "other"\n', 'unknown'),
|
|
332
|
+
('[mongo]\nuri = "m"\n[refresher]\npoll_seconds = 151\n', 'poll_seconds must be <= 150'),
|
|
333
|
+
('[mongo]\nuri = "m"\n[refresher]\nretries = -1\n', 'retries >= 0'),
|
|
334
|
+
):
|
|
335
|
+
with pytest.raises(ValueError, match=match):
|
|
336
|
+
config.load(_write(tmp_path, bad))
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def test_the_copied_catalogue_url_equals_envlibs():
|
|
340
|
+
assert config.PUBLIC_RCG_URL == envlib.catalogue.PUBLIC_RCG_URL
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def test_the_sentry_calls(monkeypatch):
|
|
344
|
+
seen = {}
|
|
345
|
+
monkeypatch.setattr(refresher_mod, 'capture_checkin', lambda **kw: seen.setdefault('checkin', kw))
|
|
346
|
+
monkeypatch.setattr(
|
|
347
|
+
refresher_mod.sentry_sdk, 'capture_message', lambda m, level: seen.setdefault('alert', (m, level))
|
|
348
|
+
)
|
|
349
|
+
monkeypatch.setattr(refresher_mod.sentry_sdk, 'capture_exception', lambda e: seen.setdefault('report', e))
|
|
350
|
+
cfg = config.Config(mongo_uri='m', poll_seconds=120, monitor_slug='slug')
|
|
351
|
+
refresher_mod._sentry_checkin(cfg, 'error')
|
|
352
|
+
refresher_mod._sentry_alert('boom')
|
|
353
|
+
err = RuntimeError('x')
|
|
354
|
+
refresher_mod._sentry_report(err)
|
|
355
|
+
ck = seen['checkin']
|
|
356
|
+
assert ck['monitor_slug'] == 'slug' and ck['status'] == 'error'
|
|
357
|
+
assert ck['monitor_config']['schedule'] == {'type': 'interval', 'value': 2, 'unit': 'minute'}
|
|
358
|
+
assert seen['alert'] == ('boom', 'error') and seen['report'] is err
|