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,808 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The API against real ts_ortho datasets (see api_support.py): every answer is compared with a
|
|
3
|
+
direct cfdb read of the same remote, on the stored quantity (round(x * 10**p)), and with the
|
|
4
|
+
producer's own input. Time windows are selected on the oracle's side by a boolean mask, never by
|
|
5
|
+
the code under test.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import csv
|
|
9
|
+
import datetime
|
|
10
|
+
import gzip
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import threading
|
|
17
|
+
|
|
18
|
+
import boto3
|
|
19
|
+
import cfdb
|
|
20
|
+
import numpy as np
|
|
21
|
+
import orjson
|
|
22
|
+
import pymongo
|
|
23
|
+
import pyproj
|
|
24
|
+
import pytest
|
|
25
|
+
import s3func
|
|
26
|
+
import zstandard
|
|
27
|
+
from ebooklet.mongo import CHUNKS, DATASETS, ENTRIES, MongoStore
|
|
28
|
+
from ebooklet.mongo.schema import chunk_id
|
|
29
|
+
from fastapi.testclient import TestClient
|
|
30
|
+
from pymongo.errors import OperationFailure
|
|
31
|
+
|
|
32
|
+
from envlib_api import mirror as mirror_mod
|
|
33
|
+
from envlib_api.api import cost, read, resolve
|
|
34
|
+
from envlib_api.api.app import check_role, create_app
|
|
35
|
+
from envlib_api.tests.api_support import HOUR, POLY_EDGE, STATIONS, T0, api_config
|
|
36
|
+
from envlib_api.tests.support import user_uri
|
|
37
|
+
|
|
38
|
+
IDENTITY = {'Accept-Encoding': 'identity'}
|
|
39
|
+
PRECISION = {'sf': 4, 'gh': 3, 'pv1': 1, 'pv2': 1}
|
|
40
|
+
VAR = {'sf': 'streamflow', 'gh': 'gage_height', 'pv1': 'precipitation', 'pv2': 'precipitation'}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def client(m, **cfg):
|
|
44
|
+
return TestClient(create_app(api_config(**cfg), db=m.adb), headers=IDENTITY)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def stored(x, p):
|
|
48
|
+
"""The stored quantity: round(x * 10**p), NaN kept."""
|
|
49
|
+
x = np.asarray(x, dtype='float64')
|
|
50
|
+
return np.where(np.isnan(x), np.nan, np.rint(x * 10.0**p))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def same(a, b):
|
|
54
|
+
a, b = np.asarray(a, dtype='float64'), np.asarray(b, dtype='float64')
|
|
55
|
+
return a.shape == b.shape and bool(np.all((a == b) | (np.isnan(a) & np.isnan(b))))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def json_values(values):
|
|
59
|
+
return np.array([np.nan if v is None else v for v in values], dtype='float64')
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def mask_window(times, start=None, end=None):
|
|
63
|
+
"""The oracle: positions whose label t has start <= t <= end, by a boolean mask."""
|
|
64
|
+
t = times.astype('datetime64[us]')
|
|
65
|
+
ok = np.ones(len(t), dtype=bool)
|
|
66
|
+
if start is not None:
|
|
67
|
+
ok &= t >= np.datetime64(start, 'us')
|
|
68
|
+
if end is not None:
|
|
69
|
+
ok &= t <= np.datetime64(end, 'us')
|
|
70
|
+
return np.nonzero(ok)[0]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def direct_series(world, name, var, refs, idx):
|
|
74
|
+
"""{ref: values at positions idx} and the times, read directly (cfdb.open_edataset on the remote)."""
|
|
75
|
+
with world.direct(name) as ds:
|
|
76
|
+
all_refs = [str(r) for r in ds['station_ref'].data]
|
|
77
|
+
times = ds['time'].data[idx] if len(idx) else ds['time'].data[:0]
|
|
78
|
+
out = {}
|
|
79
|
+
for ref in refs:
|
|
80
|
+
i = all_refs.index(ref)
|
|
81
|
+
row = ds[var][i, :].data[0]
|
|
82
|
+
out[ref] = row[idx]
|
|
83
|
+
ids = {ref: str(ds['station_id'].data[all_refs.index(ref)]) for ref in refs}
|
|
84
|
+
return out, times, ids
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def all_times(world, name):
|
|
88
|
+
with world.direct(name) as ds:
|
|
89
|
+
return ds['time'].data
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def iso(t):
|
|
93
|
+
return [str(x) + 'Z' for x in np.datetime_as_string(t.astype('datetime64[s]'), unit='s')]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def cid(m, name):
|
|
97
|
+
return m.world.dataset_id[name]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def station_id(m, name, ref):
|
|
101
|
+
with m.world.direct(name) as ds:
|
|
102
|
+
refs = [str(r) for r in ds['station_ref'].data]
|
|
103
|
+
return str(ds['station_id'].data[refs.index(ref)])
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ── metadata ─────────────────────────────────────────────────────────────────────────────────────
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_landing_conformance_and_collections_list_the_station_collections(mirror):
|
|
110
|
+
c = client(mirror)
|
|
111
|
+
land = c.get('/').json()
|
|
112
|
+
assert {link['rel'] for link in land['links']} >= {'service-desc', 'conformance', 'data'}
|
|
113
|
+
conf = c.get('/conformance').json()['conformsTo']
|
|
114
|
+
assert 'https://www.opengis.net/spec/ogcapi-edr-1/1.2/conf/core' in conf
|
|
115
|
+
assert not any(c.endswith('/oas31') or c.endswith('/oas30') for c in conf) # /api documents no query parameters yet
|
|
116
|
+
assert c.get('/api').json()['openapi'].startswith('3.1')
|
|
117
|
+
cols = c.get('/collections').json()['collections']
|
|
118
|
+
assert sorted(col['id'] for col in cols) == sorted({cid(mirror, n) for n in ('sf', 'gh', 'pv1')})
|
|
119
|
+
gh = next(col for col in cols if col['id'] == cid(mirror, 'gh'))
|
|
120
|
+
assert set(gh['parameter_names']) == {'gage_height', 'quality_code'}
|
|
121
|
+
assert gh['parameter_names']['gage_height']['measurementType'] == {'method': 'mean', 'duration': 'PT1H'}
|
|
122
|
+
assert gh['parameter_names']['gage_height']['unit']['symbol'] == 'm'
|
|
123
|
+
assert all(p['type'] == 'Parameter' for p in gh['parameter_names'].values()) # EDR A.24 text, not the schema
|
|
124
|
+
assert gh['crs'] == ['CRS84'] and gh['extent']['spatial']['bbox'] == [gh['envlib']['bbox']]
|
|
125
|
+
radius = gh['data_queries']['radius']['link']['variables']
|
|
126
|
+
assert radius['within_units'] == ['km', 'm'] and radius['crs_details'][0]['crs'] == 'CRS84'
|
|
127
|
+
assert set(radius) >= {'title', 'description', 'query_type', 'output_formats', 'default_output_format'}
|
|
128
|
+
assert any(link['rel'] == 'license' and 'spdx.org' in link['href'] for link in gh['links'])
|
|
129
|
+
assert gh['envlib']['dataset_version_id'] == mirror.world.dvid['gh']
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_the_served_version_is_the_latest_by_created_at_as_envlib_chooses(mirror):
|
|
133
|
+
"""pv1 was re-published last (newest ts) but pv2 was created later: pv2 is served."""
|
|
134
|
+
docs = {d['_id']: d for d in mirror.adb['catalogue'].find({'dataset_id': cid(mirror, 'pv1')})}
|
|
135
|
+
assert docs[mirror.world.dvid['pv1']]['ts'] > docs[mirror.world.dvid['pv2']]['ts'], 'the fixture lost its premise'
|
|
136
|
+
r = client(mirror).get(f'/collections/{cid(mirror, "pv2")}')
|
|
137
|
+
assert r.status_code == 200 and r.headers['etag'].startswith(f'"{mirror.world.dvid["pv2"]}-')
|
|
138
|
+
envlib_choice = mirror.world.catalogue().query(dataset_id=cid(mirror, 'pv2'))
|
|
139
|
+
assert [ref.dataset_version_id for ref in envlib_choice] == [mirror.world.dvid['pv2']]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_locations_lists_every_station_as_edr_geojson(mirror):
|
|
143
|
+
r = client(mirror).get(f'/collections/{cid(mirror, "sf")}/locations')
|
|
144
|
+
assert r.status_code == 200 and r.headers['content-type'] == 'application/geo+json'
|
|
145
|
+
feats = r.json()['features']
|
|
146
|
+
with mirror.world.direct('sf') as ds:
|
|
147
|
+
ids = [str(x) for x in ds['station_id'].data]
|
|
148
|
+
refs = [str(x) for x in ds['station_ref'].data]
|
|
149
|
+
pts = ds['point'].data
|
|
150
|
+
assert [f['id'] for f in feats] == ids
|
|
151
|
+
assert [f['properties']['station_ref'] for f in feats] == refs
|
|
152
|
+
assert [f['geometry']['coordinates'] for f in feats] == [[p.x, p.y] for p in pts]
|
|
153
|
+
assert all({'label', 'datetime', 'parameter-name', 'edrqueryendpoint'} <= set(f['properties']) for f in feats)
|
|
154
|
+
meta = mirror.adb['catalogue'].find_one({'_id': mirror.world.dvid['sf']})['user_meta']
|
|
155
|
+
for f in feats:
|
|
156
|
+
assert f['properties']['edrqueryendpoint'].endswith(f'/collections/{cid(mirror, "sf")}/locations/{f["id"]}')
|
|
157
|
+
assert f['properties']['datetime'] == f'{meta["time_start"]}/{meta["time_end"]}'
|
|
158
|
+
assert f['properties']['parameter-name'] == ['streamflow']
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ── data: equality with direct reads ─────────────────────────────────────────────────────────────
|
|
162
|
+
|
|
163
|
+
WINDOWS = [
|
|
164
|
+
('2020-01-01T05:00Z/2020-01-01T09:00Z', '2020-01-01T05:00', '2020-01-01T09:00'), # on-step
|
|
165
|
+
('2020-01-01T05:30Z/2020-01-01T10:30Z', '2020-01-01T05:30', '2020-01-01T10:30'), # off-step ends
|
|
166
|
+
('2020-01-01T20:00Z/2020-01-02T04:00Z', '2020-01-01T20:00', '2020-01-02T04:00'), # crosses a chunk boundary
|
|
167
|
+
('../2020-01-01T03:00Z', None, '2020-01-01T03:00'), # open start
|
|
168
|
+
('2020-01-04T20:00Z/..', '2020-01-04T20:00', None), # open end
|
|
169
|
+
('2020-01-01T17:00+12:00/2020-01-01T21:00+12:00', '2020-01-01T05:00', '2020-01-01T09:00'), # offsets
|
|
170
|
+
('2020-01-01T05:00/2020-01-01T09:00', '2020-01-01T05:00', '2020-01-01T09:00'), # naive = UTC
|
|
171
|
+
('2020-01-01T07:00Z', '2020-01-01T07:00', '2020-01-01T07:00'), # instant on a step
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@pytest.mark.parametrize('dt,start,end', WINDOWS, ids=[w[0] for w in WINDOWS])
|
|
176
|
+
@pytest.mark.parametrize('name,ref', [('sf', 'A'), ('sf', 'B'), ('sf', 'C'), ('gh', 'D')])
|
|
177
|
+
def test_one_location_equals_a_direct_read_and_the_producer_input(mirror, name, ref, dt, start, end):
|
|
178
|
+
w = mirror.world
|
|
179
|
+
var, p = VAR[name], PRECISION[name]
|
|
180
|
+
idx = mask_window(all_times(w, name), start, end)
|
|
181
|
+
exp, exp_t, ids = direct_series(w, name, var, [ref], idx)
|
|
182
|
+
c = client(mirror)
|
|
183
|
+
r = c.get(f'/collections/{cid(mirror, name)}/locations/{ids[ref]}', params={'datetime': dt})
|
|
184
|
+
assert r.status_code == 200, r.text
|
|
185
|
+
cov = r.json()
|
|
186
|
+
assert cov['type'] == 'Coverage' and cov['domain']['domainType'] == 'PointSeries' and cov['id'] == ids[ref]
|
|
187
|
+
assert cov['domain']['axes']['t']['values'] == iso(exp_t)
|
|
188
|
+
assert cov['domain']['axes']['x']['values'] == [STATIONS[ref]['lon']]
|
|
189
|
+
got = json_values(cov['ranges'][var]['values'])
|
|
190
|
+
assert same(stored(got, p), stored(exp[ref], p))
|
|
191
|
+
## Independent of cfdb's decode: the producer's input, quantised the way it was stored.
|
|
192
|
+
in_t, in_v = w.inputs[name][ref][:2]
|
|
193
|
+
pos = {t: k for k, t in enumerate(in_t)}
|
|
194
|
+
want = np.array([in_v[pos[t]] if t in pos else np.nan for t in exp_t])
|
|
195
|
+
if name == 'gh': # the 30 prepended steps are not in the build input
|
|
196
|
+
early = dict(zip(np.arange(T0 - HOUR * 30, T0, HOUR), w.gh_early[2], strict=True))
|
|
197
|
+
want = np.array([early.get(t, x) for t, x in zip(exp_t, want, strict=True)])
|
|
198
|
+
assert same(stored(got, p), stored(want, p))
|
|
199
|
+
## CSV: the same values, at exactly p decimals, empty for NaN.
|
|
200
|
+
rc = c.get(f'/collections/{cid(mirror, name)}/locations/{ids[ref]}', params={'datetime': dt, 'f': 'CSV'})
|
|
201
|
+
rows = list(csv.reader(io.StringIO(rc.text)))
|
|
202
|
+
head, body = rows[0], rows[1:]
|
|
203
|
+
k = head.index(var)
|
|
204
|
+
assert [row[head.index('time')] for row in body] == iso(exp_t)
|
|
205
|
+
assert all(row[k] == '' or re.fullmatch(rf'-?\d+\.\d{{{p}}}', row[k]) for row in body)
|
|
206
|
+
csv_vals = np.array([float(row[k]) if row[k] else np.nan for row in body])
|
|
207
|
+
assert same(stored(csv_vals, p), stored(exp[ref], p))
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_the_prepended_steps_of_a_negative_origin_are_served(mirror):
|
|
211
|
+
"""gh's time axis starts 30 steps before the build (origin -30): those steps are readable."""
|
|
212
|
+
w = mirror.world
|
|
213
|
+
sid = station_id(mirror, 'gh', 'A')
|
|
214
|
+
r = client(mirror).get(
|
|
215
|
+
f'/collections/{cid(mirror, "gh")}/locations/{sid}', params={'datetime': '2019-12-30T18:00Z/2019-12-31T02:00Z'}
|
|
216
|
+
)
|
|
217
|
+
got = json_values(r.json()['ranges']['gage_height']['values'])
|
|
218
|
+
assert same(stored(got, 3), stored(w.gh_early[0][:9], 3))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@pytest.mark.parametrize(
|
|
222
|
+
'dt',
|
|
223
|
+
[
|
|
224
|
+
'2020-01-01T07:30Z',
|
|
225
|
+
'2019-01-01T00:00Z',
|
|
226
|
+
'2021-01-01T00:00Z',
|
|
227
|
+
'2020-01-01T05:10Z/2020-01-01T05:50Z',
|
|
228
|
+
'2021-01-01T00:00Z/..',
|
|
229
|
+
],
|
|
230
|
+
)
|
|
231
|
+
def test_a_query_that_selects_no_time_step_answers_204(mirror, dt):
|
|
232
|
+
sid = station_id(mirror, 'sf', 'A')
|
|
233
|
+
r = client(mirror).get(f'/collections/{cid(mirror, "sf")}/locations/{sid}', params={'datetime': dt})
|
|
234
|
+
assert r.status_code == 204 and r.content == b'' and r.headers['vary'] == 'Accept-Encoding'
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def test_the_all_nan_window_of_a_station_is_null_in_json_and_empty_in_csv(mirror):
|
|
238
|
+
sid = station_id(mirror, 'sf', 'B')
|
|
239
|
+
c = client(mirror)
|
|
240
|
+
params = {'datetime': '2020-01-02T06:00Z/2020-01-02T11:00Z'} # steps 30..35
|
|
241
|
+
vals = c.get(f'/collections/{cid(mirror, "sf")}/locations/{sid}', params=params).json()['ranges']['streamflow'][
|
|
242
|
+
'values'
|
|
243
|
+
]
|
|
244
|
+
assert vals == [None] * 6
|
|
245
|
+
body = (
|
|
246
|
+
c.get(f'/collections/{cid(mirror, "sf")}/locations/{sid}', params={**params, 'f': 'CSV'})
|
|
247
|
+
.text.strip()
|
|
248
|
+
.split('\n')[1:]
|
|
249
|
+
)
|
|
250
|
+
assert all(line.endswith(',') for line in body)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def test_values_are_printed_at_the_declared_precision(mirror):
|
|
254
|
+
"""cfdb's decode offset prints float32 noise (0.4840002) at shortest round-trip; the API must not."""
|
|
255
|
+
r = client(mirror).get(
|
|
256
|
+
f'/collections/{cid(mirror, "gh")}/area',
|
|
257
|
+
params={
|
|
258
|
+
'coords': POLY_EDGE.replace('-44,', '-42,').replace('-44)', '-42)').replace('-45', '-46'),
|
|
259
|
+
'datetime': '2019-12-30T18:00Z/..',
|
|
260
|
+
},
|
|
261
|
+
)
|
|
262
|
+
assert r.status_code == 200
|
|
263
|
+
texts = re.findall(rb'"values":\[([^\]]*)\]', r.content)
|
|
264
|
+
numbers = [n for t in texts for n in t.split(b',') if n and n != b'null' and not n.startswith(b'"')]
|
|
265
|
+
assert numbers
|
|
266
|
+
decimals = [len(n.split(b'.')[1]) if b'.' in n else 0 for n in numbers]
|
|
267
|
+
assert max(decimals) <= 3, sorted(set(decimals))
|
|
268
|
+
with mirror.world.direct('gh') as ds:
|
|
269
|
+
raw = ds['gage_height'][:, :].data
|
|
270
|
+
noisy = [v for v in raw.ravel()[:200] if v == v and len(repr(float(np.float32(v))).split('.')[1]) > 3]
|
|
271
|
+
assert noisy, 'the fixture has no decode noise, so this test would pass vacuously'
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# ── data: area and radius ───────────────────────────────────────────────────────────────────────
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _coverage_ids(r):
|
|
278
|
+
body = r.json()
|
|
279
|
+
assert body['type'] == 'CoverageCollection'
|
|
280
|
+
return [cov['id'] for cov in body['coverages']]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def test_area_includes_a_station_on_the_boundary_and_keeps_dataset_order(mirror):
|
|
284
|
+
r = client(mirror).get(
|
|
285
|
+
f'/collections/{cid(mirror, "sf")}/area', params={'coords': POLY_EDGE, 'datetime': '2020-01-01T00:00Z'}
|
|
286
|
+
)
|
|
287
|
+
assert _coverage_ids(r) == [station_id(mirror, 'sf', ref) for ref in ('D', 'E')]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@pytest.mark.parametrize(
|
|
291
|
+
'poly',
|
|
292
|
+
['POLYGON((183 -45,184 -45,184 -43,183 -43,183 -45))', 'POLYGON((-177 -45,-176 -45,-176 -43,-177 -43,-177 -45))'],
|
|
293
|
+
ids=['0-360', '-180-180'],
|
|
294
|
+
)
|
|
295
|
+
def test_area_finds_the_chatham_station_in_either_longitude_convention(mirror, poly):
|
|
296
|
+
r = client(mirror).get(
|
|
297
|
+
f'/collections/{cid(mirror, "sf")}/area', params={'coords': poly, 'datetime': '2020-01-01T00:00Z'}
|
|
298
|
+
)
|
|
299
|
+
assert _coverage_ids(r) == [station_id(mirror, 'sf', 'C')]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def test_area_and_radius_values_equal_direct_reads(mirror):
|
|
303
|
+
w = mirror.world
|
|
304
|
+
window = ('2020-01-01T22:00Z/2020-01-02T03:00Z', '2020-01-01T22:00', '2020-01-02T03:00')
|
|
305
|
+
idx = mask_window(all_times(w, 'gh'), window[1], window[2])
|
|
306
|
+
exp, exp_t, ids = direct_series(w, 'gh', 'quality_code', ['A', 'B', 'D'], idx)
|
|
307
|
+
r = client(mirror).get(
|
|
308
|
+
f'/collections/{cid(mirror, "gh")}/radius',
|
|
309
|
+
params={
|
|
310
|
+
'coords': 'POINT(172.5 -43.5)',
|
|
311
|
+
'within': '200',
|
|
312
|
+
'within-units': 'km',
|
|
313
|
+
'datetime': window[0],
|
|
314
|
+
'parameter-name': 'quality_code',
|
|
315
|
+
},
|
|
316
|
+
)
|
|
317
|
+
body = r.json()
|
|
318
|
+
assert set(body['parameters']) == {'quality_code'}
|
|
319
|
+
by_id = {cov['id']: cov for cov in body['coverages']}
|
|
320
|
+
assert list(by_id) == [ids[k] for k in ('A', 'B', 'D')]
|
|
321
|
+
for ref in ('A', 'B', 'D'):
|
|
322
|
+
cov = by_id[ids[ref]]
|
|
323
|
+
assert cov['domain']['axes']['t']['values'] == iso(exp_t)
|
|
324
|
+
assert same(stored(json_values(cov['ranges']['quality_code']['values']), 0), stored(exp[ref], 0))
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
@pytest.mark.parametrize('km', [0, 30, 60, 100])
|
|
328
|
+
def test_radius_selects_by_great_circle_distance(mirror, km):
|
|
329
|
+
geod = pyproj.Geod(ellps='WGS84')
|
|
330
|
+
refs = list(STATIONS)
|
|
331
|
+
_, _, d = geod.inv(
|
|
332
|
+
[172.5] * len(refs), [-43.5] * len(refs), [STATIONS[r]['lon'] for r in refs], [STATIONS[r]['lat'] for r in refs]
|
|
333
|
+
)
|
|
334
|
+
want = [station_id(mirror, 'sf', ref) for ref, dist in zip(refs, d, strict=True) if dist <= km * 1000]
|
|
335
|
+
c = client(mirror)
|
|
336
|
+
base = {'coords': 'POINT(172.5 -43.5)', 'datetime': '2020-01-01T00:00Z'}
|
|
337
|
+
r_km = c.get(f'/collections/{cid(mirror, "sf")}/radius', params={**base, 'within': str(km), 'within-units': 'km'})
|
|
338
|
+
r_m = c.get(
|
|
339
|
+
f'/collections/{cid(mirror, "sf")}/radius', params={**base, 'within': str(km * 1000), 'within-units': 'm'}
|
|
340
|
+
)
|
|
341
|
+
for r in (r_km, r_m):
|
|
342
|
+
assert (r.status_code == 204 and want == []) or _coverage_ids(r) == want
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# ── parameters and errors ───────────────────────────────────────────────────────────────────────
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@pytest.mark.parametrize(
|
|
349
|
+
'path,params,status',
|
|
350
|
+
[
|
|
351
|
+
('locations/{A}', {'bogus': '1'}, 400),
|
|
352
|
+
('locations/{A}', {'datetime': '2020-01-01T00:00Z,2020-01-01T01:00Z'}, 400),
|
|
353
|
+
('locations/{A}', {'datetime': 'yesterday'}, 400),
|
|
354
|
+
('locations/{A}', {'datetime': '2020-01-02T00:00Z/2020-01-01T00:00Z'}, 400),
|
|
355
|
+
('locations/{A}', {'f': 'netCDF'}, 400),
|
|
356
|
+
('locations/{A}', {'crs': 'EPSG:2193'}, 400),
|
|
357
|
+
('locations/{A}', {'parameter-name': 'nope'}, 400),
|
|
358
|
+
('area', {}, 400),
|
|
359
|
+
('area', {'coords': 'POLYGON((1 2'}, 400),
|
|
360
|
+
('area', {'coords': 'POINT(172 -43)'}, 400),
|
|
361
|
+
('radius', {'coords': 'POINT(172 -43)', 'within': '5'}, 400),
|
|
362
|
+
('radius', {'coords': 'POINT(172 -43)', 'within': '5', 'within-units': 'mi'}, 400),
|
|
363
|
+
('radius', {'coords': 'POINT(172 -43)', 'within': '-1', 'within-units': 'km'}, 400),
|
|
364
|
+
('locations/nope', {}, 404),
|
|
365
|
+
],
|
|
366
|
+
)
|
|
367
|
+
def test_invalid_requests_answer_400_and_unknown_locations_404(mirror, path, params, status):
|
|
368
|
+
url = f'/collections/{cid(mirror, "sf")}/' + path.format(A=station_id(mirror, 'sf', 'A'))
|
|
369
|
+
r = client(mirror).get(url, params=params)
|
|
370
|
+
assert r.status_code == status, r.text
|
|
371
|
+
assert set(r.json()) >= {'code', 'description'}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def test_a_repeated_parameter_answers_400(mirror):
|
|
375
|
+
url = f'/collections/{cid(mirror, "sf")}/locations/{station_id(mirror, "sf", "A")}'
|
|
376
|
+
r = client(mirror).get(url + '?datetime=2020-01-01T00:00Z&datetime=2020-01-01T01:00Z')
|
|
377
|
+
assert r.status_code == 400 and 'more than once' in r.json()['description']
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def test_an_unknown_collection_answers_404(mirror):
|
|
381
|
+
c = client(mirror)
|
|
382
|
+
for path in (
|
|
383
|
+
'/collections/nope',
|
|
384
|
+
'/collections/nope/locations',
|
|
385
|
+
'/collections/nope/area?coords=POLYGON((0 0,1 0,1 1,0 0))',
|
|
386
|
+
):
|
|
387
|
+
assert c.get(path).status_code == 404
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ── compression ─────────────────────────────────────────────────────────────────────────────────
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
@pytest.mark.parametrize(
|
|
394
|
+
'accept,coding',
|
|
395
|
+
[
|
|
396
|
+
('gzip, deflate, zstd', 'zstd'),
|
|
397
|
+
('gzip, deflate', 'gzip'),
|
|
398
|
+
('zstd;q=0, gzip', 'gzip'),
|
|
399
|
+
('gzip;q=0.2, zstd;q=0.5', 'zstd'),
|
|
400
|
+
('zstd;q=0.1, gzip;q=0.9', 'gzip'),
|
|
401
|
+
('identity', None),
|
|
402
|
+
('*', 'zstd'),
|
|
403
|
+
('zstd;q=0, gzip;q=0', None),
|
|
404
|
+
('ZSTD, GZIP', 'zstd'),
|
|
405
|
+
],
|
|
406
|
+
)
|
|
407
|
+
def test_compression_is_negotiated_and_decodes_to_the_same_body(mirror, accept, coding):
|
|
408
|
+
url = f'/collections/{cid(mirror, "sf")}/area'
|
|
409
|
+
params = {'coords': POLY_EDGE, 'datetime': '2020-01-01T00:00Z/2020-01-02T00:00Z'}
|
|
410
|
+
c = client(mirror)
|
|
411
|
+
plain = c.get(url, params=params).content
|
|
412
|
+
r = c.get(url, params=params, headers={'Accept-Encoding': accept})
|
|
413
|
+
assert r.headers.get('content-encoding') == coding and 'Accept-Encoding' in r.headers['vary']
|
|
414
|
+
assert r.content == plain # httpx decodes gzip and (with zstandard installed) zstd
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def test_the_wire_body_is_really_compressed(mirror):
|
|
418
|
+
"""Read the raw bytes (no client-side decoding) and decode them ourselves."""
|
|
419
|
+
app = create_app(api_config(), db=mirror.adb)
|
|
420
|
+
url = f'/collections/{cid(mirror, "sf")}/area'
|
|
421
|
+
params = {'coords': POLY_EDGE, 'datetime': '2020-01-01T00:00Z/2020-01-02T00:00Z'}
|
|
422
|
+
with TestClient(app) as c:
|
|
423
|
+
plain = c.get(url, params=params, headers=IDENTITY).content
|
|
424
|
+
for accept, decode in (('zstd', zstandard.ZstdDecompressor().decompress), ('gzip', gzip.decompress)):
|
|
425
|
+
with c.stream('GET', url, params=params, headers={'Accept-Encoding': accept}) as r:
|
|
426
|
+
wire = b''.join(r.iter_raw())
|
|
427
|
+
assert len(wire) < len(plain) and decode(wire) == plain
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
# ── caps ────────────────────────────────────────────────────────────────────────────────────────
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
class KeySpy:
|
|
434
|
+
"""Records every key MongoStore is asked to load, and every data key it is asked for."""
|
|
435
|
+
|
|
436
|
+
def __init__(self, monkeypatch):
|
|
437
|
+
self.loaded, self.fills = [], []
|
|
438
|
+
real_load, real_fill = MongoStore.load_items, MongoStore._fill
|
|
439
|
+
spy = self
|
|
440
|
+
|
|
441
|
+
def load_items(store, keys=None):
|
|
442
|
+
keys = list(keys)
|
|
443
|
+
spy.loaded.append(keys)
|
|
444
|
+
return real_load(store, keys)
|
|
445
|
+
|
|
446
|
+
def _fill(store, keys):
|
|
447
|
+
spy.fills.append(list(keys))
|
|
448
|
+
return real_fill(store, keys)
|
|
449
|
+
|
|
450
|
+
monkeypatch.setattr(MongoStore, 'load_items', load_items)
|
|
451
|
+
monkeypatch.setattr(MongoStore, '_fill', _fill)
|
|
452
|
+
|
|
453
|
+
def data_keys(self, var):
|
|
454
|
+
return [k for ks in self.loaded for k in ks if k.startswith(f'{var}!')]
|
|
455
|
+
|
|
456
|
+
def data_fills(self, var):
|
|
457
|
+
return [ks for ks in self.fills if any(k.startswith(f'{var}!') for k in ks)]
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
@pytest.mark.parametrize('cap,field', [('max_values', 'values returned'), ('max_csv_rows', 'CSV rows')])
|
|
461
|
+
def test_one_over_a_values_cap_is_413_and_reads_no_data(mirror, monkeypatch, cap, field):
|
|
462
|
+
url = f'/collections/{cid(mirror, "sf")}/area'
|
|
463
|
+
params = {
|
|
464
|
+
'coords': POLY_EDGE,
|
|
465
|
+
'datetime': '2020-01-01T00:00Z/2020-01-01T09:00Z',
|
|
466
|
+
'f': 'CSV',
|
|
467
|
+
} # 2 stations x 10 steps
|
|
468
|
+
assert client(mirror, **{cap: 20}).get(url, params=params).status_code == 200
|
|
469
|
+
spy = KeySpy(monkeypatch)
|
|
470
|
+
r = client(mirror, **{cap: 19}).get(url, params=params)
|
|
471
|
+
assert r.status_code == 413
|
|
472
|
+
body = r.json()
|
|
473
|
+
assert body['limits'] == [{'limit': field, 'requested': 20, 'max': 19}]
|
|
474
|
+
assert body['dataset_version_id'] == mirror.world.dvid['sf'] and body['db_url'] == mirror.world.conn('sf').db_url
|
|
475
|
+
assert mirror.world.dvid['sf'] in body['envlib_snippet']
|
|
476
|
+
assert spy.data_keys('streamflow') == [] and spy.data_fills('streamflow') == []
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def test_one_over_the_bytes_cap_is_413(mirror):
|
|
480
|
+
"""2 stations x a window crossing one boundary = 4 chunks of 24 float32 = 384 bytes."""
|
|
481
|
+
url = f'/collections/{cid(mirror, "sf")}/area'
|
|
482
|
+
params = {'coords': POLY_EDGE, 'datetime': '2020-01-01T20:00Z/2020-01-02T04:00Z'}
|
|
483
|
+
assert client(mirror, max_decoded_bytes=384).get(url, params=params).status_code == 200
|
|
484
|
+
r = client(mirror, max_decoded_bytes=383).get(url, params=params)
|
|
485
|
+
assert r.status_code == 413 and r.json()['limits'] == [
|
|
486
|
+
{'limit': 'decoded bytes touched', 'requested': 384, 'max': 383}
|
|
487
|
+
]
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
@pytest.mark.parametrize('name', ['sf', 'gh'])
|
|
491
|
+
@pytest.mark.parametrize('a,b', [(0, 1), (0, 24), (5, 30), (23, 25), (20, 100), (0, 100), (29, 31), (60, 130)])
|
|
492
|
+
def test_the_key_list_equals_the_keys_cfdb_itself_asks_for(mirror, monkeypatch, name, a, b):
|
|
493
|
+
"""Including gh's negative time origin, where dropping the origin changes the chunk count."""
|
|
494
|
+
spy = KeySpy(monkeypatch)
|
|
495
|
+
store = MongoStore(mirror.adb, mirror.world.dvid[name], http_session=s3func.HttpSession(stream=False))
|
|
496
|
+
with cfdb.open_store_dataset(store) as ds:
|
|
497
|
+
n = ds['time'].shape[0]
|
|
498
|
+
a, b = min(a, n - 1), min(b, n)
|
|
499
|
+
var = VAR[name]
|
|
500
|
+
mine = cost.data_keys(ds, [var], [0, 2], a, b)[var]
|
|
501
|
+
spy.loaded.clear()
|
|
502
|
+
for i in (0, 2):
|
|
503
|
+
_ = ds[var][i, a:b].data
|
|
504
|
+
theirs = list(dict.fromkeys(spy.data_keys(var)))
|
|
505
|
+
assert sorted(mine) == sorted(theirs)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def test_one_batched_fetch_serves_every_station(mirror, monkeypatch):
|
|
509
|
+
spy = KeySpy(monkeypatch)
|
|
510
|
+
r = client(mirror).get(
|
|
511
|
+
f'/collections/{cid(mirror, "sf")}/area',
|
|
512
|
+
params={
|
|
513
|
+
'coords': 'POLYGON((160 -50,180 -50,180 -40,160 -40,160 -50))',
|
|
514
|
+
'datetime': '2020-01-01T20:00Z/2020-01-02T04:00Z',
|
|
515
|
+
},
|
|
516
|
+
)
|
|
517
|
+
assert len(_coverage_ids(r)) == 4
|
|
518
|
+
assert len(spy.data_fills('streamflow')) == 1, spy.data_fills('streamflow')
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
# ── consistency (each test on its own mirror) ───────────────────────────────────────────────────
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _sf_url(m):
|
|
525
|
+
return f'/collections/{cid(m, "sf")}/locations/{station_id(m, "sf", "A")}'
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def test_a_store_refused_while_applying_is_retried_and_then_served(fresh_mirror):
|
|
529
|
+
m = fresh_mirror
|
|
530
|
+
dvid = m.world.dvid['sf']
|
|
531
|
+
m.admin[DATASETS].update_one({'_id': dvid}, {'$set': {'applying': True}})
|
|
532
|
+
timer = threading.Timer(0.05, lambda: m.admin[DATASETS].update_one({'_id': dvid}, {'$set': {'applying': False}}))
|
|
533
|
+
timer.start()
|
|
534
|
+
try:
|
|
535
|
+
r = client(m, retry_wait_ms=100, retry_attempts=3).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z'})
|
|
536
|
+
finally:
|
|
537
|
+
timer.join()
|
|
538
|
+
assert r.status_code == 200
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def test_a_store_held_past_the_attempts_answers_503_with_retry_after(fresh_mirror):
|
|
542
|
+
m = fresh_mirror
|
|
543
|
+
m.admin[DATASETS].update_one({'_id': m.world.dvid['sf']}, {'$set': {'applying': True}})
|
|
544
|
+
r = client(m, retry_attempts=3, retry_after_seconds=60).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z'})
|
|
545
|
+
assert r.status_code == 503 and r.headers['retry-after'] == '60'
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _bump_rev_on_read(m, monkeypatch, times):
|
|
549
|
+
real = read.read_values
|
|
550
|
+
calls = []
|
|
551
|
+
|
|
552
|
+
def bumping(attempt, *args, **kwargs):
|
|
553
|
+
out = real(attempt, *args, **kwargs)
|
|
554
|
+
calls.append(attempt.store)
|
|
555
|
+
if len(calls) <= times:
|
|
556
|
+
m.admin[DATASETS].update_one({'_id': attempt.doc['_id']}, {'$inc': {'rev': 1}})
|
|
557
|
+
return out
|
|
558
|
+
|
|
559
|
+
monkeypatch.setattr(read, 'read_values', bumping)
|
|
560
|
+
return calls
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def test_a_commit_applied_during_the_request_is_retried_with_a_new_store(fresh_mirror, monkeypatch):
|
|
564
|
+
m = fresh_mirror
|
|
565
|
+
calls = _bump_rev_on_read(m, monkeypatch, times=1)
|
|
566
|
+
r = client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'})
|
|
567
|
+
assert r.status_code == 200 and len(calls) == 2 and calls[0] is not calls[1]
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def test_commits_applied_during_every_attempt_answer_503(fresh_mirror, monkeypatch):
|
|
571
|
+
m = fresh_mirror
|
|
572
|
+
calls = _bump_rev_on_read(m, monkeypatch, times=99)
|
|
573
|
+
r = client(m, retry_attempts=3).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'})
|
|
574
|
+
assert r.status_code == 503 and len(calls) == 3
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def test_no_store_read_happens_after_verify(fresh_mirror, monkeypatch):
|
|
578
|
+
m = fresh_mirror
|
|
579
|
+
real_verify, real_fill, real_get = MongoStore.verify, MongoStore._fill, MongoStore.get
|
|
580
|
+
verified = []
|
|
581
|
+
|
|
582
|
+
def verify(store):
|
|
583
|
+
real_verify(store)
|
|
584
|
+
store._test_verified = True # on the object: id() values are reused once a store is freed
|
|
585
|
+
verified.append(1)
|
|
586
|
+
|
|
587
|
+
def guard(real):
|
|
588
|
+
def inner(store, *a, **kw):
|
|
589
|
+
assert not getattr(store, '_test_verified', False), 'the store was read after verify()'
|
|
590
|
+
return real(store, *a, **kw)
|
|
591
|
+
|
|
592
|
+
return inner
|
|
593
|
+
|
|
594
|
+
monkeypatch.setattr(MongoStore, 'verify', verify)
|
|
595
|
+
monkeypatch.setattr(MongoStore, '_fill', guard(real_fill))
|
|
596
|
+
monkeypatch.setattr(MongoStore, 'get', guard(real_get))
|
|
597
|
+
c = client(m)
|
|
598
|
+
for path, params in [
|
|
599
|
+
(_sf_url(m), {'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'}),
|
|
600
|
+
(_sf_url(m), {'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z', 'f': 'CSV'}),
|
|
601
|
+
(f'/collections/{cid(m, "gh")}/area', {'coords': POLY_EDGE, 'datetime': '2020-01-01T00:00Z'}),
|
|
602
|
+
(f'/collections/{cid(m, "sf")}/locations', {}),
|
|
603
|
+
(f'/collections/{cid(m, "sf")}', {}),
|
|
604
|
+
('/collections', {}),
|
|
605
|
+
]:
|
|
606
|
+
assert c.get(path, params=params).status_code == 200
|
|
607
|
+
assert verified
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
@pytest.mark.parametrize('kind', ['413', '204', '404'])
|
|
611
|
+
def test_answers_computed_from_the_store_are_verified_too(fresh_mirror, monkeypatch, kind):
|
|
612
|
+
"""A 413, 204 or 404 read across an apply is retried, like a 200 (the rev bump lands before verify())."""
|
|
613
|
+
m = fresh_mirror
|
|
614
|
+
real_snapshot = read.snapshot_attrs
|
|
615
|
+
attempts = []
|
|
616
|
+
|
|
617
|
+
def bump_once(ds):
|
|
618
|
+
out = real_snapshot(ds)
|
|
619
|
+
attempts.append(1)
|
|
620
|
+
if len(attempts) == 1:
|
|
621
|
+
m.admin[DATASETS].update_one({'_id': m.world.dvid['sf']}, {'$inc': {'rev': 1}})
|
|
622
|
+
return out
|
|
623
|
+
|
|
624
|
+
monkeypatch.setattr(read, 'snapshot_attrs', bump_once)
|
|
625
|
+
url, params, cfg = {
|
|
626
|
+
'413': (f'/collections/{cid(m, "sf")}/area', {'coords': POLY_EDGE}, {'max_values': 1}),
|
|
627
|
+
'204': (_sf_url(m), {'datetime': '2021-01-01T00:00Z'}, {}),
|
|
628
|
+
'404': (f'/collections/{cid(m, "sf")}/locations/nope', {}, {}),
|
|
629
|
+
}[kind]
|
|
630
|
+
r = client(m, **cfg).get(url, params=params)
|
|
631
|
+
assert r.status_code == int(kind) and len(attempts) == 2
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def test_a_retired_dataset_answers_404(fresh_mirror):
|
|
635
|
+
m = fresh_mirror
|
|
636
|
+
mirror_mod.retire(m.rdb, m.world.dvid['sf'])
|
|
637
|
+
assert client(m).get(_sf_url(m)).status_code == 404
|
|
638
|
+
assert client(m).get(f'/collections/{cid(m, "sf")}').status_code == 404
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def test_retiring_the_served_version_serves_the_other_one(fresh_mirror):
|
|
642
|
+
m = fresh_mirror
|
|
643
|
+
mirror_mod.retire(m.rdb, m.world.dvid['pv2'])
|
|
644
|
+
r = client(m).get(f'/collections/{cid(m, "pv1")}')
|
|
645
|
+
assert r.status_code == 200 and r.headers['etag'].startswith(f'"{m.world.dvid["pv1"]}-')
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def test_a_version_retired_mid_request_is_re_resolved(fresh_mirror, monkeypatch):
|
|
649
|
+
m = fresh_mirror
|
|
650
|
+
real_snapshot = read.snapshot_attrs
|
|
651
|
+
seen = []
|
|
652
|
+
|
|
653
|
+
def retire_once(ds):
|
|
654
|
+
out = real_snapshot(ds)
|
|
655
|
+
seen.append(1)
|
|
656
|
+
if len(seen) == 1:
|
|
657
|
+
mirror_mod.retire(m.rdb, m.world.dvid['pv2'])
|
|
658
|
+
return out
|
|
659
|
+
|
|
660
|
+
monkeypatch.setattr(read, 'snapshot_attrs', retire_once)
|
|
661
|
+
sid = station_id(m, 'pv1', 'A')
|
|
662
|
+
r = client(m).get(f'/collections/{cid(m, "pv1")}/locations/{sid}', params={'datetime': '2020-01-01T00:00Z'})
|
|
663
|
+
assert r.status_code == 200 and r.headers['etag'].startswith(f'"{m.world.dvid["pv1"]}-')
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
def test_a_missing_dataset_answers_503_and_is_left_out_of_the_listing_alone(fresh_mirror):
|
|
667
|
+
m = fresh_mirror
|
|
668
|
+
m.admin[DATASETS].update_one({'_id': m.world.dvid['sf']}, {'$set': {'missing': True}})
|
|
669
|
+
c = client(m)
|
|
670
|
+
r = c.get(_sf_url(m))
|
|
671
|
+
assert r.status_code == 503 and 'retry-after' in r.headers
|
|
672
|
+
ids = [col['id'] for col in c.get('/collections').json()['collections']]
|
|
673
|
+
assert cid(m, 'sf') not in ids and cid(m, 'gh') in ids and cid(m, 'pv1') in ids
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def test_a_poisoned_cached_chunk_answers_500(fresh_mirror):
|
|
677
|
+
m = fresh_mirror
|
|
678
|
+
dvid = m.world.dvid['sf']
|
|
679
|
+
entry = m.admin[ENTRIES].find_one({'d': dvid, 'k': 'streamflow!0.0'})
|
|
680
|
+
m.admin[CHUNKS].insert_one(
|
|
681
|
+
{
|
|
682
|
+
'_id': chunk_id(dvid, entry['u'], 'streamflow!0.0', entry['ts']),
|
|
683
|
+
'v': b'not zstd at all',
|
|
684
|
+
'n': 15,
|
|
685
|
+
't': datetime.datetime.now(datetime.UTC),
|
|
686
|
+
}
|
|
687
|
+
)
|
|
688
|
+
r = client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T03:00Z'})
|
|
689
|
+
assert r.status_code == 500
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def test_the_deadline_answers_503(fresh_mirror):
|
|
693
|
+
r = client(fresh_mirror, request_deadline_seconds=0).get(_sf_url(fresh_mirror))
|
|
694
|
+
assert r.status_code == 503 and r.json()['code'] == 'Deadline'
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
# ── the role ────────────────────────────────────────────────────────────────────────────────────
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def test_the_api_role_reads_and_fills_the_cache_and_writes_nothing_else(fresh_mirror):
|
|
701
|
+
m = fresh_mirror
|
|
702
|
+
dvid = m.world.dvid['sf']
|
|
703
|
+
before = m.admin[CHUNKS].count_documents({})
|
|
704
|
+
assert client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-02T00:00Z'}).status_code == 200
|
|
705
|
+
assert m.admin[CHUNKS].count_documents({}) > before, 'the request filled no cache document'
|
|
706
|
+
for op in (
|
|
707
|
+
lambda: m.adb[DATASETS].update_one({'_id': dvid}, {'$set': {'rev': 0}}),
|
|
708
|
+
lambda: m.adb[ENTRIES].delete_one({'d': dvid}),
|
|
709
|
+
lambda: m.adb['catalogue'].delete_one({'_id': dvid}),
|
|
710
|
+
lambda: m.adb[CHUNKS].delete_many({}),
|
|
711
|
+
):
|
|
712
|
+
with pytest.raises(OperationFailure):
|
|
713
|
+
op()
|
|
714
|
+
assert check_role(m.adb)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def test_a_role_without_insert_is_reported_at_error(fresh_mirror, mongo_admin, mongo_admin_uri, caplog):
|
|
718
|
+
m = fresh_mirror
|
|
719
|
+
privs = [
|
|
720
|
+
{'resource': {'db': m.name, 'collection': c}, 'actions': ['find']}
|
|
721
|
+
for c in ('datasets', 'entries', 'catalogue', 'chunks')
|
|
722
|
+
]
|
|
723
|
+
mongo_admin[m.name].command('createRole', 'no_insert', privileges=privs, roles=[])
|
|
724
|
+
mongo_admin[m.name].command('createUser', 'api2', pwd='pw2', roles=[{'role': 'no_insert', 'db': m.name}])
|
|
725
|
+
cl = pymongo.MongoClient(user_uri(mongo_admin_uri, m.name, 'api2', 'pw2'), tz_aware=True)
|
|
726
|
+
try:
|
|
727
|
+
with caplog.at_level('ERROR'):
|
|
728
|
+
assert not check_role(cl[m.name])
|
|
729
|
+
assert any('insert on chunks' in rec.getMessage() for rec in caplog.records if rec.levelname == 'ERROR')
|
|
730
|
+
finally:
|
|
731
|
+
cl.close()
|
|
732
|
+
mongo_admin[m.name].command('dropUser', 'api2')
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def test_the_refresher_cli_imports_neither_cfdb_nor_fastapi():
|
|
736
|
+
code = 'import sys, envlib_api.cli; print(sorted(m for m in ("cfdb", "fastapi", "pyproj", "envlib_api.api") if m in sys.modules))'
|
|
737
|
+
out = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True, check=True).stdout.strip()
|
|
738
|
+
assert out == '[]'
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def test_resolve_never_answers_for_an_unserved_dataset_type(mirror):
|
|
742
|
+
assert resolve.latest(mirror.adb, 'nope') is None
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def test_json_has_no_nan_tokens(mirror):
|
|
746
|
+
url = f'/collections/{cid(mirror, "sf")}/locations/{station_id(mirror, "sf", "B")}'
|
|
747
|
+
r = client(mirror).get(url, params={'datetime': '2020-01-02T00:00Z/2020-01-03T00:00Z'})
|
|
748
|
+
assert b'NaN' not in r.content
|
|
749
|
+
orjson.loads(r.content)
|
|
750
|
+
json.loads(r.content)
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
# ── a remote ahead of the mirror, and an integrity fault (on a world of their own) ──────────────
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
class BuildCounter:
|
|
757
|
+
def __init__(self, monkeypatch):
|
|
758
|
+
self.n = 0
|
|
759
|
+
real = MongoStore.__init__
|
|
760
|
+
counter = self
|
|
761
|
+
|
|
762
|
+
def init(store, *a, **kw):
|
|
763
|
+
counter.n += 1
|
|
764
|
+
real(store, *a, **kw)
|
|
765
|
+
|
|
766
|
+
monkeypatch.setattr(MongoStore, '__init__', init)
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def test_a_remote_ahead_of_the_mirror_answers_503_after_one_attempt(small_mirror, monkeypatch):
|
|
770
|
+
"""A push the refresher has not applied yet: only its next poll helps, so no retry is spent."""
|
|
771
|
+
m = small_mirror
|
|
772
|
+
w = m.world
|
|
773
|
+
with cfdb.open_edataset(w.conn('sf'), w.tmp / 'sf.cfdb', flag='w') as ds:
|
|
774
|
+
ds['streamflow'][0, 0:24] = np.full((1, 24), 3.25)
|
|
775
|
+
assert ds.push()
|
|
776
|
+
builds = BuildCounter(monkeypatch)
|
|
777
|
+
r = client(m, retry_attempts=3).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'})
|
|
778
|
+
assert r.status_code == 503 and r.headers['retry-after'] == '60' and builds.n == 1
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def test_a_chunk_missing_from_an_unchanged_remote_answers_500(small_mirror):
|
|
782
|
+
m = small_mirror
|
|
783
|
+
w = m.world
|
|
784
|
+
b3 = boto3.client(
|
|
785
|
+
's3', endpoint_url=w.url, aws_access_key_id='test', aws_secret_access_key='test', region_name='us-east-1'
|
|
786
|
+
)
|
|
787
|
+
b3.delete_object(Bucket=w.bucket, Key=f'{w.prefix}/sf/streamflow!0.0')
|
|
788
|
+
r = client(m).get(_sf_url(m), params={'datetime': '2020-01-01T00:00Z/2020-01-01T05:00Z'})
|
|
789
|
+
assert r.status_code == 500 and r.json()['code'] == 'IntegrityError'
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def test_a_version_retired_between_resolving_and_building_is_re_resolved(fresh_mirror, monkeypatch):
|
|
793
|
+
"""The store build meets the tombstone (RemoteMissingError); another version is listed, so retry."""
|
|
794
|
+
m = fresh_mirror
|
|
795
|
+
real_latest = resolve.latest
|
|
796
|
+
calls = []
|
|
797
|
+
|
|
798
|
+
def latest_then_retire(db, dataset_id):
|
|
799
|
+
doc = real_latest(db, dataset_id)
|
|
800
|
+
calls.append(doc['_id'] if doc else None)
|
|
801
|
+
if len(calls) == 1:
|
|
802
|
+
mirror_mod.retire(m.rdb, m.world.dvid['pv2'])
|
|
803
|
+
return doc
|
|
804
|
+
|
|
805
|
+
monkeypatch.setattr(resolve, 'latest', latest_then_retire)
|
|
806
|
+
r = client(m).get(f'/collections/{cid(m, "pv1")}')
|
|
807
|
+
assert r.status_code == 200 and r.headers['etag'].startswith(f'"{m.world.dvid["pv1"]}-')
|
|
808
|
+
assert calls[0] == m.world.dvid['pv2'] and m.world.dvid['pv1'] in calls
|