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,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The station table of a ts_ortho dataset, and selecting stations by id, polygon or radius.
|
|
3
|
+
|
|
4
|
+
Station order is always the dataset's own (ascending position on the `point` axis), whatever order
|
|
5
|
+
a query names them in.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pyproj
|
|
10
|
+
import shapely
|
|
11
|
+
from shapely.errors import ShapelyError
|
|
12
|
+
|
|
13
|
+
from envlib_api.api.errors import ApiError
|
|
14
|
+
|
|
15
|
+
_GEOD = pyproj.Geod(ellps='WGS84')
|
|
16
|
+
STATION_VARS = ('station_id', 'station_ref', 'station_name')
|
|
17
|
+
WITHIN_UNITS = {'km': 1000.0, 'm': 1.0}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Stations:
|
|
21
|
+
"""Positions, ids and names of every station, in dataset order."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, ids, refs, names, lon, lat):
|
|
24
|
+
self.ids = ids
|
|
25
|
+
self.refs = refs
|
|
26
|
+
self.names = names
|
|
27
|
+
self.lon = lon
|
|
28
|
+
self.lat = lat
|
|
29
|
+
|
|
30
|
+
def __len__(self):
|
|
31
|
+
return len(self.ids)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def read(cls, ds):
|
|
35
|
+
points = ds['point'].data
|
|
36
|
+
lon = np.array([p.x for p in points], dtype='float64')
|
|
37
|
+
lat = np.array([p.y for p in points], dtype='float64')
|
|
38
|
+
cols = [[str(v) for v in ds[name].data] for name in STATION_VARS]
|
|
39
|
+
if not all(len(c) == len(points) for c in cols):
|
|
40
|
+
raise ValueError('station variables are not aligned with the point axis')
|
|
41
|
+
return cls(*cols, lon, lat)
|
|
42
|
+
|
|
43
|
+
def by_id(self, loc_id):
|
|
44
|
+
"""The position of station `loc_id`, or None."""
|
|
45
|
+
try:
|
|
46
|
+
return self.ids.index(loc_id)
|
|
47
|
+
except ValueError:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
def in_geometry(self, geom):
|
|
51
|
+
"""
|
|
52
|
+
Positions of the stations the polygon covers (its boundary included). Each station is also
|
|
53
|
+
tried at lon - 360 and lon + 360, so a polygon drawn across the antimeridian, in either
|
|
54
|
+
longitude convention, finds the stations on both sides.
|
|
55
|
+
"""
|
|
56
|
+
hit = np.zeros(len(self), dtype=bool)
|
|
57
|
+
for shift in (0.0, -360.0, 360.0):
|
|
58
|
+
hit |= shapely.covers(geom, shapely.points(self.lon + shift, self.lat))
|
|
59
|
+
return [int(i) for i in np.nonzero(hit)[0]]
|
|
60
|
+
|
|
61
|
+
def within(self, lon, lat, metres):
|
|
62
|
+
"""Positions of the stations within `metres` of (lon, lat), by great-circle distance on WGS84."""
|
|
63
|
+
if not len(self):
|
|
64
|
+
return []
|
|
65
|
+
_, _, dist = _GEOD.inv(np.full(len(self), lon), np.full(len(self), lat), self.lon, self.lat)
|
|
66
|
+
return [int(i) for i in np.nonzero(np.asarray(dist) <= metres)[0]]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_wkt(text, kinds, param='coords'):
|
|
70
|
+
"""A WKT geometry of one of the given kinds (e.g. ('Polygon', 'MultiPolygon')), or a 400."""
|
|
71
|
+
try:
|
|
72
|
+
geom = shapely.from_wkt(text)
|
|
73
|
+
except (ShapelyError, ValueError, TypeError, NotImplementedError) as err: # curved WKT: NotImplementedError
|
|
74
|
+
raise ApiError(400, 'InvalidParameterValue', f'{param} is not valid WKT: {err}') from err
|
|
75
|
+
if geom is None or geom.geom_type not in kinds or geom.is_empty:
|
|
76
|
+
raise ApiError(400, 'InvalidParameterValue', f'{param} must be a WKT {" or ".join(k.upper() for k in kinds)}.')
|
|
77
|
+
return geom
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def check_point(point):
|
|
81
|
+
"""A radius centre must be a real lon/lat: |lat| <= 90 and finite."""
|
|
82
|
+
if not (np.isfinite(point.x) and np.isfinite(point.y) and -90 <= point.y <= 90):
|
|
83
|
+
raise ApiError(400, 'InvalidParameterValue', 'coords: the POINT must be a finite lon/lat with |lat| <= 90.')
|
|
84
|
+
return point
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def within_metres(within, units):
|
|
88
|
+
try:
|
|
89
|
+
value = float(within)
|
|
90
|
+
except ValueError as err:
|
|
91
|
+
raise ApiError(400, 'InvalidParameterValue', 'within must be a number.') from err
|
|
92
|
+
if not np.isfinite(value) or value < 0:
|
|
93
|
+
raise ApiError(400, 'InvalidParameterValue', 'within must be a finite number >= 0.')
|
|
94
|
+
if units not in WITHIN_UNITS:
|
|
95
|
+
raise ApiError(400, 'InvalidParameterValue', f'within-units must be one of {sorted(WITHIN_UNITS)}.')
|
|
96
|
+
return value * WITHIN_UNITS[units]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Resolving an EDR `datetime` against a dataset's time axis.
|
|
3
|
+
|
|
4
|
+
The rule is label containment: a time step is selected when its label t satisfies
|
|
5
|
+
start <= t <= end. An instant must equal a step exactly. Times are UTC: a naive time is read as UTC,
|
|
6
|
+
and an offset is converted.
|
|
7
|
+
|
|
8
|
+
cfdb's `.loc` is deliberately not used (plan review edr-api-plan-3). It casts string bounds to the
|
|
9
|
+
axis unit, so 05:30 would select the 05:00 step. It also answers the next step for an off-step
|
|
10
|
+
instant, and clamps an instant before the axis to its first step. The bounds here are compared at
|
|
11
|
+
microsecond resolution against the axis's integer labels, and returned as plain ints. cfdb reads a
|
|
12
|
+
numpy-integer slice bound as "the whole axis".
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import datetime
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from envlib_api.api.errors import ApiError
|
|
20
|
+
|
|
21
|
+
_US = np.timedelta64(1, 'us')
|
|
22
|
+
_OPEN = ('..', '')
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _parse_one(text):
|
|
26
|
+
try:
|
|
27
|
+
dt = datetime.datetime.fromisoformat(text.replace('Z', '+00:00').replace('z', '+00:00'))
|
|
28
|
+
if dt.tzinfo is not None:
|
|
29
|
+
## OverflowError: an offset that moves year 1 or 9999 out of range (code review edr-api-code-3)
|
|
30
|
+
dt = dt.astimezone(datetime.UTC).replace(tzinfo=None)
|
|
31
|
+
except (ValueError, OverflowError) as err:
|
|
32
|
+
raise ApiError(400, 'InvalidParameterValue', f'datetime {text!r} is not a usable RFC 3339 date-time.') from err
|
|
33
|
+
return np.datetime64(dt, 'us')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def parse(text):
|
|
37
|
+
"""`None` (no filter), ('instant', t) or ('interval', start or None, end or None), at us resolution."""
|
|
38
|
+
if text is None:
|
|
39
|
+
return None
|
|
40
|
+
if ',' in text:
|
|
41
|
+
raise ApiError(
|
|
42
|
+
400, 'InvalidParameterValue', 'A list of datetimes is not supported: give an instant or an interval.'
|
|
43
|
+
)
|
|
44
|
+
if '/' in text:
|
|
45
|
+
parts = text.split('/')
|
|
46
|
+
if len(parts) != 2:
|
|
47
|
+
raise ApiError(400, 'InvalidParameterValue', 'A datetime interval has exactly one "/".')
|
|
48
|
+
start, end = (None if p.strip() in _OPEN else _parse_one(p.strip()) for p in parts)
|
|
49
|
+
if start is not None and end is not None and end < start:
|
|
50
|
+
raise ApiError(400, 'InvalidParameterValue', 'The datetime interval ends before it starts.')
|
|
51
|
+
return ('interval', start, end)
|
|
52
|
+
if text.strip() in _OPEN:
|
|
53
|
+
raise ApiError(400, 'InvalidParameterValue', 'datetime ".." alone is not an instant.')
|
|
54
|
+
return ('instant', _parse_one(text.strip()))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _floor(key, unit):
|
|
58
|
+
"""(the axis-unit label at or below `key`, whether `key` is exactly on it)."""
|
|
59
|
+
step = np.timedelta64(1, unit)
|
|
60
|
+
us_per = int(step / _US)
|
|
61
|
+
us = int(key.astype('int64'))
|
|
62
|
+
floor_units = us // us_per
|
|
63
|
+
return np.datetime64(floor_units, unit), floor_units * us_per == us
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def resolve(spec, axis):
|
|
67
|
+
"""The positional range [a, b) of `axis` (a sorted datetime64 array) selected by `spec`, as plain ints."""
|
|
68
|
+
n = len(axis)
|
|
69
|
+
if spec is None:
|
|
70
|
+
return 0, n
|
|
71
|
+
unit = np.datetime_data(axis.dtype)[0]
|
|
72
|
+
if spec[0] == 'instant':
|
|
73
|
+
label, exact = _floor(spec[1], unit)
|
|
74
|
+
i = int(np.searchsorted(axis, label, side='left'))
|
|
75
|
+
if exact and i < n and axis[i] == label:
|
|
76
|
+
return i, i + 1
|
|
77
|
+
return i, i # empty
|
|
78
|
+
_, start, end = spec
|
|
79
|
+
a = 0
|
|
80
|
+
if start is not None:
|
|
81
|
+
label, exact = _floor(start, unit)
|
|
82
|
+
a = int(np.searchsorted(axis, label, side='left'))
|
|
83
|
+
if not exact and a < n and axis[a] == label:
|
|
84
|
+
a += 1 # that label is before an off-step start
|
|
85
|
+
b = n
|
|
86
|
+
if end is not None:
|
|
87
|
+
label, _ = _floor(end, unit)
|
|
88
|
+
b = int(np.searchsorted(axis, label, side='right'))
|
|
89
|
+
return a, max(a, b)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def iso(times):
|
|
93
|
+
"""CoverageJSON / RFC 3339 text for datetime64 values: YYYY-MM-DDTHH:MM:SS[.f]Z."""
|
|
94
|
+
secs = times.astype('datetime64[s]')
|
|
95
|
+
if np.any(secs != times):
|
|
96
|
+
return [s + 'Z' for s in np.datetime_as_string(times.astype('datetime64[us]'), unit='us')]
|
|
97
|
+
return [s + 'Z' for s in np.datetime_as_string(secs, unit='s')]
|
envlib_api/cli.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The command line: `envlib-api refresher` (the service), `envlib-api status`, and `envlib-api
|
|
3
|
+
allow-retires`.
|
|
4
|
+
|
|
5
|
+
There is deliberately no one-shot refresh command. A refresh run by hand beside the service is a
|
|
6
|
+
second refresher, which diverges MongoDB for good (ebooklet docs/ops.md).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import datetime
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import signal
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
import pymongo
|
|
18
|
+
import sentry_sdk
|
|
19
|
+
import typer
|
|
20
|
+
from ebooklet.mongo import DATASETS, ENTRIES
|
|
21
|
+
from sentry_sdk.integrations.logging import LoggingIntegration
|
|
22
|
+
|
|
23
|
+
from envlib_api import __version__, config, mirror
|
|
24
|
+
from envlib_api.refresher import Refresher, Shutdown
|
|
25
|
+
|
|
26
|
+
app = typer.Typer(add_completion=False, help='envlib-api: the refresher service and its operator commands.')
|
|
27
|
+
logger = logging.getLogger('envlib_api')
|
|
28
|
+
|
|
29
|
+
STALE_FACTOR = 3 # `status` flags a dataset whose checked_at is older than this many poll intervals
|
|
30
|
+
## After SIGTERM the process force-exits this many seconds later, whatever it is doing. Raising
|
|
31
|
+
## Shutdown abandons a refresh at once, except where something holds the exit: a thread-pool join on a
|
|
32
|
+
## stalled HTTP read (measured at 62 s), or a library swallowing the exception. A hard exit is as safe as
|
|
33
|
+
## a crash, which every refresh survives. The env var is for tests.
|
|
34
|
+
EXIT_WATCHDOG_SECONDS = float(os.environ.get('ENVLIB_API_EXIT_WATCHDOG', '10'))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _setup(cfg):
|
|
38
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s', stream=sys.stdout)
|
|
39
|
+
if cfg.sentry_dsn:
|
|
40
|
+
sentry_sdk.init(
|
|
41
|
+
dsn=cfg.sentry_dsn,
|
|
42
|
+
environment=cfg.sentry_environment,
|
|
43
|
+
release=f'envlib-api@{__version__}',
|
|
44
|
+
integrations=[LoggingIntegration(event_level=None)], # log records never become error events
|
|
45
|
+
)
|
|
46
|
+
else:
|
|
47
|
+
logger.warning('error reporting is OFF: no [sentry] dsn in the config, so nothing will alert.')
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _db(cfg):
|
|
51
|
+
return pymongo.MongoClient(cfg.mongo_uri, tz_aware=True)[cfg.database]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.command()
|
|
55
|
+
def refresher(config_path: str = typer.Option(None, '--config', help='The TOML (default: $ENVLIB_API_TOML).')):
|
|
56
|
+
"""Run the refresher until SIGTERM."""
|
|
57
|
+
cfg = config.load(config_path)
|
|
58
|
+
_setup(cfg)
|
|
59
|
+
worker = Refresher(cfg, _db(cfg))
|
|
60
|
+
|
|
61
|
+
def on_term(signum, frame):
|
|
62
|
+
if not worker.stop.is_set():
|
|
63
|
+
worker.stop.set()
|
|
64
|
+
threading.Thread(target=_hard_exit, args=(EXIT_WATCHDOG_SECONDS,), daemon=True).start()
|
|
65
|
+
raise Shutdown()
|
|
66
|
+
|
|
67
|
+
signal.signal(signal.SIGTERM, on_term)
|
|
68
|
+
signal.signal(signal.SIGINT, on_term)
|
|
69
|
+
try:
|
|
70
|
+
worker.run()
|
|
71
|
+
except Shutdown:
|
|
72
|
+
logger.info('stopping on a signal; a refresh in flight was abandoned, and the next start redoes it.')
|
|
73
|
+
sys.exit(0)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _hard_exit(after):
|
|
77
|
+
time.sleep(after)
|
|
78
|
+
logger.warning(
|
|
79
|
+
f'still running {after:.0f} s after the signal; forcing the exit (a refresh in flight is redone next start).'
|
|
80
|
+
)
|
|
81
|
+
logging.shutdown()
|
|
82
|
+
os._exit(0)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def status_rows(db, poll_seconds, now=None):
|
|
86
|
+
"""
|
|
87
|
+
One row per dataset document, with the reasons it is flagged (an empty list when fine), plus a
|
|
88
|
+
row for each catalogue entry that has never been mirrored (no dataset document at all).
|
|
89
|
+
"""
|
|
90
|
+
now = now or datetime.datetime.now(datetime.UTC)
|
|
91
|
+
rows = []
|
|
92
|
+
known = set()
|
|
93
|
+
for d in db[DATASETS].find({}, {'meta_section': 0}).sort('_id'):
|
|
94
|
+
known.add(d['_id'])
|
|
95
|
+
flags = []
|
|
96
|
+
checked = d.get('checked_at')
|
|
97
|
+
age = None if checked is None else (now - checked.replace(tzinfo=datetime.UTC)).total_seconds()
|
|
98
|
+
if d.get('retired'):
|
|
99
|
+
pass # listed for information; a retired dataset is meant to be idle
|
|
100
|
+
else:
|
|
101
|
+
if age is None or age > STALE_FACTOR * poll_seconds:
|
|
102
|
+
flags.append('stale')
|
|
103
|
+
if d.get('missing'):
|
|
104
|
+
flags.append('missing')
|
|
105
|
+
if d.get('applied') is None:
|
|
106
|
+
flags.append('not applied')
|
|
107
|
+
rows.append(
|
|
108
|
+
{
|
|
109
|
+
'id': d['_id'],
|
|
110
|
+
'age': age,
|
|
111
|
+
'rev': d.get('rev'),
|
|
112
|
+
'applying': bool(d.get('applying')),
|
|
113
|
+
'missing': bool(d.get('missing')),
|
|
114
|
+
'retired': bool(d.get('retired')),
|
|
115
|
+
'applied_ts': (d.get('applied') or {}).get('ts'),
|
|
116
|
+
'flags': flags,
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
for e in db[ENTRIES].find({'d': mirror.CATALOGUE_ID}, {'k': 1}).sort('k'):
|
|
120
|
+
if mirror.HEX24.fullmatch(e['k']) and e['k'] not in known:
|
|
121
|
+
rows.append(
|
|
122
|
+
{
|
|
123
|
+
'id': e['k'],
|
|
124
|
+
'age': None,
|
|
125
|
+
'rev': None,
|
|
126
|
+
'applying': False,
|
|
127
|
+
'missing': False,
|
|
128
|
+
'retired': False,
|
|
129
|
+
'applied_ts': None,
|
|
130
|
+
'flags': ['never mirrored'],
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
return rows
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@app.command()
|
|
137
|
+
def status(
|
|
138
|
+
config_path: str = typer.Option(None, '--config', help='The TOML (default: $ENVLIB_API_TOML).'),
|
|
139
|
+
recheck_seconds: float = typer.Option(10.0, help='How long to wait before re-reading an `applying` dataset.'),
|
|
140
|
+
):
|
|
141
|
+
"""One row per dataset; exits 1 if any is stale, missing, unapplied, or stuck applying."""
|
|
142
|
+
cfg = config.load(config_path)
|
|
143
|
+
db = _db(cfg)
|
|
144
|
+
rows = status_rows(db, cfg.poll_seconds)
|
|
145
|
+
applying = [r['id'] for r in rows if r['applying'] and not r['retired']]
|
|
146
|
+
if applying:
|
|
147
|
+
time.sleep(recheck_seconds)
|
|
148
|
+
again = {r['id']: r for r in status_rows(db, cfg.poll_seconds)}
|
|
149
|
+
for r in rows:
|
|
150
|
+
if r['id'] in applying and again.get(r['id'], {}).get('applying'):
|
|
151
|
+
r['flags'].append('stuck applying')
|
|
152
|
+
print(f'{"dataset":26s} {"checked":>9s} {"rev":>5s} state flags')
|
|
153
|
+
for r in rows:
|
|
154
|
+
state = (
|
|
155
|
+
'retired'
|
|
156
|
+
if r['retired']
|
|
157
|
+
else 'missing' if r['missing'] else 'applying' if r['applying'] else 'unknown' if r['rev'] is None else 'ok'
|
|
158
|
+
)
|
|
159
|
+
age = '-' if r['age'] is None else f'{r["age"]:.0f} s'
|
|
160
|
+
print(f'{r["id"]:26s} {age:>9s} {str(r["rev"]):>5s} {state:10s} {", ".join(r["flags"])}')
|
|
161
|
+
flagged = [r for r in rows if r['flags']]
|
|
162
|
+
if flagged:
|
|
163
|
+
print(f'{len(flagged)} flagged.')
|
|
164
|
+
raise typer.Exit(1)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@app.command('allow-retires')
|
|
168
|
+
def allow_retires(config_path: str = typer.Option(None, '--config', help='The TOML (default: $ENVLIB_API_TOML).')):
|
|
169
|
+
"""After checking a blocked retire: accept the current catalogue, and allow one retire pass (within an hour)."""
|
|
170
|
+
cfg = config.load(config_path)
|
|
171
|
+
try:
|
|
172
|
+
uuid, until = mirror.allow_retires(_db(cfg))
|
|
173
|
+
except ValueError as err:
|
|
174
|
+
print(f'Refused: {err}.')
|
|
175
|
+
raise typer.Exit(1) from err
|
|
176
|
+
print(
|
|
177
|
+
f'Acknowledged catalogue uuid {uuid}; the next retire pass (before {until:%Y-%m-%d %H:%M} UTC) '
|
|
178
|
+
'ignores the cap and the empty-catalogue guard, once.'
|
|
179
|
+
)
|
envlib_api/config.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration: one TOML file, delivered as a Docker secret. Its path comes from ENVLIB_API_TOML.
|
|
3
|
+
|
|
4
|
+
[mongo]
|
|
5
|
+
uri = "mongodb://refresher:<password>@mongo:27017/envlib_api?authSource=envlib_api"
|
|
6
|
+
database = "envlib_api" # optional
|
|
7
|
+
|
|
8
|
+
[sentry]
|
|
9
|
+
dsn = "https://...@sentry.io/..." # optional, but without it nothing alerts (a loud warning says so)
|
|
10
|
+
monitor_slug = "envlib-api-refresher"
|
|
11
|
+
environment = "production"
|
|
12
|
+
|
|
13
|
+
[refresher] # every key optional; the defaults are below
|
|
14
|
+
poll_seconds = 60
|
|
15
|
+
chunk_ttl_days = 7
|
|
16
|
+
read_timeout = 20
|
|
17
|
+
retries = 2
|
|
18
|
+
max_retires_per_cycle = 2
|
|
19
|
+
value_failure_alert_cycles = 10
|
|
20
|
+
catalogue_url = "<envlib's public catalogue>"
|
|
21
|
+
|
|
22
|
+
[api] # the API (envlib-api-server); every key optional
|
|
23
|
+
max_decoded_bytes = 100_000_000 # decoded bytes of the data chunks a request touches
|
|
24
|
+
max_values = 2_000_000 # values returned (stations x time steps x parameters)
|
|
25
|
+
max_csv_rows = 500_000 # rows of a CSV response (long form: one per station and time step)
|
|
26
|
+
retry_attempts = 3 # stores built per request when a refresh overlaps it
|
|
27
|
+
retry_wait_ms = 100
|
|
28
|
+
retry_after_seconds = 60 # Retry-After of a 503 (the refresher's poll interval)
|
|
29
|
+
request_deadline_seconds = 30
|
|
30
|
+
read_timeout = 20 # B2 reads on a chunk-cache miss
|
|
31
|
+
retries = 2
|
|
32
|
+
public_url = "https://..." # optional: the base of absolute links (default: the request's)
|
|
33
|
+
|
|
34
|
+
Each service gets its own TOML: the refresher's [mongo] uri names the `refresher` user, the API's
|
|
35
|
+
the `api` user.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
import dataclasses
|
|
39
|
+
import logging
|
|
40
|
+
import os
|
|
41
|
+
import pathlib
|
|
42
|
+
import tomllib
|
|
43
|
+
|
|
44
|
+
from envlib_api import healthcheck
|
|
45
|
+
|
|
46
|
+
## envlib's public catalogue (envlib.catalogue.PUBLIC_RCG_URL). It is copied, not imported: importing
|
|
47
|
+
## envlib loads numpy, scipy, cfdb and pyproj (about 50 MB RSS) for one string. A test asserts the two
|
|
48
|
+
## are equal.
|
|
49
|
+
PUBLIC_RCG_URL = 'https://b2.envlib.xyz/file/envlib/envlib-commons/catalogue'
|
|
50
|
+
## The poll interval must leave the heartbeat (touched by a refresh, not by the sleep) fresh.
|
|
51
|
+
MAX_POLL_SECONDS = healthcheck.MAX_AGE_SECONDS // 2
|
|
52
|
+
|
|
53
|
+
logger = logging.getLogger(__name__)
|
|
54
|
+
|
|
55
|
+
ENV_VAR = 'ENVLIB_API_TOML'
|
|
56
|
+
DEFAULT_PATH = '~/.envlib/envlib-api.toml'
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclasses.dataclass(frozen=True)
|
|
60
|
+
class Config:
|
|
61
|
+
mongo_uri: str
|
|
62
|
+
database: str = 'envlib_api'
|
|
63
|
+
sentry_dsn: str | None = None
|
|
64
|
+
monitor_slug: str = 'envlib-api-refresher'
|
|
65
|
+
sentry_environment: str = 'production'
|
|
66
|
+
poll_seconds: int = 60
|
|
67
|
+
chunk_ttl_days: int = 7
|
|
68
|
+
read_timeout: int = 20
|
|
69
|
+
retries: int = 2
|
|
70
|
+
max_retires_per_cycle: int = 2
|
|
71
|
+
value_failure_alert_cycles: int = 10
|
|
72
|
+
catalogue_url: str = PUBLIC_RCG_URL
|
|
73
|
+
## [api]
|
|
74
|
+
max_decoded_bytes: int = 100_000_000
|
|
75
|
+
max_values: int = 2_000_000
|
|
76
|
+
max_csv_rows: int = 500_000
|
|
77
|
+
retry_attempts: int = 3
|
|
78
|
+
retry_wait_ms: int = 100
|
|
79
|
+
retry_after_seconds: int = 60
|
|
80
|
+
request_deadline_seconds: int = 30
|
|
81
|
+
api_read_timeout: int = 20
|
|
82
|
+
api_retries: int = 2
|
|
83
|
+
public_url: str | None = None
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def chunk_ttl_seconds(self):
|
|
87
|
+
return self.chunk_ttl_days * 86400
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
REFRESHER_KEYS = {
|
|
91
|
+
'poll_seconds',
|
|
92
|
+
'chunk_ttl_days',
|
|
93
|
+
'read_timeout',
|
|
94
|
+
'retries',
|
|
95
|
+
'max_retires_per_cycle',
|
|
96
|
+
'value_failure_alert_cycles',
|
|
97
|
+
'catalogue_url',
|
|
98
|
+
}
|
|
99
|
+
## [api] keys, and the Config field each sets (read_timeout and retries would clash with the refresher's).
|
|
100
|
+
API_KEYS = {
|
|
101
|
+
'max_decoded_bytes': 'max_decoded_bytes',
|
|
102
|
+
'max_values': 'max_values',
|
|
103
|
+
'max_csv_rows': 'max_csv_rows',
|
|
104
|
+
'retry_attempts': 'retry_attempts',
|
|
105
|
+
'retry_wait_ms': 'retry_wait_ms',
|
|
106
|
+
'retry_after_seconds': 'retry_after_seconds',
|
|
107
|
+
'request_deadline_seconds': 'request_deadline_seconds',
|
|
108
|
+
'read_timeout': 'api_read_timeout',
|
|
109
|
+
'retries': 'api_retries',
|
|
110
|
+
'public_url': 'public_url',
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def load(path=None):
|
|
115
|
+
"""Read the TOML at `path`, else $ENVLIB_API_TOML, else ~/.envlib/envlib-api.toml."""
|
|
116
|
+
path = pathlib.Path(path or os.environ.get(ENV_VAR) or DEFAULT_PATH).expanduser()
|
|
117
|
+
with open(path, 'rb') as f:
|
|
118
|
+
raw = tomllib.load(f)
|
|
119
|
+
mongo = raw.get('mongo') or {}
|
|
120
|
+
if not mongo.get('uri'):
|
|
121
|
+
raise ValueError(f'{path}: [mongo] uri is required.')
|
|
122
|
+
sentry = raw.get('sentry') or {}
|
|
123
|
+
ref = raw.get('refresher') or {}
|
|
124
|
+
unknown = sorted(set(ref) - REFRESHER_KEYS)
|
|
125
|
+
if unknown:
|
|
126
|
+
raise ValueError(f'{path}: unknown [refresher] keys {unknown}.')
|
|
127
|
+
api = raw.get('api') or {}
|
|
128
|
+
unknown = sorted(set(api) - set(API_KEYS))
|
|
129
|
+
if unknown:
|
|
130
|
+
raise ValueError(f'{path}: unknown [api] keys {unknown}.')
|
|
131
|
+
cfg = Config(
|
|
132
|
+
mongo_uri=mongo['uri'],
|
|
133
|
+
database=mongo.get('database', 'envlib_api'),
|
|
134
|
+
sentry_dsn=sentry.get('dsn'),
|
|
135
|
+
monitor_slug=sentry.get('monitor_slug', 'envlib-api-refresher'),
|
|
136
|
+
sentry_environment=sentry.get('environment', 'production'),
|
|
137
|
+
**ref,
|
|
138
|
+
**{API_KEYS[k]: v for k, v in api.items()},
|
|
139
|
+
)
|
|
140
|
+
if cfg.poll_seconds < 1 or cfg.read_timeout < 1 or cfg.retries < 0 or cfg.chunk_ttl_days < 1:
|
|
141
|
+
raise ValueError(f'{path}: poll_seconds, read_timeout and chunk_ttl_days must be >= 1, retries >= 0.')
|
|
142
|
+
api_ints = (
|
|
143
|
+
cfg.max_decoded_bytes,
|
|
144
|
+
cfg.max_values,
|
|
145
|
+
cfg.max_csv_rows,
|
|
146
|
+
cfg.retry_attempts,
|
|
147
|
+
cfg.retry_after_seconds,
|
|
148
|
+
cfg.request_deadline_seconds,
|
|
149
|
+
cfg.api_read_timeout,
|
|
150
|
+
)
|
|
151
|
+
if min(api_ints) < 1 or cfg.retry_wait_ms < 0 or cfg.api_retries < 0:
|
|
152
|
+
raise ValueError(f'{path}: the [api] caps, attempts, timeouts and deadline must be >= 1, and the waits >= 0.')
|
|
153
|
+
if cfg.poll_seconds > MAX_POLL_SECONDS:
|
|
154
|
+
raise ValueError(
|
|
155
|
+
f'{path}: poll_seconds must be <= {MAX_POLL_SECONDS}: the healthcheck fails when the heartbeat is '
|
|
156
|
+
f'older than {healthcheck.MAX_AGE_SECONDS} s, and only a refresh touches it.'
|
|
157
|
+
)
|
|
158
|
+
return cfg
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Docker HEALTHCHECK: `python -m envlib_api.healthcheck` exits 1 when the refresher's heartbeat
|
|
3
|
+
file is older than MAX_AGE_SECONDS, or missing.
|
|
4
|
+
|
|
5
|
+
The refresher touches the heartbeat after each successful refresh, and at no other time. So a
|
|
6
|
+
worker that is stalled, or whose every refresh fails, turns unhealthy, and Swarm replaces it.
|
|
7
|
+
MAX_AGE_SECONDS is above the bounded worst case of one refresh: a HEAD plus a GET, each up to
|
|
8
|
+
(retries + 1) x read_timeout plus backoff, which is about 2 min at the defaults (20 s, 2 retries).
|
|
9
|
+
|
|
10
|
+
Deliberately light: stdlib only, because it runs every 30 s.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
HEARTBEAT_PATH = os.environ.get('ENVLIB_API_HEARTBEAT', '/tmp/envlib-api-heartbeat') # the env var is for tests
|
|
18
|
+
MAX_AGE_SECONDS = 300
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def age(path=HEARTBEAT_PATH):
|
|
22
|
+
"""Seconds since the heartbeat was touched, or None if it was never touched."""
|
|
23
|
+
try:
|
|
24
|
+
return time.time() - os.stat(path).st_mtime
|
|
25
|
+
except FileNotFoundError:
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(path=None):
|
|
30
|
+
a = age(path or HEARTBEAT_PATH)
|
|
31
|
+
if a is None or a > MAX_AGE_SECONDS:
|
|
32
|
+
print(f'unhealthy: heartbeat {"missing" if a is None else f"{a:.0f} s old"} (limit {MAX_AGE_SECONDS} s)')
|
|
33
|
+
return 1
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
if __name__ == '__main__':
|
|
38
|
+
sys.exit(main())
|